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

import logging 

import re 

import os.path as op 

import shutil 

import numpy as num 

from datetime import datetime, timedelta 

 

from pyrocko.guts import Bool, List 

from .plugin import PluginConfig, Plugin 

 

 

def load_params(filename): 

rc = re.compile(r'([\w]*)\s*([\w.+-]*)') 

params = {} 

 

with open(filename, mode='r') as par: 

for line in par: 

parsed = rc.match(line) 

if parsed is None: 

continue 

 

groups = parsed.groups() 

params[groups[0]] = groups[1].strip() 

 

return params 

 

 

class GACOSGrid(object): 

 

def __init__(self, filename, time, data, 

ulLat, ulLon, dLat, dLon): 

self.filename = filename 

self.time = time 

 

self.data = data 

self.rows, self.cols = data.shape 

 

self.dLat = dLat 

self.dLon = dLon 

 

self.ulLat = ulLat 

self.ulLon = ulLon 

 

self.llLat = self.ulLat + self.rows * self.dLat 

self.llLon = ulLon 

 

self.urLon = ulLon + self.cols * self.dLon 

 

def contains(self, llLat, llLon, dLat, dLon, rows, cols): 

ulLat = llLat + dLat * rows 

urLon = llLon + dLon * cols 

 

boundary_exception = AssertionError( 

'GACOS Grid does not contain scene!\n' 

' llLat: %.4f urLat: %.4f\n' 

' llLon: %.4f urLon: %.4f\n' 

'Scene:\n' 

' llLat: %.4f urLat: %.4f\n' 

' llLon: %.4f urLon: %.4f' 

% (self.llLat, self.ulLat, self.llLon, self.urLon, 

llLat, ulLat, llLon, urLon)) 

 

assert llLat >= self.llLat, boundary_exception 

assert llLon >= self.llLon, boundary_exception 

 

assert urLon <= self.urLon, boundary_exception 

assert ulLat <= self.ulLat, boundary_exception 

 

def get_corrections(self, llLat, llLon, dLat, dLon, rows, cols): 

self.contains(llLat, llLon, dLat, dLon, rows, cols) 

 

ulLat = llLat + dLat * rows 

ulLon = llLon 

urLon = llLon + dLon * cols # noqa 

 

row_offset = (self.ulLat - ulLat) // -self.dLat 

col_offset = (ulLon - self.llLon) // self.dLon 

 

idx_rows = row_offset + (num.arange(rows) * dLat // -self.dLat) 

idx_cols = col_offset + (num.arange(cols) * dLon // self.dLon) 

 

idx_rows = num.repeat(idx_rows, cols).astype(num.intp) 

idx_cols = num.tile(idx_cols, rows).astype(num.intp) 

 

return num.flipud(self.data[idx_rows, idx_cols].reshape(rows, cols)) 

 

@classmethod 

def load(cls, filename): 

rsc_file = filename + '.rsc' 

if not op.exists(filename) and not op.exists(rsc_file): 

raise FileNotFoundError('Could not find %s or .rsc file %s' 

% (filename, rsc_file)) 

 

params = load_params(rsc_file) 

 

time = datetime.strptime(op.basename(filename)[:8], '%Y%m%d') 

hour = timedelta(hours=float(params['TIME_OF_DAY'].rstrip('UTC'))) 

time += hour 

 

rows = int(params['FILE_LENGTH']) 

cols = int(params['WIDTH']) 

 

ulLat = float(params['Y_FIRST']) 

ulLon = float(params['X_FIRST']) 

 

dLat = float(params['Y_STEP']) 

dLon = float(params['X_STEP']) 

 

data = num.memmap( 

filename, dtype=num.float32, mode='r', shape=(rows, cols)) 

 

return cls(filename, time, data, ulLat, ulLon, dLat, dLon) 

 

 

class GACOSConfig(PluginConfig): 

grd_filenames = List.T( 

default=[], 

help='List of *two* GACOS gridfiles.') 

applied = Bool.T( 

default=False, 

help='Is the correction applied.') 

 

 

class GACOSCorrection(Plugin): 

 

def __init__(self, scene=None, config=None): 

self.config = config or GACOSConfig() 

self.scene = scene 

 

if scene: 

self._log = scene._log.getChild('GACOSCorrection') 

else: 

self._log = logging.getLogger('GACOSCorrection') 

 

self.grids = [] 

 

assert len(self.config.grd_filenames) <= 2 

for filename in self.config.grd_filenames: 

self.load(filename) 

 

def has_data(self): 

if len(self.grids) == 2: 

return True 

return False 

 

def _scene_extent(self): 

frame = self.scene.frame 

return { 

'llLat': frame.llLat, 

'llLon': frame.llLon, 

'dLat': frame.dNdegree, 

'dLon': frame.dEdegree, 

'cols': frame.cols, 

'rows': frame.rows 

} 

 

def load(self, filename): 

if len(self.grids) == 2: 

raise AttributeError('already loaded two GACOS grids!') 

 

if filename.startswith('./'): 

abs_path = op.join(op.dirname(self.scene.meta.filename), filename) 

else: 

abs_path = filename 

if not op.exists(abs_path): 

raise OSError('cannot find GACOS grid %s' % abs_path) 

 

self._log.info('Loading %s', filename) 

 

grd = GACOSGrid.load(abs_path) 

grd.contains(**self._scene_extent()) 

 

self.grids.append(grd) 

self.grids = sorted(self.grids, key=lambda grd: grd.time) 

 

if filename not in self.config.grd_filenames: 

self.config.grd_filenames.append(filename) 

 

def unload(self): 

self.grids = [] 

self.config.grd_filenames = [] 

 

def save(self, dirname): 

for grd_file in self.config.grd_filenames: 

self._log.info('copying GACOS grid %s', grd_file) 

grd_file = op.join(op.dirname(self.scene.meta.filename), grd_file) 

try: 

shutil.copy(grd_file, dirname) 

shutil.copy(grd_file + '.rsc', dirname) 

except shutil.SameFileError: 

pass 

 

self.config.grd_filenames = [ 

'./%s' % op.basename(grd_file) 

for grd_file in self.config.grd_filenames] 

 

def get_correction(self): 

if len(self.grids) != 2: 

raise AttributeError( 

'need two GACOS grids to calculate the corrections!') 

 

extent = self._scene_extent() 

 

corr_date1 = self.grids[0].get_corrections(**extent) 

corr_date2 = self.grids[1].get_corrections(**extent) 

 

return corr_date2 - corr_date1 

 

def apply(self, displacement): 

self._log.info('Applying GACOS model to displacement') 

correction = self.get_correction() 

correction *= 1./num.sin(self.scene.phi) 

 

displacement -= correction 

return displacement