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

import logging 

import numpy as num 

from scipy import linalg as splinalg 

 

from pyrocko import gf 

from pyrocko.guts import String, Bool, Dict, List 

from pyrocko.guts_array import Array 

 

import os 

 

from grond.meta import Parameter, has_get_plot_classes 

from ..base import MisfitConfig, MisfitTarget, MisfitResult, TargetGroup 

 

guts_prefix = 'grond' 

logger = logging.getLogger('grond.targets.satellite.target') 

 

 

class SatelliteMisfitConfig(MisfitConfig): 

"""Carries the misfit configuration.""" 

optimise_orbital_ramp = Bool.T( 

default=True, 

help='Switch to account for a linear orbital ramp or not') 

ranges = Dict.T( 

String.T(), gf.Range.T(), 

default={'offset': '-0.5 .. 0.5', 

'ramp_east': '-1e-7 .. 1e-7', 

'ramp_north': '-1e-7 .. 1e-7' 

}, 

help='These parameters give bounds for an offset [m], a linear' 

' gradient in east direction [m/m] and a linear gradient in north' 

' direction [m/m]. Note, while the optimisation of these ramps' 

' is individual for each target, the ranges set here are common' 

' for all satellite targets.') 

 

 

class SatelliteTargetGroup(TargetGroup): 

r"""Handles maps of static ground motion from satellite observations (InSAR) 

 

The InSAR displacement maps post-processed by the `pyrocko` module `kite` 

are usually `Quadtree` downsampled (Jonsson, 2002). Each data point has a 

latitude, longitude, Line-of-sight displacement value [m] as well as an 

orientation and elevation angle, which define the Line-of-Sight. The data 

are associated with a weight matrix, which is the inverse of a full 

variance-covariance matrix (Sudhaus \& Jonsson, 2009). In principle, these 

data sets could stem from pixel offset maps. See also the documentation of 

the `kite` module. 

""" 

