-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsetup_gf_tools_arctic.py
2356 lines (1691 loc) · 88.7 KB
/
setup_gf_tools_arctic.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
#coding=utf-8
import os.path as op
import os
import sys
from sys import *
from os import *
import math
import cmath
import re
import scipy
import string
import numpy
from numpy import *
from scipy.io import read_array, write_array
import shutil
import ConfigParser
from scipy.linalg import *
from scipy import io as s_io
import random as rdm
#import pickle as pp
from scipy.integrate import simps as simps
from subprocess import *
import pyrocko.io as pio
import pyrocko.util as pu
import pyrocko.trace as ptc
import Scientific.IO.NetCDF as sioncdf
import time
import calendar as cldr
import numpy.random as nr
import pymseed
#----------------------------------------------------------------------
total_length = 36
#TODO: source indizes bei 1 anfangen lassen !!!!
#----------------------------------------------------------------------
pi = math.pi
#Earth's radius in metres
R = 6371000
#Conversion of degrees to/from radians
rad_to_deg = 180./pi
#accuracy factor - needed in comparison of time axes
accuracy = 0.001
#numerical accuracy
epsilon = 1e-8
#----------------------------------------------------------------------
_debug = 0
import code
import pdb
console = code.InteractiveConsole()
#----------------------------------------------------------------------
def read_in_config_file(filename):
"""Reads given config-file for setup GF-DB.
input:
-- filename (absolute or relative))
output:
-- configuration-dictionary
"""
configfile = path.abspath(path.realpath(filename))
print 'reading config_file...(%s)'%configfile
#set up configuration-dictionary
config = ConfigParser.ConfigParser()
#read in configuration-file
config.read(configfile)
cfg = dict()
#read in key-value pairs
sec = config.sections()
for s in sec:
o = config.options(s)
for oi in o:
oi_v = config.get(s,oi)
cfg[oi] = oi_v
if _debug:
print '%s \t\t = \t %s'%(str(oi),str(oi_v))
zdown_key = cfg.get('change_2_Zdown',0)
if int(round(float(zdown_key))) == 1:
cfg['change_2_Zdown'] = 1
else:
cfg['change_2_Zdown'] = 0
#working paths:
base_dir = path.abspath(path.realpath(cfg['base_dir']))
gf_dir = path.abspath(path.realpath(path.join(cfg['base_dir'],'DB','GF')))
data_dir = path.abspath(path.realpath(path.join(base_dir, cfg['data_dir'])))
#data input location:
data_dir_in = path.abspath(path.realpath(path.join(cfg['base_dir'],cfg['data_dir'])))
# Green's functions input location
gfdb_base_dir = path.abspath(path.realpath(cfg['gf_db_base_dir'] ))
gf_dir_input = path.abspath(path.realpath(path.join(gfdb_base_dir,cfg['gf_dir_input'] )))
# directory for temporary files:
temp_dir = path.abspath(path.realpath(path.join(cfg['base_dir'], 'temp' ) ))
# directory for temporary collecting suited GFs
temp_gf_dir = path.abspath(path.realpath(path.join(temp_dir,'gf_collected')))
if (not path.exists( base_dir ) ):
os.makedirs(base_dir)
if (not path.exists(gf_dir)):
os.makedirs(gf_dir)
if (not path.exists(data_dir) ):
os.makedirs(data_dir)
if (not path.exists(temp_dir)):
os.makedirs(temp_dir)
if (not path.exists(temp_gf_dir)):
os.makedirs(temp_gf_dir)
cfg['base_dir'] = base_dir
cfg['gf_dir'] = gf_dir
cfg['gf_dir_input'] = gf_dir_input
cfg['gfdb_base_dir'] = gfdb_base_dir
cfg['data_dir'] = data_dir
cfg['data_dir_in'] = data_dir_in
cfg['temporary_directory'] = temp_dir
cfg['temp_dir'] = temp_dir
cfg['temp_gf_dir'] = temp_gf_dir
number_gfs = int(float(cfg.get('number_of_gf',0)))
if not int(number_gfs) in [8,10]:
cfg['number_of_gf'] = 8
return cfg
#----------------------------------------------------------------------
def set_GF_parameters(cfg):
print 'setting parameters...'
# event- and window- times:
eventtime = read_datetime_to_epoch(cfg['event_id'])
cfg['event_datetime_in_epoch'] = eventtime
current_year = time.gmtime(eventtime)[0]
cfg['current_year'] = current_year
current_day = time.gmtime(eventtime)[7]
cfg['current_day'] = current_day
parent_data_directory = path.realpath(path.abspath( path.join( str(cfg['data_dir']))))
# if (not path.exists(parent_data_directory)):
# print 'could not find data directory %s'%(parent_data_directory)
# os.makedirs(parent_data_directory)
# print 'dummy directory artificially set up'
cfg['parent_data_directory'] = parent_data_directory
if cfg.has_key('network_names'):
list_of_all_networks = cfg['network_names']
else:
cfg['network_names'] = ''
list_of_all_networks = cfg['network_names']
nw_list_raw = list_of_all_networks.split(',')
list_of_all_nw = []
for ii in nw_list_raw:
dummy_element = ii.strip()
dummy_element = dummy_element.upper()
list_of_all_nw.append(dummy_element)
cfg['list_of_networks'] = list_of_all_nw
list_of_all_networks = cfg['network_names']
if cfg.has_key('location_names'):
list_of_all_locations = cfg['location_names']
else:
cfg['location_names'] = ''
list_of_all_locations = cfg['location_names']
loc_list_raw = list_of_all_locations.split(',')
list_of_all_loc = []
for ii in loc_list_raw:
dummy_element = ii.strip()
dummy_element = dummy_element.upper()
list_of_all_loc.append(dummy_element)
cfg['list_of_locations'] = list_of_all_loc
if cfg.has_key('list_of_all_channels'):
list_of_all_channels_raw_string = cfg['list_of_all_channels']
else:
cfg['list_of_all_channels'] = 'BHN,BHE,BHZ'
list_of_all_channels_raw_string = cfg['list_of_all_channels']
channel_list_raw = list_of_all_channels_raw_string.split(',')
list_of_all_channels = []
for ii in channel_list_raw:
dummy_element = ii.strip()
dummy_element = dummy_element.upper()
list_of_all_channels.append(dummy_element)
cfg['list_of_channels'] = list_of_all_channels
# building config-dict entry 'channel_index_dictionary'
if not make_dict_channels_indices(cfg):
print 'ERROR'
exit()
# building config-dict entry 'grid_coordinates'
if not set_sourcepoint_configuration(cfg):
print 'ERROR in setting of sourcepoints'
exit()
#building config-dict entries 'station_coordinate_dictionary'(dict), 'station_index_dictionary'(dict),'list_of_stations'(list),'station_coordinates'(array)
if not set_station_configuration(cfg):
print 'ERROR in setting of stations '
exit()
#building config-dict entries 'receiver_nslc_dictionary', 'list_of_receivers', 'receiver_index_dictionary'
if not set_receiver_names(cfg):
print 'ERROR in setting of receiver names'
exit()
return 1
#---------------------------------------------------------------------
def read_datetime_to_epoch(datetime):
#TODO ersetze timie durch calendar
import calendar as cc
if len(datetime.split('.')) == 2:
milisecs = float('0.'+datetime.split('.')[1])
else:
milisecs = 0.
date = datetime.split('.')[0]
#print date,'\n'
format = '%Y-%m-%dT%H:%M:%S'
time_tuple = time.strptime(date,format)
epoch_seconds = time.mktime(time_tuple) - time.altzone + milisecs
return epoch_seconds
#---------------------------------------------------------------------
def make_dict_channels_indices(cfg):
list_of_channels = cfg['list_of_channels']
channel_index_dict ={}
for uu in list_of_channels:
if uu.endswith('N'):
channel_index_dict[uu] = 0
elif uu.endswith('E'):
channel_index_dict[uu] = 1
elif uu.endswith('Z'):
channel_index_dict[uu] = 2
else:
print 'ERROR 234'
exit()
channel_index_dict['0'] = 'N'
channel_index_dict['1'] = 'E'
channel_index_dict['2'] = 'Z'
channel_index_dict['N'] = 0
channel_index_dict['E'] = 1
channel_index_dict['Z'] = 2
channel_index_dict['n'] = 0
channel_index_dict['e'] = 1
channel_index_dict['z'] = 2
cfg['channel_index_dictionary'] = channel_index_dict
return 1
#---------------------------------------------------------------------
def set_receiver_names(cfg):
lo_stat = cfg['list_of_stations']
lo_chan = cfg['list_of_channels']
lo_loc = cfg['list_of_locations']
lo_nw = cfg['list_of_networks']
r_nslc_dict = {}
reclist = []
rec_index_dict = {}
idx_count = 1
for idx_nw in lo_nw:
for idx_stat in lo_stat:
for idx_loc in lo_loc:
for idx_chan in lo_chan:
temp_dict = {}
temp_dict['network'] = idx_nw
temp_dict['station'] = idx_stat
temp_dict['location'] = idx_loc
temp_dict['channel'] = idx_chan
receivername = '%s.%s.%s.%s'%(idx_nw,idx_stat,idx_loc,idx_chan)
rec_index_dict[receivername] = idx_count
rec_index_dict[str(idx_count)] = receivername
reclist.append(receivername)
r_nslc_dict[receivername] = temp_dict
idx_count += 1
cfg['receiver_nslc_dictionary'] = r_nslc_dict
cfg['list_of_receivers'] = reclist
cfg['receiver_index_dictionary'] = rec_index_dict
return 1
#---------------------------------------------------------------------
def set_station_configuration_old(cfg):
print 'setting station coordinates...'
station_coords_filename = path.realpath(path.abspath( path.join(cfg['base_dir'],cfg['station_coords_file']) ))
if int(cfg['use_station_file']):
if path.isfile(station_coords_filename):
print 'by reading from existing file:\n',station_coords_filename
else:
station_coords_filename_in = path.realpath(path.abspath( path.join(cfg['base_dir'],cfg['station_coords_file'])))
if path.isfile(station_coords_filename_in):
print 'by reading from file:\n',station_coords_filename_in
shutil.copy(station_coords_filename_in,station_coords_filename)
else:
exit('station coordinate file %s not found '%(station_coords_filename_in))
if not read_station_coordinates(cfg):
exit('ERROR! Could not read station coordinates from file %s !\n'%(station_coords_filename))
#else:
# exit( 'ERROR - station coordinate file not found !\n Please provide file %s !\n' %(station_coords_filename))
else:
#print 'by building artificial station grid (spiral shaped) using specifications in config file\n'
print 'by building artificial station grid (concentric circular shaped - 5 circles, each 8 stations) using specifications in config file\n'
#-------------
# reading central latitude from config file
central_latitude_raw_string = cfg['central_latitude']
central_latitude_raw = central_latitude_raw_string.split(',')
if len(central_latitude_raw) == 3 or len(central_latitude_raw) == 1 :
for central_latitude_raw_element in central_latitude_raw:
dummy5 = central_latitude_raw_element.split('.')
if not ( len(dummy5) in [1,2]):
print 'ERROR!! Wrong coordinate format for latitude of sourcepoint grid center!!!'
exit()
for dummy5_element in dummy5:
if not ( dummy5_element.isdigit() ):
print 'ERROR!! Wrong coordinate format for latitude of sourcepoint grid center!!!'
exit()
if len(central_latitude_raw) == 3:
central_latitude_deg = float( float( central_latitude_raw[0]) + (1./60. * ( float(central_latitude_raw[1]) + (1./60. * float(central_latitude_raw[2]) ))))
else:
central_latitude_deg = float(central_latitude_raw[0])
#-------------
# reading central longitude from config file
central_longitude_raw_string = cfg['central_longitude']
central_longitude_raw = central_longitude_raw_string.split(',')
if len(central_longitude_raw) == 3 or len(central_longitude_raw) == 1 :
for central_lonitude_raw_element in central_longitude_raw:
dummy5 = central_lonitude_raw_element.split('.')
if not ( len(dummy5) in [1,2]):
print 'ERROR!! Wrong coordinate format for longitude of sourcepoint grid center!!!'
exit()
for dummy5_element in dummy5:
if not ( dummy5_element.isdigit() ):
print 'ERROR!! Wrong coordinate format for longitude of sourcepoint grid center!!!'
exit()
if len(central_longitude_raw) == 3:
central_longitude_deg = float( float( central_longitude_raw[0]) + (1./60. * ( float(central_longitude_raw[1]) + (1./60. * float(central_longitude_raw[2]) ))))
else:
central_longitude_deg = float(central_longitude_raw[0])
lat0 = central_latitude_deg
lon0 = central_longitude_deg
distmin = int(cfg['stat_dist_min'])
diststep = int(cfg['stat_radial_dist_step'])
station_index_dict ={}
# --------------------
# set receivers/stations
# either read from file
if cfg.has_key('list_of_all_stations'):
list_of_stations_raw_string = cfg['list_of_all_stations']
station_list_raw = list_of_stations_raw_string.split(',')
list_of_stations = []
count = 1
for ii in station_list_raw:
dummy_element = ii.strip()
dummy_element = dummy_element.upper()
list_of_stations.append(dummy_element)
index = count
station_coordinate_dict[dummy_element] = index
station_coordinate_dict[str(index)] = dummy_element
count += 1
# or build:
else:
if not cfg.has_key('n_stations'):
print "ERROR! Either provide number of stations as 'n_stations' or give 'list_of_all_stations'"
raise SystemExit
else:
list_of_stations=[]
number_of_stations = int(cfg['n_stations'])
chars = 'abcdefghijklmnopqrstuvwxyz'
for jj in xrange(number_of_stations):
charslist = ''.join( [ chars[jj] ] + [ rdm.choice(chars) for i in xrange(4) ])
station = charslist.upper()
list_of_stations.append(station)
station_index = jj
station_index_dict[station] = jj
station_index_dict[str(jj)] = station
s_number = len(list_of_stations)
stat_coords = zeros((s_number,4),float)
for idx_r in xrange(s_number):
azimuth = (idx_r + 1) * 350./float(s_number)
dist = float(distmin + idx_r * diststep)
dist_north = dist * cos(azimuth / rad_to_deg)
dist_east = dist * sin(azimuth / rad_to_deg)
lat_shift = dist_north * rad_to_deg /R
lat_rec = lat0 + lat_shift
lon_shift = dist_east * rad_to_deg / (R * sin((90.-lat_rec)/rad_to_deg))
lon_rec = lon0 + lon_shift
stat_coords[idx_r,0] = int(idx_r)
stat_coords[idx_r,1] = lat_rec
stat_coords[idx_r,2] = lon_rec
stat_coords[idx_r,3] = 0.
rec_co_file = file(station_coords_filename,'w')
stat_co_conf = ConfigParser.ConfigParser()
station_coordinate_dict = {}
for hh in xrange(s_number):
temp_dict={}
stat_idx = int(stat_coords[hh,0])
stationname = station_index_dict[str(stat_idx)]
lat = stat_coords[hh,1]
lon = stat_coords[hh,2]
stat_co_conf.add_section(stationname)
stat_co_conf.set(stationname,'lat',str(lat))
stat_co_conf.set(stationname,'lon',str(lon))
stat_co_conf.set(stationname,'index',str(stat_idx))
temp_dict['lat'] = lat
temp_dict['lon'] = lon
temp_dict['index'] = stat_idx
station_coordinate_dict[stationname] = temp_dict
#------------------------------
dist,azi,bazi = distance_azi_backazi([lat0,lon0],[lat,lon])
vp_max = cfg.get('vpmax',30000.)
vs_min = cfg.get('vsmin',10.)
stretch_factor= cfg.get('stretch_factor',1.5)
model_tmin = dist/vp_max
largest_depth = max(abs( cfg['grid_coordinates'][:,2]))
stretch_factor = float(cfg.get('stretch_factor',1.5))
model_tmax = stretch_factor*sqrt(dist**2+largest_depth**2)/vs_min
effective_window = model_tmax - model_tmin
# expansion of section
model_tmin_eff = model_tmin - 3./74.*effective_window
#window cannot start before t=0:
if model_tmin_eff < 0:
model_tmin_eff = 0
model_tmax_eff = model_tmax + 3./74.*effective_window
#set dictionary-entry for curent station
tmin_tmax_dict[stationname] = [model_tmin_eff ,model_tmax_eff]
cfg['stations_tmin_tmax'] = tmin_tmax_dict
#------------------------------
stat_co_conf.write(rec_co_file)
rec_co_file.close()
cfg['list_of_stations'] = list_of_stations
cfg['station_coordinates'] = stat_coords
cfg['station_coordinate_dictionary'] = station_coordinate_dict
cfg['station_index_dictionary'] = station_index_dict
print " station <-> coordinates dictionary set up " #in %s "%(cfg['station_coordinate_dictionary'] )
return 1
#---------------------------------------------------------------------
def set_station_configuration(cfg):
print 'setting station coordinates...'
station_coords_filename = path.realpath(path.abspath( path.join(cfg['base_dir'],cfg['station_coords_file']) ))
if int(cfg['use_station_file']):
if path.isfile(station_coords_filename):
print 'by reading from existing file:\n',station_coords_filename
else:
station_coords_filename_in = path.realpath(path.abspath( path.join(cfg['base_dir'],cfg['station_coords_file'])))
if path.isfile(station_coords_filename_in):
print 'by reading from file:\n',station_coords_filename_in
shutil.copy(station_coords_filename_in,station_coords_filename)
else:
exit('station coordinate file %s not found '%(station_coords_filename_in))
if not read_station_coordinates(cfg):
exit('ERROR! Could not read station coordinates from file %s !\n'%(station_coords_filename))
#else:
# exit( 'ERROR - station coordinate file not found !\n Please provide file %s !\n' %(station_coords_filename))
else:
#print 'by building artificial station grid (spiral shaped) using specifications in config file\n'
print 'by building artificial station grid (concentric circular shaped - 5 circles, each 8 stations) using specifications in config file\n'
#-------------
# reading central latitude from config file
central_latitude_raw_string = cfg['central_latitude']
central_latitude_raw = central_latitude_raw_string.split(',')
if len(central_latitude_raw) == 3 or len(central_latitude_raw) == 1 :
for central_latitude_raw_element in central_latitude_raw:
dummy5 = central_latitude_raw_element.split('.')
if not ( len(dummy5) in [1,2]):
print 'ERROR!! Wrong coordinate format for latitude of sourcepoint grid center!!!'
exit()
for dummy5_element in dummy5:
if (not ( dummy5_element.isdigit() )) and (not(dummy5_element[0]=='-' and dummy5_element[1:] ) ):
print 'ERROR!! Wrong coordinate format for latitude of sourcepoint grid center!!!'
exit()
if len(central_latitude_raw) == 3:
central_latitude_deg = float( float( central_latitude_raw[0]) + (1./60. * ( float(central_latitude_raw[1]) + (1./60. * float(central_latitude_raw[2]) ))))
else:
central_latitude_deg = float(central_latitude_raw[0])
#-------------
# reading central longitude from config file
central_longitude_raw_string = cfg['central_longitude']
central_longitude_raw = central_longitude_raw_string.split(',')
if len(central_longitude_raw) == 3 or len(central_longitude_raw) == 1 :
for central_lonitude_raw_element in central_longitude_raw:
dummy5 = central_lonitude_raw_element.split('.')
if not ( len(dummy5) in [1,2]):
print 'ERROR!! Wrong coordinate format for longitude of sourcepoint grid center!!!'
exit()
for dummy5_element in dummy5:
if (not ( dummy5_element.isdigit() )) and (not(dummy5_element[0]=='-' and dummy5_element[1:] ) ):
print 'ERROR!! Wrong coordinate format for longitude of sourcepoint grid center!!!'
exit()
if len(central_longitude_raw) == 3:
central_longitude_deg = float( float( central_longitude_raw[0]) + (1./60. * ( float(central_longitude_raw[1]) + (1./60. * float(central_longitude_raw[2]) ))))
else:
central_longitude_deg = float(central_longitude_raw[0])
lat0 = central_latitude_deg
lon0 = central_longitude_deg
distmin = int(cfg['stat_dist_min'])
diststep = int(cfg['stat_radial_dist_step'])
print lat0, lon0
exit()
station_index_dict ={}
# --------------------
# set receivers/stations
n_circles = 5
circ_dists = [1,5,25,100,250]
n_stats_per_circ = 8
s_number = n_circles * n_stats_per_circ
# either read from file
if cfg.has_key('list_of_all_stations'):
list_of_stations_raw_string = cfg['list_of_all_stations']
station_list_raw = list_of_stations_raw_string.split(',')
list_of_stations = []
count = 1
for ii in station_list_raw:
dummy_element = ii.strip()
dummy_element = dummy_element.upper()
list_of_stations.append(dummy_element)
index = count
station_coordinate_dict[dummy_element] = index
station_coordinate_dict[str(index)] = dummy_element
count += 1
# or build:
else:
#if not cfg.has_key('n_stations'):
# print "ERROR! Either provide number of stations as 'n_stations' or give 'list_of_all_stations'"
# raise SystemExit
pass
stat_coords = zeros((s_number,4),float)
lo_stat_idx = 'ABCDE'
list_of_stations=[]
rec_co_file2 = file(station_coords_filename[:-4]+'.alpha','w')
for circ in arange(n_circles):
for az in arange(n_stats_per_circ):
jj = n_stats_per_circ * circ + az
idx_r = jj
azimuth = az * 45. #(idx_r + 1) * 350./float(s_number)
dist = float(circ_dists[circ])*1000 #float(distmin + idx_r * diststep))
dist_north = dist * cos(azimuth / rad_to_deg)
dist_east = dist * sin(azimuth / rad_to_deg)
lat_shift = dist_north * rad_to_deg /R
lat_rec = lat0 + lat_shift
lon_shift = dist_east * rad_to_deg / (R * sin((90.-lat_rec)/rad_to_deg))
lon_rec = lon0 + lon_shift
stat_coords[idx_r,0] = int(jj+1)
stat_coords[idx_r,1] = lat_rec
stat_coords[idx_r,2] = lon_rec
stat_coords[idx_r,3] = 0.
station = lo_stat_idx[circ]+str(az+1)
list_of_stations.append(station)
station_index_dict[station] = jj++1
station_index_dict[str(jj+1)] = station
rec_co_file2.write('%s \t %s \t %s \t 0 \n'%(station,lat_rec,lon_rec))
rec_co_file2.close()
rec_co_file = file(station_coords_filename,'w')
stat_co_conf = ConfigParser.ConfigParser()
station_coordinate_dict = {}
for hh in arange(s_number):
temp_dict={}
stat_idx = int(stat_coords[hh,0])
stationname = station_index_dict[str(stat_idx)]
lat = stat_coords[hh,1]
lon = stat_coords[hh,2]
stat_co_conf.add_section(stationname)
stat_co_conf.set(stationname,'lat',str(lat))
stat_co_conf.set(stationname,'lon',str(lon))
stat_co_conf.set(stationname,'index',str(stat_idx))
temp_dict['lat'] = lat
temp_dict['lon'] = lon
temp_dict['index'] = stat_idx
station_coordinate_dict[stationname] = temp_dict
stat_co_conf.write(rec_co_file)
rec_co_file.close()
cfg['list_of_stations'] = list_of_stations
cfg['station_coordinates'] = stat_coords
cfg['station_coordinate_dictionary'] = station_coordinate_dict
cfg['station_index_dictionary'] = station_index_dict
print " station <-> coordinates dictionary set up " #in %s "%(cfg['station_coordinate_dictionary'] )
return 1
#---------------------------------------------------------------------
def read_station_coordinates(cfg):
#station_coordinate_filename = cfg['station_coords_file']
station_coordinate_file = path.realpath(path.abspath(path.join(cfg['base_dir'], cfg['station_coords_file'] )))
if not path.isfile(station_coordinate_file):
exit( 'file with station coordinates not found !')
config_filehandler = ConfigParser.ConfigParser()
config_filehandler.read(station_coordinate_file)
list_of_stations = []
station_coordinate_dict = {}
station_index_dict = {}
lo_stat_index = []
sections = config_filehandler.sections()
for sec in sections:
list_of_stations.append(sec)
temp_lat_lon_dict ={}
options = config_filehandler.options(sec)
for opt in options:
value = config_filehandler.get(sec,opt)
if opt == 'lat' or opt == 'latitude' or opt == 'lon' or opt == 'longitude':
if opt == 'latitude':
opt = 'lat'
if opt == 'longitude':
opt = 'lon'
try:
lat_lon = value.split(',')
except:
print 'ERROR!! Wrong coordinate format for ',opt, ' of station ', sec,'!!!'
raise SystemExit
if len(lat_lon) == 3 or len(lat_lon) == 1 :
for lat_lon_element in lat_lon:
dummy3 = lat_lon_element.split('.')
if not ( len(dummy3) in [1,2]):
print 'ERROR!! Wrong coordinate format for ',opt, ' of station ', sec,'!!! '
exit()
for dummy3_element in dummy3:
try:
int(dummy3_element)
except:
print 'ERROR!! Wrong coordinate format for ',opt, ' of station ', sec,'!!!'
raise SystemExit
if len(lat_lon) == 3:
lat_lon_deg = float( float( lat_lon[0]) + (1./60. * ( float(lat_lon[1]) + (1./60. * float(lat_lon[2]) ))))
else:
lat_lon_deg = float(lat_lon[0])
temp_lat_lon_dict[opt] = lat_lon_deg
if opt == 'index' or opt == 'idx':
station_index_dict[sec] = int(value)
station_index_dict[value] = sec
temp_lat_lon_dict[opt] = value
if not len(temp_lat_lon_dict) == 3:
print 'coordinates of station ',sec, ' are wrong - latitude and/or longitude and/or index missing !!!!!'
exit()
station_coordinate_dict[sec] = temp_lat_lon_dict
#filling array 'stat_coords'
s_number = len(list_of_stations)
stat_coords = zeros((s_number,4),float)
tmin_tmax_dict = {}
for hh in arange(s_number):
stationname = station_index_dict[str(hh+1)]
temp_co_dict = station_coordinate_dict[stationname]
lat = float(temp_co_dict['lat'])
lon = float(temp_co_dict['lon'])
idx = int(temp_co_dict['index'])
stat_coords[hh,0] = int(idx)
stat_coords[hh,1] = lat
stat_coords[hh,2] = lon
#------------------------------
dist,azi,bazi = distance_azi_backazi([float(cfg['central_latitude']),float(cfg['central_longitude'])],[lat,lon])
vp_max = float(cfg.get('vpmax',30000.))
vs_min = float(cfg.get('vsmin',10.))
stretch_factor= float(cfg.get('stretch_factor',1.5))
model_tmin = dist/vp_max
largest_depth = max(abs( cfg['grid_coordinates'][:,2]))
stretch_factor = float(cfg.get('stretch_factor',1.5))
model_tmax = stretch_factor*sqrt(dist**2+largest_depth**2)/vs_min
effective_window = model_tmax - model_tmin
# expansion of section
model_tmin_eff = model_tmin - 3./74.*effective_window
#window cannot start before t=0:
if model_tmin_eff < 0:
model_tmin_eff = 0
model_tmax_eff = model_tmax + 3./74.*effective_window
#set dictionary-entry for curent station
tmin_tmax_dict[stationname] = [model_tmin_eff ,model_tmax_eff]
cfg['stations_tmin_tmax'] = tmin_tmax_dict
#------------------------------
cfg['station_coordinate_dictionary'] = station_coordinate_dict
cfg['station_index_dictionary'] = station_index_dict
cfg['list_of_stations'] = list_of_stations
cfg['station_coordinates'] = stat_coords
#save array for checking and plotting
#station_co_fn = 'station_coordinates.dat'
#station_co_file = path.abspath(path.realpath(path.join(cfg['base_dir'],station_co_fn)))
#savetxt(station_co_file,stat_coords,fmt=['%i','%.4f','%.4f','%.2f'])
print 'Station coordinates for %i stations ok!\n\n'%(s_number)
return 1
#---------------------------------------------------------------------
def set_sourcepoint_configuration(cfg):
"""
Setting geographical coordinates of source locations.
Indexing is done by looping over all source-points in the order (N,E,Z)
Input:
-- Config-dictionary
indirect Output:
-- File with coordinate-array (lat,lon,depth) in in base directory
-- array with source coordinates in config-dictionary
direct output:
-- control parameter
"""
print 'setting grid_coords...'
source_coords_filename = path.realpath(path.abspath( path.join(cfg['base_dir'],cfg['source_coords_file']) ))
northdim = int(cfg['northdim'])
eastdim = int(cfg['eastdim'])
depthdim = int(cfg['depthdim'])
northstep = int(cfg['northstep'])
eaststep = int(cfg['eaststep'])
depthstep = int(cfg['depthstep'])
N_N = int(2 * northdim + 1)
N_E = int(2 * eastdim + 1)
N_Z = int(depthdim)
N_tot = int(N_N * N_E * N_Z)
check_flag = 1
# if already existing and in right dimensions:
if path.isfile(source_coords_filename):
try:
File7 = file(source_coords_filename,'r')
grid_coords_array = loadtxt(File7, usecols=tuple(range(0,3)))
File7.close()
except:
print 'cannot read existing source coordinate file - generating new one'
check_flag = 0
if len(grid_coords_array) == N_tot:
print 'by reading from file:\n',source_coords_filename
else:
print 'existing source coordinate file has wrong number of entries - generating new file'
check_flag = 0
# otherwise set up new file:
if (not path.isfile(source_coords_filename)) or check_flag == 0 :
print 'by building source point grid (rectangular) using specifications in config file\n'
central_latitude_raw_string = cfg['central_latitude']
central_latitude_raw = central_latitude_raw_string.split(',')
if len(central_latitude_raw) == 3 or len(central_latitude_raw) == 1 :
for central_latitude_raw_element in central_latitude_raw:
dummy5 = central_latitude_raw_element.split('.')
if not ( len(dummy5) in [1,2]):
print 'ERROR!! Wrong coordinate format for latitude of sourcepoint grid center!!!'
exit()
for dummy5_element in dummy5:
if (not ( dummy5_element.isdigit() )) and (not(dummy5_element[0]=='-' and dummy5_element[1:] ) ) :
print 'ERROR!! Wrong coordinate format for latitude of sourcepoint grid center!!!'
exit()
if len(central_latitude_raw) == 3:
central_latitude_deg = float( float( central_latitude_raw[0]) + (1./60. * ( float(central_latitude_raw[1]) + (1./60. * float(central_latitude_raw[2]) ))))
else:
central_latitude_deg = float(central_latitude_raw[0])
central_longitude_raw_string = cfg['central_longitude']
central_longitude_raw = central_longitude_raw_string.split(',')
if len(central_longitude_raw) == 3 or len(central_longitude_raw) == 1 :
for central_lonitude_raw_element in central_longitude_raw:
dummy5 = central_lonitude_raw_element.split('.')
if not ( len(dummy5) in [1,2]):
print 'ERROR!! Wrong coordinate format for longitude of sourcepoint grid center!!!'
exit()
for dummy5_element in dummy5:
if (not ( dummy5_element.isdigit() )) and (not(dummy5_element[0]=='-' and dummy5_element[1:] ) ):
print 'ERROR!! Wrong coordinate format for longitude of sourcepoint grid center!!!'
exit()
if len(central_longitude_raw) == 3:
central_longitude_deg = float( float( central_longitude_raw[0]) + (1./60. * ( float(central_longitude_raw[1]) + (1./60. * float(central_longitude_raw[2]) ))))
else:
central_longitude_deg = float(central_longitude_raw[0])
lat0 = central_latitude_deg
lon0 = central_longitude_deg
depth0 = int(cfg['min_depth'])
list_of_source_points = []
coord_array_temp = zeros((N_N,N_E,N_Z, 3),float64)
grid_coords_array = zeros((N_tot, 3),float64)
if _debug:
count = 1
gp_count = 0
for z1 in (arange(N_Z)):
depth = z1 * depthstep + depth0
current_radius = float(R) - depth
for e2 in (arange(N_E) - eastdim):
for n3 in (arange(N_N) - northdim):
#lat = lat0 + ( n3 * northstep * rad_to_deg / current_radius)
north_distance = n3 * northstep
east_distance = e2 * eaststep
#angle in degrees w.r.t. north
angle = float((90-arctan2(north_distance,east_distance)*float(rad_to_deg)))%360
#effective distance on regular rectangular grid
distance = sqrt(float(north_distance) **2 + float(east_distance)**2 )
#needed for input to trigonometric functions
azimuth = float(angle)/rad_to_deg
angular_distance = distance/float(current_radius)
#calculate coordinates for current grid point
lat_rad = arcsin(sin(lat0/rad_to_deg)*cos(angular_distance) + cos(lat0/rad_to_deg)*sin(angular_distance)*cos(azimuth))
lat = lat_rad*rad_to_deg
lon_rad = lon0/rad_to_deg + arctan2( sin(azimuth)*sin(angular_distance)*cos(lat0/rad_to_deg), cos(angular_distance) - sin(lat0/rad_to_deg) * sin(lat/rad_to_deg) )
lon = lon_rad*rad_to_deg
#lon = lon0 + ( e2 * eaststep * rad_to_deg / current_radius / sin( (90-lat)/rad_to_deg ) )