-
Notifications
You must be signed in to change notification settings - Fork 0
/
dvv.py
190 lines (153 loc) · 6.36 KB
/
dvv.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
"""
This plot shows the final output of MSNoise.
.. include:: clickhelp/msnoise-plot-dvv.rst
Example:
``msnoise plot dvv`` will plot all defaults:
.. image:: .static/dvv.png
"""
import matplotlib.gridspec as gridspec
import matplotlib.pyplot as plt
from ..api import *
def wavg(group, dttname, errname):
d = group[dttname]
group[errname][group[errname] == 0] = 1e-6
w = 1. / group[errname]
wavg = (d * w).sum() / w.sum()
return wavg
def wstd(group, dttname, errname):
d = group[dttname]
group[errname][group[errname] == 0] = 1e-6
w = 1. / group[errname]
wavg = (d * w).sum() / w.sum()
N = len(np.nonzero(w)[0])
wstd = np.sqrt(np.sum(w * (d - wavg) ** 2) / ((N - 1) * np.sum(w) / N))
return wstd
def get_wavgwstd(data, dttname, errname):
grouped = data.groupby(level=0)
g = grouped.apply(wavg, dttname=dttname, errname=errname)
h = grouped.apply(wstd, dttname=dttname, errname=errname)
return g, h
def main(mov_stack=None, dttname="M", components='ZZ', filterid=1,
pairs=[], showALL=False, show=False, outfile=None ,scale=False):
db = connect()
if get_config(db, name="autocorr", isbool=True):
condition = "sta2 >= sta1"
else:
condition = "sta2 > sta1"
start, end, datelist = build_movstack_datelist(db)
if mov_stack != 0:
mov_stacks = [mov_stack, ]
else:
mov_stack = get_config(db, "mov_stack")
if mov_stack.count(',') == 0:
mov_stacks = [int(mov_stack), ]
else:
mov_stacks = [int(mi) for mi in mov_stack.split(',')]
if components.count(","):
components = components.split(",")
else:
components = [components, ]
gs = gridspec.GridSpec(len(mov_stacks), 1)
plt.figure(figsize=(12, 9))
plt.subplots_adjust(bottom=0.06, hspace=0.3)
first_plot = True
for i, mov_stack in enumerate(mov_stacks):
current = start
first = True
alldf = []
while current <= end:
for comp in components:
day = os.path.join('DTT', "%02i" % filterid, "%03i_DAYS" %
mov_stack, comp, '%s.txt' % current)
if os.path.isfile(day):
df = pd.read_csv(day, header=0, index_col=0,
parse_dates=True)
alldf.append(df)
current += datetime.timedelta(days=1)
if len(alldf) == 0:
print("No Data for %s m%i f%i" % (components, mov_stack, filterid))
continue
alldf = pd.concat(alldf)
print(mov_stack, alldf.head())
if 'alldf' in locals():
errname = "E" + dttname
alldf[dttname] *= -100
alldf[errname] *= -100
ALL = alldf[alldf['Pairs'] == 'ALL'].copy()
allbut = alldf[alldf['Pairs'] != 'ALL'].copy()
if first_plot == 1:
ax = plt.subplot(gs[i])
else:
plt.subplot(gs[i], sharex=ax)
# x = {}
# for group in groups.keys():
# pairindex = []
# for j, pair in enumerate(allbut['Pairs']):
# net1, sta1, net2, sta2 = pair.split('_')
# if sta1 in groups[group] and sta2 in groups[group]:
# pairindex.append(j)
# tmp = allbut.iloc[np.array(pairindex)]
# tmp = tmp.resample('D', how='mean')
# #~ plt.plot(tmp.index, tmp[dttname], label=group)
# x[group] = tmp
#
# tmp = x["CRATER"] - x["VOLCAN"]
# plt.plot(tmp.index, tmp[dttname], label="Crater - Volcan")
for pair in pairs:
print(pair)
pair1 = alldf[alldf['Pairs'] == pair].copy()
print(pair1.head())
plt.plot(pair1.index, pair1[dttname], label=pair)
plt.fill_between(pair1.index, pair1[dttname]-pair1[errname],
pair1[dttname]+pair1[errname], zorder=-1,
alpha=0.5)
pair1.to_csv('%s-m%i-f%i.csv'%(pair, mov_stack, filterid))
if showALL:
plt.plot(ALL.index, ALL[dttname], c='r',
label='ALL: $\delta v/v$ of the mean network')
tmp2 = allbut[dttname].resample('D').mean()
tmp2.plot(label='mean', color='orange')
tmp4 = allbut[dttname].resample('D').mean()+allbut[dttname].resample('D').std()
tmp4.plot(label='meanstd-',color='red')
tmp5 = allbut[dttname].resample('D').mean()-allbut[dttname].resample('D').std()
tmp5.plot(label='meanstd+',color='red')
#tmp3 = allbut[dttname].resample('D').median()
#tmp3.plot(label='median',)
#plt.ylabel('dv/v (%)')
if first_plot == 1:
plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=4,
ncol=2, borderaxespad=0.)
lim1=min(tmp5)
lim2=max(tmp4)
left, right = plt.xlim()
if mov_stack == 1:
plt.title('1 Day')
else:
plt.title('%i Days Average' % mov_stack)
first_plot = False
else:
plt.xlim(left, right)
plt.title('%i Days Average' % mov_stack)
plt.grid(True)
#if scale=True
#plt.ylim(min(tmp5),max(tmp4))# MY ADJUSTMENT!!!!!
plt.ylim(lim1,lim2)# MY ADJUSTMENT!!!!!
del alldf
if outfile:
if outfile.startswith("?"):
if len(mov_stacks) == 1:
outfile = outfile.replace('?', '%s-f%i-m%i-M%s' % (components,
filterid,
mov_stack,
dttname))
else:
outfile = outfile.replace('?', '%s-f%i-M%s' % (components,
filterid,
dttname))
outfile = "dvv " + outfile
print("output to:", outfile)
plt.savefig(outfile)
if show:
plt.show()
if __name__ == "__main__":
main()