kite_scenes = List.T( 

optional=True, 

help='List of InSAR data files prepared \ 

by the ``pyrocko`` module ``kite``') 

misfit_config = SatelliteMisfitConfig.T( 

help='Settings for the objective function of these targets') 

 

def get_targets(self, ds, event, default_path='none'): 

logger.debug('Selecting satellite targets...') 

targets = [] 

 

for scene in ds.get_kite_scenes(): 

if scene.meta.scene_id not in self.kite_scenes and\ 

'*all' not in self.kite_scenes: 

continue 

 

qt = scene.quadtree 

 

lats = num.empty(qt.nleaves) 

lons = num.empty(qt.nleaves) 

lats.fill(qt.frame.llLat) 

lons.fill(qt.frame.llLon) 

 

if qt.frame.isDegree(): 

logger.debug('Target "%s" is referenced in degree.' 

% scene.meta.scene_id) 

lons += qt.leaf_focal_points[:, 0] 

lats += qt.leaf_focal_points[:, 1] 

east_shifts = num.zeros_like(lats) 

north_shifts = num.zeros_like(lats) 

elif qt.frame.isMeter(): 

logger.debug('Target "%s" is referenced in meter.' 

% scene.meta.scene_id) 

east_shifts = qt.leaf_focal_points[:, 0] 

north_shifts = qt.leaf_focal_points[:, 1] 

else: 

assert False 

 

sat_target = SatelliteMisfitTarget( 

quantity='displacement', 

scene_id=scene.meta.scene_id, 

lats=lats, 

lons=lons, 

east_shifts=east_shifts, 

north_shifts=north_shifts, 

theta=qt.leaf_thetas, 

phi=qt.leaf_phis, 

tsnapshot=None, 

interpolation=self.interpolation, 

store_id=self.store_id, 

normalisation_family=self.normalisation_family, 

path=self.path or default_path, 

misfit_config=self.misfit_config) 

 

sat_target.set_dataset(ds) 

targets.append(sat_target) 

 

return targets 

 

 

class SatelliteMisfitResult(gf.Result, MisfitResult): 

"""Carries the observations for a target and corresponding synthetics.""" 

statics_syn = Dict.T( 

String.T(), 

Array.T(dtype=num.float, shape=(None,), serialize_as='base64'), 

optional=True, 

help='Predicted static displacements for a target (synthetics).') 

statics_obs = Dict.T( 

String.T(), 

Array.T(dtype=num.float, shape=(None,), serialize_as='base64'), 

optional=True, 

help='Observed static displacement for a target.') 

 

 

@has_get_plot_classes 

class SatelliteMisfitTarget(gf.SatelliteTarget, MisfitTarget): 

"""Handles and carries out operations related to the objective functions. 

 

Standard operations are the calculation of the weighted misfit between 

observed and predicted (synthetic) data. If enabled in the misfit 

configuration, orbital ramps are optimized for. 

""" 

scene_id = String.T( 

help='UID string each Kite displacemente scene.' 

' Corresponds to Kite scene_id.') 

misfit_config = SatelliteMisfitConfig.T( 

help='Configuration of the ``SatelliteTarget``') 

 

can_bootstrap_residuals = True 

 

available_parameters = [ 

Parameter('offset', 'm'), 

Parameter('ramp_north', 'm/m'), 

Parameter('ramp_east', 'm/m')] 

 

def __init__(self, *args, **kwargs): 

gf.SatelliteTarget.__init__(self, *args, **kwargs) 

MisfitTarget.__init__(self, **kwargs) 

if not self.misfit_config.optimise_orbital_ramp: 

self.parameters = [] 

else: 

self.parameters = self.available_parameters 

 

self.parameter_values = {} 

 

self._noise_weight_matrix = None 

 

@property 

def target_ranges(self): 

return self.misfit_config.ranges 

 

def string_id(self): 

return '.'.join([self.path, self.scene_id]) 

 

@property 

def id(self): 

return self.scene_id 

 

def set_dataset(self, ds): 

MisfitTarget.set_dataset(self, ds) 

 

@property 

def nmisfits(self): 

return self.lats.size 

 

def get_correlated_weights(self, nthreads=0): 

''' is for L2-norm weighting, the square-rooted, inverse covar ''' 

if self._noise_weight_matrix is None: 

logger.info( 

'Inverting scene covariance matrix (nthreads=%i)...' 

% nthreads) 

cov = self.scene.covariance 

cov.nthreads = nthreads 

 

self._noise_weight_matrix = splinalg.sqrtm( 

num.linalg.inv(cov.covariance_matrix)) 

 

logger.info('Inverting scene covariance matrix done.') 

 

return self._noise_weight_matrix 

 

@property 

def scene(self): 

return self._ds.get_kite_scene(self.scene_id) 

 

def post_process(self, engine, source, statics): 

"""Applies the objective function. 

 

As a result the weighted misfits are given and the observed and 

synthetic data. For the satellite target the orbital ramp is 

calculated and applied here.""" 

scene = self.scene 

quadtree = scene.quadtree 

 

obs = quadtree.leaf_medians 

 

if self.misfit_config.optimise_orbital_ramp: 

stat_level = num.full_like(obs, self.parameter_values['offset']) 

 

stat_level += (quadtree.leaf_center_distance[:, 0] 

* self.parameter_values['ramp_east']) 

stat_level += (quadtree.leaf_center_distance[:, 1] 

* self.parameter_values['ramp_north']) 

statics['displacement.los'] += stat_level 

 

stat_syn = statics['displacement.los'] 

 

res = obs - stat_syn 

 

misfit_value = res 

misfit_norm = obs 

 

mf = num.vstack([misfit_value, misfit_norm]).T 

result = SatelliteMisfitResult( 

misfits=mf) 

 

if self._result_mode == 'full': 

result.statics_syn = statics 

result.statics_obs = {'displacement.los': obs} 

 

return result 

 

def get_combined_weight(self): 

if self._combined_weight is None: 

# invcov = self.scene.covariance.weight_matrix 

# self._combined_weight = invcov * self.manual_weight 

self._combined_weight = num.full(self.nmisfits, self.manual_weight) 

 

return self._combined_weight 

 

def prepare_modelling(self, engine, source, targets): 

return [self] 

 

def finalize_modelling( 

self, engine, source, modelling_targets, modelling_results): 

return modelling_results[0] 

 

def init_bootstrap_residuals(self, nbootstraps, rstate=None, nthreads=0): 

logger.info( 

'Scene "%s", initializing bootstrapping residuals from noise ' 

'pertubations...' % self.scene_id) 

 

if rstate is None: 

rstate = num.random.RandomState() 

 

scene = self.scene 

qt = scene.quadtree 

cov = scene.covariance 

bootstraps = num.zeros((nbootstraps, qt.nleaves)) 

 

try: 

# TODO:mi Signal handler is not given back to the main task! 

# This is a python3.7 bug 

logger.warning('Using multi-threading for SatelliteTargets. ' 

'Python 3.7 is buggy and needs to be killed hard:' 

' `killall grond`') 

from concurrent.futures import ThreadPoolExecutor 

nthreads = os.cpu_count() if not nthreads else nthreads 

 

with ThreadPoolExecutor(max_workers=nthreads) as executor: 

res = executor.map( 

cov.getQuadtreeNoise, 

[rstate for _ in range(nbootstraps)]) 

 

for ibs, bs in enumerate(res): 

bootstraps[ibs, :] = bs 

except ImportError: 

for ibs in range(nbootstraps): 

if not (ibs+1) % 5: 

logger.info('Calculating noise realisation %d/%d.' 

% (ibs+1, nbootstraps)) 

bootstraps[ibs, :] = cov.getQuadtreeNoise(rstate=rstate) 

 

self.set_bootstrap_residuals(bootstraps) 

 

@classmethod 

def get_plot_classes(cls): 

from . import plot 

plots = super(SatelliteMisfitTarget, cls).get_plot_classes() 

plots.extend(plot.get_plot_classes()) 

return plots 

 

 

__all__ = ''' 

SatelliteTargetGroup 

SatelliteMisfitConfig 

SatelliteMisfitTarget 

SatelliteMisfitResult 

'''.split()