-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy patharctic_tools_0_11.py
6589 lines (4773 loc) · 235 KB
/
arctic_tools_0_11.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 ipython
# coding=utf-8
#
#-*- coding: utf-8 -*-
#----------------------------------------------------------------------
# version 0.10 - 22.08.10 - LK -
#----------------------------------------------------------------------
#
#
# Functions for setting up a database of Green's functions for a
# - circular shaped configuration of receivers
# - rectangular setup of source-grid
# around a given centre (point, given in (lat,lon)-coordinates
#
# Function for setting up synthetic data-set for arbitrarily chosen source-point from source-grid
#
# All functions needed for SETUP_GF and ARCTIC
#
# contains:
#
# - read_in_config_file
#
# - set_source_grid
# - set_receiver
# - setup_db
# - source_coords
# - receiver_coords
# - s_r_azi_dist
# - calc_distance
# - neighbouring_distances
#
# - setup_synth_data
#.
#.
#----------------------------------------------------------------------
# to do
#.
#.
# korrektur der koordinatenberechung im rechtwinkligen Gitter
# rausschreiben des xml files
# einlesen der benoetigten daten bzgl der topographie
# neue GF datenbank
# "automatisches" erstellen eines config-files
# "konsistentes" aufrufen des codes (zeitschleife nicht noetig, wenn von conny aufgerufen)
#
#----------------------------------------------------------------------
#
# 'indirect output' : the result is written to the global config dictionary
#
#----------------------------------------------------------------------
import sys
import os
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
import cPickle as cP
from scipy.integrate import simps as simps
import Scientific.IO.NetCDF as sioncdf
import time
import calendar
from lxml import etree as xet
import pymseed
#----------------------------------------------------------------------
#complex_unit = complex(0,1)
pi = math.pi
#conversion from radians to/from degrees
rad_to_deg = 180./pi
#Earth's radius
R = 6371000
radius = R
#----------------------------------------------------------------------
global _debug
_debug = 1
_debug_plot = 0
_debug_print_on_screen = 1
import code
import pdb
#----------------------------------------------------------------------
#----------------------------------------------------------------------
def printf(format, *args):
sys.stdout.write(format % args)
#----------------------------------------------------------------------
#----------------------------------------------------------------------
def read_in_config_file(filename):
"""Reads given configuration file.
This has to have the structure
[section]
key = value
...
Names of sections do not matter - only for human reading.
input:
-- name of configuration file
output:
-- config dictionary
"""
print 'reading config_file...'
configfile = filename
#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
#setting paths:
base_dir = path.abspath(path.realpath(cfg['base_dir']))
gf_dir = path.abspath(path.realpath(path.join(cfg['base_dir'], cfg['gf_dir']) ))
data_dir = path.abspath(path.realpath(path.join(cfg['base_dir'], cfg['data_dir']) ))
temp_dir = path.abspath(path.realpath(path.join(cfg['base_dir'], 'temp' )))
plot_dir = path.abspath(path.realpath(path.join(cfg['base_dir'], 'plots' )))
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(plot_dir)):
os.makedirs(plot_dir)
cfg['gf_dir'] = gf_dir
cfg['GF_directory'] = gf_dir
cfg['data_dir'] = data_dir
cfg['parent_data_directory'] = data_dir
cfg['temp_dir'] = temp_dir
cfg['temporary_directory'] = temp_dir
cfg['plot_dir'] = plot_dir
if _debug:
for i in sort(cfg.keys()):
print '%s\t \t= \t%s'%(i, cfg[i])
return cfg
#----------------------------------------------------------------------
#----------------------------------------------------------------------
def bp_butterworth(data_in,sampling, cfg):
"""
Filters given 1-D data array in frequency domain with numpy inherited butterworth filter. Corner
frequencies are given in config dictionary.
input:
-- data
-- sampling in Hz
-- config dictionary
output:
-- frequency filtered data of same length
"""
# sampling in Hz
sampling_rate = sampling
deltat = 1./sampling_rate
length = float(cfg['time_window_length'])
lower_corner_freq = float(cfg['bp_lower_corner'])
upper_corner_freq = float(cfg['bp_upper_corner'])
order = int(float(cfg['bp_order']))
# setting the filter coefficients
(b,a ) = scipy.signal.butter(order,[corner*2.0*deltat for corner in (lower_corner_freq, upper_corner_freq) ], btype='band' )
data = data_in.astype(numpy.float64)
data -= numpy.mean(data)
# apply scipy filter
data_out = scipy.signal.lfilter(b,a,data)
return data_out
#----------------------------------------------------------------------
def bp_boxcar( in_data,sampling, cfg):
"""real-valued rectangular frequency filter for data and Green's functions.
TODO rename to bp_boxcar
input:
-- sampling in Hz
-- data as numpy array of floats
-- config dictionary
output:
-- frequency filtered data of same length
"""
f_up = float(cfg['bp_upper_corner'])
f_low = float(cfg['bp_lower_corner'])
data = in_data.astype(float64)
n = len(data)
fdata = numpy.fft.rfft(data)
nf = len(fdata)
df = 1./(n*sampling)
freqs = arange(nf)*df
fdata *= logical_and(f_low < freqs, freqs < f_up)
data = numpy.fft.irfft(fdata,n)
assert len(data) == n
out_data = real(data)
#check dimension of result:
if ( len(in_data) != len(out_data) ):
print "ERROR in filter-function !!!!"
raise SystemExit
#output of filtered data:
return out_data
#----------------------------------------------------------------------
#----------------------------------------------------------------------
def setup_A(cfg):
"""Gives array of correlation matrices A_(i,j) for combination of [source, station, component].
input:
-- config dictionary
indirect output:
-- correlation matrix array A[gp,s,c] in config dictionary
direct output:
-- control parameter '1'
"""
# read in all data via config dict:
gf = cfg['GF']
time_axis = cfg['time_axis_of_GF']
station_index_dict = cfg['station_index_dictionary']
stations_array = cfg['station_coordinates']
lo_chans = cfg['list_of_channels']
channel_index_dict = cfg['channel_index_dictionary']
lo_stations = cfg['list_of_stations']
lo_all_gridpoints = cfg['list_of_all_gridpoints']
if cfg.has_key('list_of_gridpoint_section'):
current_lo_gridpoints = cfg['list_of_gridpoint_section']
else:
current_lo_gridpoints = lo_all_gridpoints
n_gridpoints = len(current_lo_gridpoints)
n_stations = len(lo_stations)
filter_flag = int(cfg['filter_flag'])
# set filenames -- storing A for the current setting for later use:
# filename is coded by stations.
#If too many stations shortening of filename:
lo_stats = lo_stations
if len(lo_stats) > 10:
lo_stats = ['many','stations']
if filter_flag == 1 or filter_flag == 2 :
corr_mat_filename = 'bandpass_filtered_correlation_matrix_A_for_stations_'+'_'.join(lo_stats)+'.pp'
else:
corr_mat_filename = 'correlation_matrix_A_for_stations_'+'_'.join(lo_stats)+'.pp'
corr_mat_file_abs = path.realpath(path.abspath(path.join(cfg['temporary_directory'],corr_mat_filename)))
corr_mat_file = path.realpath(path.abspath(corr_mat_file_abs ))
# reset internal variable to original value
if len(lo_stats) == 2:
lo_stats = lo_stations
# calculate A and save to file:
try:
# if aleready existing just read in A from file
File1b = file(corr_mat_file,'r')
A = pp.load(File1b)
File1b.close()
print 'read in correlation matrix A...'
except:
print 'Calculating correlation matrix A...'
summation_key = int(cfg.get('summation_key',0))
if not (summation_key == 0 or summation_key == 1):
summation_key = 0
if _debug:
lo_added_receivers = []
if summation_key == 0:
#sum over all receivers (station-component-combinations)
A = zeros((6,6,n_gridpoints),float)
#loop over all sources, stations and components
for gp in arange(n_gridpoints):
dummy_matrix = zeros((6,6))
for station in lo_stats:
station_index = int(station_index_dict[station])-1
station_weight = stations_array[station_index,4]
for channel in lo_chans:
channel_index = int(channel_index_dict[channel])
dummy_matrix += calc_corr_mat(gp,station_index,channel_index,station_weight, time_axis, cfg)
if _debug:
receiver = '%s.%s'%(station,channel)
lo_added_receivers.append(receiver)
A[:,:,gp] = dummy_matrix
sys.stdout.write( 'A for gridpoint %4i of %4i set \r'%(gp+1,n_gridpoints))
if summation_key == 1:
A = zeros((6,6,n_gridpoints,3),float)
pass
if _debug:
set_of_added_receivers = sort(list(set(lo_added_receivers)))
#d_break(locals(),'AAAA')
File1b = file(corr_mat_file,'w')
pp.dump(A,File1b)
File1b.close()
# put matrix A into config dictionary
cfg['A'] = A
#print A[:,:,0],'\n'
#print A[:,:,-1],'\n'
#exit()
#return control value
return 1
#----------------------------------------------------------------------
#----------------------------------------------------------------------
def calc_corr_mat(gp_idx, station_idx, channel_idx,station_weight, time_axis, cfg):
"""Calculate correlation matrix of different Green functions.
Indizes are given w.r.t. the Greens functions tensor GF for the chosen selection of stations and gridpoints, all starting with '0'
input:
-- index of source (grid point index)
-- index of station
-- index of component
-- time axis
-- config dictionary
sampling_in_s
output:
-- correlation matrix A
"""
gf = cfg['GF']
A_gp_s_c = matrix(zeros((6,6), float))
sampling_in_Hz = float(cfg['gf_sampling_rate'])
sampling_in_s = 1./sampling_in_Hz
for i in xrange(6):
for j in xrange(i,6):
#calculate integrand by reading in pair of greens functions with indizes i,j
tmp2 = gf[station_idx, gp_idx, channel_idx, i,:]
tmp4 = gf[station_idx, gp_idx, channel_idx, j,:]
integrand = tmp2 * tmp4
#set up matrix-elements symmetrically:
A_gp_s_c[i,j] = station_weight * simps(integrand, dx=sampling_in_s)
A_gp_s_c[j,i] = A_gp_s_c[i,j]
# return whole matrix A[i=1...6,j=1...6] for fixed set (grid point (gp), station (s), component (c) )
return A_gp_s_c
#----------------------------------------------------------------------
#----------------------------------------------------------------------
def calc_inv_A(cfg):
"""Gives an array with the inverses 'inv_A[gp,s,c]' of the correlation matrices 'A[gp,s,c]'.
input:
-- config dictionary
indirect output:
Depending of mode of inversion ('summation_key') either a simple matrix or array of matrices
-- 0: summation over all receivers and all components - obtain matrix inv_A
TODO:
(-- 1: summation separated by components (k) - obtain array of 3 matrices inv_A[k])
direct output:
-- control parameter '1'
"""
A = cfg['A']
station_index_dict = cfg['station_index_dictionary']
channel_index_dict = cfg['channel_index_dictionary']
lo_chans = cfg['list_of_all_channels']
lo_stations = cfg['list_of_stations']
filter_flag = int(cfg['filter_flag'])
lo_stats = lo_stations
# filename gets too long for too many stations
if len(lo_stats) > 10:
lo_stats = ['many','stations']
#set filename for saving output
if filter_flag == 1 or filter_flag == 2:
inv_corr_mat_filename = 'bandpass_filtered_inverted_matrix_A_for_stations_'+'_'.join(lo_stats)+'.pp'
else:
inv_corr_mat_filename = 'inverted_matrix_A_for_stations_'+'_'.join(lo_stats)+'.pp'
inv_corr_mat_file_abs = path.realpath(path.abspath(path.join(cfg['temporary_directory'],inv_corr_mat_filename)))
inv_corr_mat_file = path.realpath(path.abspath(inv_corr_mat_file_abs ))
#if too many stations: reload stations list
if len(lo_stats) == 2:
lo_stats = lo_stations
# calculate inv_A if not existing:
try:
# if aleready existing just read in inv_ A from file
File1b = file(inv_corr_mat_file,'r')
inv_A = pp.load(File1b)
File1b.close()
print 'read in inverted correlation matrix inv_A...'
except:
print 'Inversion of matrices A:'
summation_key = int(cfg.get('summation_key',0))
if not (summation_key == 0 or summation_key == 1):
summation_key = 0
lo_all_gridpoints = cfg['list_of_all_gridpoints']
if cfg.has_key('list_of_gridpoint_section'):
current_lo_gridpoints= cfg['list_of_gridpoint_section']
else:
current_lo_gridpoints = lo_all_gridpoints
n_gridpoints = len(current_lo_gridpoints)
if summation_key == 0:
a_tmp2 = matrix(zeros((6,6),float))
a_tmp3 = matrix(zeros((6,6),float))
inv_A = zeros((6,6,n_gridpoints),float)
for gp in arange(n_gridpoints):
#inversion of the respective correlation matrix for each grid point
a_tmp2 = matrix(A[:,:,gp])
a_tmp3 = inv(a_tmp2)
inv_A[:,:,gp] = a_tmp3
if summation_key == 1:
a_tmp2 = matrix(zeros((6,6),float))
a_tmp3 = matrix(zeros((6,6),float))
inv_A = zeros((6,6,n_gridpoints,3),float)
pass
#save inv_A for further use in file
File1c = file(inv_corr_mat_file,'w')
pp.dump(inv_A,File1c)
File1c.close()
#save inv_A in config dictionary
cfg['inv_A'] = inv_A
#print inv_A[:,:,0],'\n'
#print inv_A[:,:,-1],'\n'
#exit()
if _debug:
print shape(inv_A)
#return control parameter
return 1
#----------------------------------------------------------------------
#----------------------------------------------------------------------
def calc_corr_vec(cfg):
"""Calculate array of correlation vectors of data and Green's function 'b[time_window,M_component,grid point]'.
input:
-- config dictionary
indirect output:
-- array of correlation vectors b
direct output:
-- control parameter
"""
data_array = cfg['data_array']
gf_array = cfg['GF']
print 'size of GF, data: ' ,shape(gf_array),shape(data_array)
time_array = cfg['data_time_axes_array']
lo_stations_w_data = cfg['list_of_stations_with_data']
filter_flag = int(cfg['filter_flag'])
lo_stats = lo_stations_w_data
# filename gets too long for too many stations
if len(lo_stats) > 10 :
lo_stats = ['many','stations']
#set filename for saving output
if filter_flag == 1 or filter_flag == 2 :
corr_vec_filename = path.realpath(path.abspath(path.join(cfg['temporary_directory'], 'bandpass_filtered_current_corr_vec_for_stations_'+'_'.join(lo_stats)+'.pp')))
elif int(cfg['filter_flag']) == 0:
corr_vec_filename = path.realpath(path.abspath(path.join(cfg['temporary_directory'], 'current_corr_vec_for_stations_'+'_'.join(lo_stats)+'.pp')))
else:
print 'ERROR!!! filter_flag must be "0" or "1" or "2"'
raise SystemExit
#if too many stations: reload stations list
if len(lo_stats) == 2 :
lo_stats = lo_stations_w_data
#load b from file if existing
try:
raise
File1d = file(corr_vec_filename,'r')
b = pp.load(File1d)
File1d.close()
print 'Reading array of correlation vectors "b" from file: ', corr_vec_filename
# otherwise calculation of b
except:
print 'Calculation of correlation vector array "b":...'
key = int(cfg['summation_key'])
filter_flag = int(cfg['filter_flag'])
sampling_in_s = 1./float(cfg['data_sampling_rate'])
if cfg.has_key('list_of_gridpoint_section'):
lo_gp = cfg['list_of_gridpoint_section']
else:
lo_gp = cfg['list_of_gridpoints']
n_gridpoints = len(lo_gp)
lo_receivers = cfg['list_of_receivers_with_data']
n_receivers = len(lo_receivers)
stations_array = cfg['station_coordinates']
channel_index_dict = cfg['channel_index_dictionary']
stat_idx_dict = cfg['station_index_dictionary']
cont_stat_index_dict = cfg['ContributingStation_index_dictionary']
receiver_index_dict = cfg['receiver_index_dictionary']
list_of_moving_window_starttimes = cfg['list_of_moving_window_starttimes']
number_of_window_steps = len(list_of_moving_window_starttimes)
# time axis
n_time = int(float(cfg['time_window_length'])*float(cfg['data_sampling_rate']) + 1 )
#temporary values, vector and integrand:
b_tmp = zeros((number_of_window_steps, n_gridpoints, n_receivers, 6),float)
int_tmp = zeros((n_gridpoints, n_receivers, 6, n_time),float)
if _debug:
lo_added_receivers = []
# loop over all time windows
for window_idx in arange(number_of_window_steps):
#loop over all receivers - combination of station and channel
for receiver in lo_receivers:
receiver_index = int(float( receiver_index_dict[receiver] ))
station_name = receiver.split('.')[0]
station_index = int(stat_idx_dict[station_name])-1
abs_station_index = int(stat_idx_dict[station_name])-1
station_weight = cfg['station_weights_dict'][station_name]#stations_array[abs_station_index,4]
channel = receiver.split('.')[1]
regex_check = re.compile(r'\w$')
channel_letter = regex_check.findall(channel)[0]
if _debug:
pass
#print receiver, station_name, channel_letter
channel_index = int(channel_index_dict[channel_letter])
tmp5 = station_weight * data_array[window_idx, receiver_index, :][:]
#loop over source points
for gp in arange(n_gridpoints):
gp_index = lo_gp[gp]-1
#loop over all M components
for m_component in xrange(6):
#read in green function and data:
#print station_index, gp_index, channel_index, m_component
tmp2 = gf_array[station_index, gp, channel_index, m_component,:][:]
#setup integrand:
int_tmp = tmp2 * tmp5
#
#calculate correlation vector by integrating with scipy internal Simpson rule:
b_tmp[window_idx, gp, receiver_index, m_component] = simps(int_tmp ,dx=sampling_in_s)
#visual check
if _debug_plot:
if gp == 50 and ( m_component == 4):
figure( 10 * (station_index+1) + channel_index )
plot(tmp2)
figure(100 + 10 * (station_index+1) + channel_index)
plot(tmp5)
print 'plotted gf(4) for station ',station_name,' and channel ',channel_letter, ' in window ', 10 * (station_index+1) + channel_index
print 'plotted data for station ',station_name,' and channel ',channel_letter, ' in window ',100 + 10 * (station_index+1) + channel_index,'\n'
print sum(tmp2-tmp5)
# print "prepared element (s,r,c_m)=",idx_s,idx_r,idx_k,j," of b"
if _debug:
lo_added_receivers.append(receiver)
# calculate sum over all stations for each time window, source point, and M component
if key == 0:
b = zeros((number_of_window_steps,6, n_gridpoints),float)
for window_idx in arange(number_of_window_steps):
for gp in xrange(n_gridpoints):
for m_component in xrange(6):
b[window_idx, m_component, gp] = sum(b_tmp[window_idx,gp, :, m_component])
#save array 'b' into file
File1d = file(corr_vec_filename,'w')
pp.dump(b,File1d)
File1d.close()
#write array 'b' into config dictionary
cfg['b'] = b
#print '\n\n BBBBBBBBBBBBBBBBBBBBBBBB:\n\n', b[0,:,0],'\n\n\n'
# print b[0,:,-1],'\n'
#exit()
if _debug:
set_of_added_receivers = sort(list(set(lo_added_receivers)))
#d_break(locals(),'bbbb')
if _debug:
print shape(b)
#control parameter
return 1
#----------------------------------------------------------------------
#----------------------------------------------------------------------
def read_in_data(cfg):
"""Reading data files into pure ascii time-series.
input:
-- config dictionary
indirect output:
-- data array into config dictionary
-- time axes into config dictionary
direct output:
-- control parameter
"""
print 'Reading the current data-set:...'
if _debug:
lo_added_receivers =[]
temp_datetime = cfg['datetime']
lo_datetime = temp_datetime.split(':')
datetime_new = '_'.join(lo_datetime)
lo_stations = cfg['list_of_stations_with_data']
filter_flag = int(cfg['filter_flag'])
lo_stats = lo_stations
# filename gets too long for too many stations
if len(lo_stats) > 10:
lo_stats = ['many','stations']
#set filename for saving output
if filter_flag == 1 or filter_flag == 2 :
data_filename = path.realpath(path.abspath(path.join(cfg['temporary_directory'], 'bandpass_filtered_data_array_v%i_event%s_stations_%s.pp'% (int(cfg['data_version']),datetime_new,'_'.join(lo_stats) ) )))
data_time_filename = path.realpath(path.abspath(path.join(cfg['temporary_directory'], 'bandpass_filtered_current_data_time_axis_event%s_stations_%s.pp'% (datetime_new,'_'.join(lo_stats) ))))
elif filter_flag == 0:
data_filename = path.realpath(path.abspath(path.join(cfg['temporary_directory'], 'data_array_v%i_event%s_stations_%s.pp'% (int(cfg['data_version']),datetime_new,'_'.join(lo_stats) ) )))
data_time_filename = path.realpath(path.abspath(path.join(cfg['temporary_directory'], 'current_data_time_axis_event%s_stations_%s.pp'% (datetime_new,'_'.join(lo_stats) ))))
else:
print 'ERROR!!! filter_flag must be "0" or "1" or "2" '
#if too many stations: reload stations list
if len(lo_stats) == 2:
lo_stats = lo_stations
#d_break(locals(),'filename datafile')
#TODO: nur zum debuggen
#load data from file if existing
if 0:#path.isfile(data_filename) and path.isfile(data_time_filename):
File8a = file(data_filename,'r')
print 'read from ',data_filename, 'and ', data_time_filename
data_array = pp.load(File8a)
File8a.close()
File9a = file(data_time_filename,'r')
time_axes_array = pp.load(File9a)
File9a.close()
print 'data ... re-read from file\n'
data_pile_for_main_window = cfg['data_pile_for_main_window']
data_sampling = int(1./data_pile_for_main_window[0].deltat)
#cfg['sampling_rate'] = data_sampling
cfg['data_sampling_rate'] = data_sampling
# otherwise read in data
else:
data_pile_for_main_window = cfg['data_pile_for_main_window']
lo_receivers = cfg['list_of_receivers_with_data']
lo_cont_stats = cfg['list_of_stations_with_data']
lo_channels = cfg['list_of_channels_with_data']
# print lo_receivers
# print lo_cont_stats
# print lo_channels
# exit()
length = int(cfg['time_window_length'])
gf_sampling = int(float(cfg['gf_sampling_rate']))
data_sampling = int(1./data_pile_for_main_window[0].deltat)
cfg['data_sampling_rate'] = data_sampling
n_time = int(length * data_sampling) + 1
parent_data_directory = cfg['parent_data_directory']
receiver_index_dictionary = cfg['receiver_index_dictionary']
channel_index_dict = cfg['channel_index_dictionary']
station_index_dict = cfg['station_index_dictionary']
list_of_moving_window_starttimes = cfg['list_of_moving_window_starttimes']
number_of_window_steps = len(list_of_moving_window_starttimes)
data_array = zeros((number_of_window_steps, len(lo_receivers), n_time),float32)
time_axes_array = zeros((number_of_window_steps,n_time),float32)
# loop over time windows
for window_idx in arange(number_of_window_steps):
window_starttime = int(list_of_moving_window_starttimes[window_idx])
temp_time_axis = 0.
#loop over receivers
for current_rec in lo_receivers:
receiver_index = int(receiver_index_dictionary[current_rec])
dummy1 = current_rec.split('.')
current_station = dummy1[0]
current_channel = dummy1[1]
#loop for finding the appropriate data pile for the respective station/component combination
for fff in arange(len(cfg['list_of_datafiles'])):
dummy2 = data_pile_for_main_window[fff]
if dummy2.channel == current_channel and dummy2.station == current_station:
current_data_pile_idx = fff
break
#extract correct data pile for the given receiver
current_data_pile_element = data_pile_for_main_window[current_data_pile_idx]
#TODO !!! auch in andere richtung resampling erm�glichen
if (not data_sampling == gf_sampling):
if data_sampling%gf_sampling == 0:
downsample_factor = int(data_sampling/gf_sampling)
current_data_pile_element.downsample(downsample_factor)
cfg['sampling_rate'] = data_sampling/downsample_factor
#error, if downsampling not possible
else:
exit( 'ERROR : incompatible sampling rates [Hz] of data and GF !!!!\n ',data_sampling, gf_sampling)
#endtime must be one sample later than time of interest
window_endtime = window_starttime + int(cfg['time_window_length']) + current_data_pile_element.deltat
#cut out time interval
current_pile_section = current_data_pile_element.chop(window_starttime,window_endtime )
#check, if right interval length has been taken
if (not len(current_pile_section.ydata) == n_time ):
exit( 'ERROR !!!! Chosen section has wrong length: ', len(current_pile_section.ydata), ' -- must have ', n_time)
#option 1: filter here with butterworth bandpass...
if (int(cfg['filter_flag']) == 2) :
current_pile_section.bandpass( int(cfg['bp_order']),float(cfg['bp_lower_corner']) , float(cfg['bp_upper_corner']))
data_array[window_idx,receiver_index,:] = current_pile_section.ydata
if _debug:
lo_added_receivers.append(current_rec)
#option 2: ... or here with boxcar filter
if (int(cfg['filter_flag']) == 1):
temp_in_data= current_pile_section.ydata
temp_filtered = bp_boxcar(taper_data(temp_in_data),float(cfg['data_sampling_rate']), cfg)
data_array[window_idx,receiver_index,:] = temp_filtered
#read time axis from data pile object
temp_time_axis += current_pile_section.make_xdata()
#visualisation for debugging
if _debug_plot:
station_index = station_index_dict[current_station]
channel_index = channel_index_dict[current_channel]
figure(70 + 10 * (station_index+1) + channel_index)
print 70 + 10 * (station_index+1) + channel_index , current_rec
plot(data_array[window_idx,receiver_index,:])
print 'plotted data for station ',current_station,' and channel ',current_channel, ' in window ',70 + 10 * (station_index+1) + channel_index,'\n'
#building average time axis for case of slight time shifts
temp_time_axis /= len(lo_receivers)
time_axes_array[window_idx,:] = temp_time_axis
#save data to file for later reprocessing
#print data_filename
#File8a = file(data_filename,'w')
#pp.dump(data_array,File8a)
#File8a.close()
#File9 = file(data_time_filename,'w')
#pp.dump(time_axes_array,File9)
#File9.close()
#print 'data-array written to file\n'
if _debug:
print 'data_db and time set: \n data shape:',shape(data_array),'\n time-axis shape:',shape(time_axes_array),'\n '
if int(cfg['filter_flag']) == 1 or int(cfg['filter_flag']) == 2 :
print '\n\n Data is bandpass filtered !!!!\n'
#put data and time axes into config dictionary
cfg['data_time_axes_array'] = time_axes_array
cfg['data_array'] = data_array
if _debug:
print shape(data_array),data_array.max(),data_array.min()
set_of_added_receivers = sort(list(set(lo_added_receivers)))
#d_break(locals(),'DATAaaaaa')
#control parameter
return 1
#----------------------------------------------------------------------
#----------------------------------------------------------------------
def read_in_GF(cfg):
"""Reading gf-files into combined array.
input:
-- config dictionary
indirect output:
-- time axis, array of Greens functions 'gf'
direct output:
-- control parameter
"""
#pdb.set_trace()
gf_version = int(cfg['gf_version'])
#list of chosen stations
lo_stations = cfg['list_of_stations']
n_stations = len(lo_stations)
print 'current number of stations: ',n_stations,':\n (',lo_stations,')'
#list of source points, according to chosen section
try:
gs_section_key = int(cfg.get('gs_type_of_section'))
except:
gs_section_key = 0
if gs_section_key == 0:
current_lo_gridpoints = cfg['list_of_all_gridpoints']
else:
current_lo_gridpoints = cfg['list_of_gridpoint_section']
n_gridpoints = len(current_lo_gridpoints)
#time parameters