-
Notifications
You must be signed in to change notification settings - Fork 31
/
creepmeters.py
475 lines (358 loc) · 12.2 KB
/
creepmeters.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
'''
A class that deals with creepmeter data
Written by R. Jolivet, April 2013.
'''
import numpy as np
import pyproj as pp
import datetime as dt
import matplotlib.pyplot as plt
import os
# Personals
from .SourceInv import SourceInv
class creepmeters(SourceInv):
'''
A class that handles creepmeter data
Args:
* name : Name of the dataset.
Kwargs:
* utmzone : UTM zone (optional, default=None)
* lon0 : Longitude of the center of the UTM zone
* lat0 : Latitude of the center of the UTM zone
* ellps : ellipsoid (optional, default='WGS84')
* verbose : Speak to me (default=True)
'''
def __init__(self, name, utmzone=None, ellps='WGS84', lon0=None, lat0=None, verbose=True):
# Initialize the data set
self.dtype = 'creepmeters'
# Print
if verbose:
print ("---------------------------------")
print ("---------------------------------")
print (" Initialize Creepmeters data set {}".format(self.name))
self.verbose = verbose
# Base class init
super(creepmeters,self).__init__(name,
utmzone = utmzone,
ellps = ellps,
lon0 = lon0,
lat0 = lat0)
# Initialize some things
self.data = {}
# All done
return
def readStationList(self, filename):
'''
Reads the list of Stations. Input file format is
+--------------+-----+-----+
| Station Name | Lon | Lat |
+--------------+-----+-----+
Args:
* filename : Input file.
Returns:
* None
'''
# open the file
fin = open(filename, 'r')
# Read all lines
Text = fin.readlines()
fin.close()
# Create lists
self.station = []
self.lon = []
self.lat = []
# Loop
for t in Text:
tex = t.split()
self.station.append(tex[0])
self.lon.append(float(tex[2]))
self.lat.append(float(tex[1]))
# translate to array
self.lon = np.array(self.lon)
self.lat = np.array(self.lat)
# Convert to utm
self.lonlat2xy()
# All done
return
def position(self, station):
'''
Returns lon,lat of a station.
Args:
* station : Name of a station.
Returns:
* lon, lat
'''
# Find it
u = np.flatnonzero(np.array(self.station)==station)
u = u[0]
# Get lon, lat and return
return self.lon[u], self.lat[u]
def distance(self, station, point, direction):
'''
Computes the distance between a station and a point.
Args:
* station : Name of a station.
* point : [Lon, Lat].
* direction : Direction of the positive sign.
Returns:
* None. Distance is stored in the {data} attribute under the station name.
'''
# Check
if 'Distance' not in self.data[station].keys():
self.data[station]['Distance'] = []
# Get station lon,lat
lon, lat = self.position(station)
x, y = self.ll2xy(lon,lat)
# Transfert point
x0, y0 = self.ll2xy(point[0],point[1])
# Computes the sign
Dir = np.array([np.cos(direction*np.pi/180.), np.sin(direction*np.pi/180.)])
vec = np.array([x0-x, y0-y])
sign = np.sign(np.dot(Dir, vec))
# Compute distance
d = np.sqrt( (x0-x)**2 +(y0-y)**2 ) * sign
# Stores it
self.data[station]['Distance'].append([[lon,lat], d])
# all done
return
def deleteStation(self, station):
'''
Removes a station.
Args:
* station : Name of the station to remove
Returns:
* None
'''
# find it
u = np.flatnonzero(np.array(self.station)==station)
# delete it
del self.station[u]
self.lon = np.delete(self.lon, u)
self.lat = np.delete(self.lat, u)
# All done
return
def readAllStations(self, directory='.'):
'''
Reads all the station files.
Kwargs:
* directory : directory where to find the station files
Returns:
* None
'''
for station in self.station:
self.readStationData(station,directory=directory)
# stations to delete
sta = []
for station in self.station:
if self.data[station] == {}:
sta.append(station)
for s in sta:
self.deleteStation(s)
# all done
return
def readStationData(self, station, directory='.'):
'''
From the name of a station, reads what is in station.day.
Args:
* station : name of the station
Kwargs:
* directory : directory where to find the station.day file.
Returns:
* None
'''
# Filename
filename = '{}/{}.day'.format(directory,station)
if not os.path.exists(filename):
filename = '{}/{}.m'.format(directory,station)
if not os.path.exists(filename):
self.data[station] = {}
return
# Create the storage
self.data[station] = {}
self.data[station]['Time'] = []
self.data[station]['Offset'] = []
t = self.data[station]['Time']
o = self.data[station]['Offset']
# Open
fin = open(filename, 'r')
# Read everything in it
Text = fin.readlines()
fin.close()
# Loop
for text in Text:
# Get values
yr = int(text.split()[0])
da = int(text.split()[1])
of = float(text.split()[2])
# Compute the time
time = dt.datetime.fromordinal(dt.datetime(yr, 1, 1).toordinal() + da)
# Append
t.append(time)
o.append(of)
# Arrays
self.data[station]['Time'] = np.array(self.data[station]['Time'])
self.data[station]['Offset'] = np.array(self.data[station]['Offset'])
# All done
return
def selectbox(self, minlon, maxlon, minlat, maxlat):
'''
Select the earthquakes in a box defined by min and max, lat and lon.
Args:
* minlon : Minimum longitude.
* maxlon : Maximum longitude.
* minlat : Minimum latitude.
* maxlat : Maximum latitude.
Returns:
* None
'''
# Store the corners
self.minlon = minlon
self.maxlon = maxlon
self.minlat = minlat
self.maxlat = maxlat
# Select on latitude and longitude
print( "Selecting the earthquakes in the box Lon: {} to {} and Lat: {} to {}".format(minlon, maxlon, minlat, maxlat))
u = np.flatnonzero((self.lat>minlat) & (self.lat<maxlat) & (self.lon>minlon) & (self.lon<maxlon))
# Select the stations
self.lon = self.lon[u]
self.lat = self.lat[u]
self.x = self.x[u]
self.y = self.y[u]
self.station = sellf.station[u]
# All done
return
def lonlat2xy(self):
'''
Converts the lat lon positions into utm coordinates.
Returns:
* None
'''
self.x, self.y = self.ll2xy(self.lon, self.lat)
# all done
return
def fitLinearAllStations(self, period=None, directory='.'):
'''
Fits a linear trend to all the available stations. Can specify a period=[startdate, enddate]
Args:
* period : list of 2 tuples (yyyy, mm, dd)
Kwargs:
* directory : If station files have not been read before, this is the directory where to find the station files
Returns:
* None
'''
# Loop
for station in self.station:
print('Fitting Station {}'.format(station))
self.fitLinear(station, period=period, directory=directory)
# All done
return
def fitLinear(self, station, period=None, directory='.'):
'''
Fits a linear trend onto the offsets for the station 'station'.
Args:
* station : station name
Kwargs:
* period : list of 2 tuples (yyyy, mm, dd)
* directory : If station files have not been read before, this is the directory where to find the station files
Returns:
* None
'''
# Check if the station has been read before
if not (station in self.data.keys()):
self.readStationData(station, directory=directory)
if not (station in self.data.keys()):
print('Cannot fit station {} ...'.format(station))
return
# Creates a storage
self.data[station]['Linear'] = {}
store = self.data[station]['Linear']
# Create the dates
if period is None:
date1 = self.data[station]['Time'][0]
date2 = self.data[station]['Time'][1]
else:
date1 = dt.datetime(period[0][0], period[0][1], period[0][2])
date2 = dt.datetime(period[1][0], period[1][1], period[1][2])
# Keep the period
store['Period'] = []
store['Period'].append(date1)
store['Period'].append(date2)
# Get the data we want
time = self.data[station]['Time']
offset = self.data[station]['Offset']
# Get the dates we want
u = np.flatnonzero(time>=date1)
v = np.flatnonzero(time<=date2)
w = np.intersect1d(u,v)
if w.shape[0]<2:
print('Not enough points for station {}'.format(station))
store['Fit'] = None
return
ti = time[w]
of = offset[w]
# pass the dates into real numbers
tr = np.array([self.date2real(ti[i]) for i in range(ti.shape[0])])
# Make an array
A = np.ones((tr.shape[0], 2))
A[:,0] = tr
# invert
m, res, rank, s = np.linalg.lstsq(A, of)
# Stores the results
store['Fit'] = m
# all done
return
def plotStation(self, station, figure=100, save=None):
'''
Plots one station evolution through time.
Args:
* station : name of the station
Kwargs:
* figure : figure numner
* save : name of the file if you want to save
Returns:
* None
'''
# Check if the station has been read
if not (station in self.data.keys()):
print('Read the data first...')
return
# Create figure
fig = plt.figure(figure)
ax = fig.add_subplot(111)
# Title
ax.set_title(station)
# plot data
t = self.data[station]['Time']
o = self.data[station]['Offset']
ax.plot(t, o, '.k')
# plot fit
if 'Linear' in self.data[station].keys():
if self.data[station]['Linear']['Fit'] is not None:
v = self.data[station]['Linear']['Fit'][0]
c = self.data[station]['Linear']['Fit'][1]
date1 = self.data[station]['Linear']['Period'][0]
date2 = self.data[station]['Linear']['Period'][1]
dr1 = self.date2real(date1)
dr2 = self.date2real(date2)
plt.plot([date1, date2],[c+dr1*v, c+dr2*v], '-r')
# save
if save is not None:
plt.savefig(save)
# Show
plt.show()
# All done
return
def date2real(self, date):
'''
Pass from a datetime to a real number.
Weird method... Who implemented that?
Args:
* date : datetime instance
Returns:
* float
'''
yr = date.year
yrordi = dt.datetime(yr, 1, 1).toordinal()
ordi = date.toordinal()
days = ordi - yrordi
return yr + days/365.25
#EOF