1# http://pyrocko.org - GPLv3 

2# 

3# The Pyrocko Developers, 21st Century 

4# ---|P------/S----------~Lg---------- 

5 

6import math 

7import random 

8import logging 

9 

10try: 

11 from StringIO import StringIO as BytesIO 

12except ImportError: 

13 from io import BytesIO 

14 

15import numpy as num 

16 

17from pyrocko.guts import (Object, Float, Bool, Int, Tuple, String, List, 

18 Unicode, Dict) 

19from pyrocko.guts_array import Array 

20from pyrocko.dataset import topo 

21from pyrocko import orthodrome as od 

22from . import gmtpy 

23from . import nice_value 

24 

25 

26points_in_region = od.points_in_region 

27 

28logger = logging.getLogger('pyrocko.plot.automap') 

29 

30earthradius = 6371000.0 

31r2d = 180./math.pi 

32d2r = 1./r2d 

33km = 1000. 

34d2m = d2r*earthradius 

35m2d = 1./d2m 

36cm = gmtpy.cm 

37 

38 

39def darken(c, f=0.7): 

40 return (c[0]*f, c[1]*f, c[2]*f) 

41 

42 

43def corners(lon, lat, w, h): 

44 ll_lat, ll_lon = od.ne_to_latlon(lat, lon, -0.5*h, -0.5*w) 

45 ur_lat, ur_lon = od.ne_to_latlon(lat, lon, 0.5*h, 0.5*w) 

46 return ll_lon, ll_lat, ur_lon, ur_lat 

47 

48 

49def extent(lon, lat, w, h, n): 

50 x = num.linspace(-0.5*w, 0.5*w, n) 

51 y = num.linspace(-0.5*h, 0.5*h, n) 

52 slats, slons = od.ne_to_latlon(lat, lon, y[0], x) 

53 nlats, nlons = od.ne_to_latlon(lat, lon, y[-1], x) 

54 south = slats.min() 

55 north = nlats.max() 

56 

57 wlats, wlons = od.ne_to_latlon(lat, lon, y, x[0]) 

58 elats, elons = od.ne_to_latlon(lat, lon, y, x[-1]) 

59 elons = num.where(elons < wlons, elons + 360., elons) 

60 

61 if elons.max() - elons.min() > 180 or wlons.max() - wlons.min() > 180.: 

62 west = -180. 

63 east = 180. 

64 else: 

65 west = wlons.min() 

66 east = elons.max() 

67 

68 return topo.positive_region((west, east, south, north)) 

69 

70 

71class NoTopo(Exception): 

72 pass 

73 

74 

75class OutOfBounds(Exception): 

76 pass 

77 

78 

79class FloatTile(Object): 

80 xmin = Float.T() 

81 ymin = Float.T() 

82 dx = Float.T() 

83 dy = Float.T() 

84 data = Array.T(shape=(None, None), dtype=float, serialize_as='table') 

85 

86 def __init__(self, xmin, ymin, dx, dy, data): 

87 Object.__init__(self, init_props=False) 

88 self.xmin = float(xmin) 

89 self.ymin = float(ymin) 

90 self.dx = float(dx) 

91 self.dy = float(dy) 

92 self.data = data 

93 self._set_maxes() 

94 

95 def _set_maxes(self): 

96 self.ny, self.nx = self.data.shape 

97 self.xmax = self.xmin + (self.nx-1) * self.dx 

98 self.ymax = self.ymin + (self.ny-1) * self.dy 

99 

100 def x(self): 

101 return self.xmin + num.arange(self.nx) * self.dx 

102 

103 def y(self): 

104 return self.ymin + num.arange(self.ny) * self.dy 

105 

106 def get(self, x, y): 

107 ix = int(round((x - self.xmin) / self.dx)) 

108 iy = int(round((y - self.ymin) / self.dy)) 

109 if 0 <= ix < self.nx and 0 <= iy < self.ny: 

110 return self.data[iy, ix] 

111 else: 

112 raise OutOfBounds() 

113 

114 

115class City(Object): 

116 def __init__(self, name, lat, lon, population=None, asciiname=None): 

117 name = str(name) 

118 lat = float(lat) 

119 lon = float(lon) 

120 if asciiname is None: 

121 asciiname = name.encode('ascii', errors='replace') 

122 

123 if population is None: 

124 population = 0 

125 else: 

126 population = int(population) 

127 

128 Object.__init__(self, name=name, lat=lat, lon=lon, 

129 population=population, asciiname=asciiname) 

130 

131 name = Unicode.T() 

132 lat = Float.T() 

133 lon = Float.T() 

134 population = Int.T() 

135 asciiname = String.T() 

136 

137 

138class Map(Object): 

139 lat = Float.T(optional=True) 

140 lon = Float.T(optional=True) 

141 radius = Float.T(optional=True) 

142 width = Float.T(default=20.) 

143 height = Float.T(default=14.) 

144 margins = List.T(Float.T()) 

145 illuminate = Bool.T(default=True) 

146 skip_feature_factor = Float.T(default=0.02) 

147 show_grid = Bool.T(default=False) 

148 show_topo = Bool.T(default=True) 

149 show_scale = Bool.T(default=False) 

150 show_topo_scale = Bool.T(default=False) 

151 show_center_mark = Bool.T(default=False) 

152 show_rivers = Bool.T(default=True) 

153 show_plates = Bool.T(default=False) 

154 show_plate_velocities = Bool.T(default=False) 

155 show_plate_names = Bool.T(default=False) 

156 show_boundaries = Bool.T(default=False) 

157 illuminate_factor_land = Float.T(default=0.5) 

158 illuminate_factor_ocean = Float.T(default=0.25) 

159 color_wet = Tuple.T(3, Int.T(), default=(216, 242, 254)) 

160 color_dry = Tuple.T(3, Int.T(), default=(172, 208, 165)) 

161 color_boundaries = Tuple.T(3, Int.T(), default=(1, 1, 1)) 

162 topo_resolution_min = Float.T( 

163 default=40., 

164 help='minimum resolution of topography [dpi]') 

165 topo_resolution_max = Float.T( 

166 default=200., 

167 help='maximum resolution of topography [dpi]') 

168 replace_topo_color_only = FloatTile.T( 

169 optional=True, 

170 help='replace topo color while keeping topographic shading') 

171 topo_cpt_wet = String.T(default='light_sea') 

172 topo_cpt_dry = String.T(default='light_land') 

173 axes_layout = String.T(optional=True) 

174 custom_cities = List.T(City.T()) 

175 gmt_config = Dict.T(String.T(), String.T()) 

176 comment = String.T(optional=True) 

177 approx_ticks = Int.T(default=4) 

178 

179 def __init__(self, gmtversion='newest', **kwargs): 

180 Object.__init__(self, **kwargs) 

181 self._gmt = None 

182 self._scaler = None 

183 self._widget = None 

184 self._corners = None 

185 self._wesn = None 

186 self._minarea = None 

187 self._coastline_resolution = None 

188 self._rivers = None 

189 self._dems = None 

190 self._have_topo_land = None 

191 self._have_topo_ocean = None 

192 self._jxyr = None 

193 self._prep_topo_have = None 

194 self._labels = [] 

195 self._area_labels = [] 

196 self._gmtversion = gmtversion 

197 

198 def save(self, outpath, resolution=75., oversample=2., size=None, 

199 width=None, height=None, psconvert=False, crop_eps_mode=False): 

200 

201 ''' 

202 Save the image. 

203 

204 Save the image to ``outpath``. The format is determined by the filename 

205 extension. Formats are handled as follows: ``'.eps'`` and ``'.ps'`` 

206 produce EPS and PS, respectively, directly with GMT. If the file name 

207 ends with ``'.pdf'``, GMT output is fed through ``gmtpy-epstopdf`` to 

208 create a PDF file. For any other filename extension, output is first 

209 converted to PDF with ``gmtpy-epstopdf``, then with ``pdftocairo`` to 

210 PNG with a resolution oversampled by the factor ``oversample`` and 

211 finally the PNG is downsampled and converted to the target format with 

212 ``convert``. The resolution of rasterized target image can be 

213 controlled either by ``resolution`` in DPI or by specifying ``width`` 

214 or ``height`` or ``size``, where the latter fits the image into a 

215 square with given side length. To save transparency use 

216 ``psconvert=True``. To crop the output image with a rectangle to the 

217 nearest non-white element set ``crop_eps_mode=True``. 

218 ''' 

219 

220 gmt = self.gmt 

221 self.draw_labels() 

222 self.draw_axes() 

223 if self.show_topo and self.show_topo_scale: 

224 self._draw_topo_scale() 

225 

226 gmt.save(outpath, resolution=resolution, oversample=oversample, 

227 crop_eps_mode=crop_eps_mode, 

228 size=size, width=width, height=height, psconvert=psconvert) 

229 

230 @property 

231 def scaler(self): 

232 if self._scaler is None: 

233 self._setup_geometry() 

234 

235 return self._scaler 

236 

237 @property 

238 def wesn(self): 

239 if self._wesn is None: 

240 self._setup_geometry() 

241 

242 return self._wesn 

243 

244 @property 

245 def widget(self): 

246 if self._widget is None: 

247 self._setup() 

248 

249 return self._widget 

250 

251 @property 

252 def layout(self): 

253 if self._layout is None: 

254 self._setup() 

255 

256 return self._layout 

257 

258 @property 

259 def jxyr(self): 

260 if self._jxyr is None: 

261 self._setup() 

262 

263 return self._jxyr 

264 

265 @property 

266 def pxyr(self): 

267 if self._pxyr is None: 

268 self._setup() 

269 

270 return self._pxyr 

271 

272 @property 

273 def gmt(self): 

274 if self._gmt is None: 

275 self._setup() 

276 

277 if self._have_topo_ocean is None: 

278 self._draw_background() 

279 

280 return self._gmt 

281 

282 def _setup(self): 

283 if not self._widget: 

284 self._setup_geometry() 

285 

286 self._setup_lod() 

287 self._setup_gmt() 

288 

289 def _setup_geometry(self): 

290 wpage, hpage = self.width, self.height 

291 ml, mr, mt, mb = self._expand_margins() 

292 wpage -= ml + mr 

293 hpage -= mt + mb 

294 

295 wreg = self.radius * 2.0 

296 hreg = self.radius * 2.0 

297 if wpage >= hpage: 

298 wreg *= wpage/hpage 

299 else: 

300 hreg *= hpage/wpage 

301 

302 self._wreg = wreg 

303 self._hreg = hreg 

304 

305 self._corners = corners(self.lon, self.lat, wreg, hreg) 

306 west, east, south, north = extent(self.lon, self.lat, wreg, hreg, 10) 

307 

308 x, y, z = ((west, east), (south, north), (-6000., 4500.)) 

309 

310 xax = gmtpy.Ax(mode='min-max', approx_ticks=self.approx_ticks) 

311 yax = gmtpy.Ax(mode='min-max', approx_ticks=self.approx_ticks) 

312 zax = gmtpy.Ax(mode='min-max', inc=1000., label='Height', 

313 scaled_unit='km', scaled_unit_factor=0.001) 

314 

315 scaler = gmtpy.ScaleGuru(data_tuples=[(x, y, z)], axes=(xax, yax, zax)) 

316 

317 par = scaler.get_params() 

318 

319 west = par['xmin'] 

320 east = par['xmax'] 

321 south = par['ymin'] 

322 north = par['ymax'] 

323 

324 self._wesn = west, east, south, north 

325 self._scaler = scaler 

326 

327 def _setup_lod(self): 

328 w, e, s, n = self._wesn 

329 if self.radius > 1500.*km: 

330 coastline_resolution = 'i' 

331 rivers = False 

332 else: 

333 coastline_resolution = 'f' 

334 rivers = True 

335 

336 self._minarea = (self.skip_feature_factor * self.radius/km)**2 

337 

338 self._coastline_resolution = coastline_resolution 

339 self._rivers = rivers 

340 

341 self._prep_topo_have = {} 

342 self._dems = {} 

343 

344 cm2inch = gmtpy.cm/gmtpy.inch 

345 

346 dmin = 2.0 * self.radius * m2d / (self.topo_resolution_max * 

347 (self.height * cm2inch)) 

348 dmax = 2.0 * self.radius * m2d / (self.topo_resolution_min * 

349 (self.height * cm2inch)) 

350 

351 for k in ['ocean', 'land']: 

352 self._dems[k] = topo.select_dem_names(k, dmin, dmax, self._wesn) 

353 if self._dems[k]: 

354 logger.debug('using topography dataset %s for %s' 

355 % (','.join(self._dems[k]), k)) 

356 

357 def _expand_margins(self): 

358 if len(self.margins) == 0 or len(self.margins) > 4: 

359 ml = mr = mt = mb = 2.0 

360 elif len(self.margins) == 1: 

361 ml = mr = mt = mb = self.margins[0] 

362 elif len(self.margins) == 2: 

363 ml = mr = self.margins[0] 

364 mt = mb = self.margins[1] 

365 elif len(self.margins) == 4: 

366 ml, mr, mt, mb = self.margins 

367 

368 return ml, mr, mt, mb 

369 

370 def _setup_gmt(self): 

371 w, h = self.width, self.height 

372 scaler = self._scaler 

373 

374 if gmtpy.is_gmt5(self._gmtversion): 

375 gmtconf = dict( 

376 MAP_TICK_PEN_PRIMARY='1.25p', 

377 MAP_TICK_PEN_SECONDARY='1.25p', 

378 MAP_TICK_LENGTH_PRIMARY='0.2c', 

379 MAP_TICK_LENGTH_SECONDARY='0.6c', 

380 FONT_ANNOT_PRIMARY='12p,1,black', 

381 FONT_LABEL='12p,1,black', 

382 PS_CHAR_ENCODING='ISOLatin1+', 

383 MAP_FRAME_TYPE='fancy', 

384 FORMAT_GEO_MAP='D', 

385 PS_MEDIA='Custom_%ix%i' % ( 

386 w*gmtpy.cm, 

387 h*gmtpy.cm), 

388 PS_PAGE_ORIENTATION='portrait', 

389 MAP_GRID_PEN_PRIMARY='thinnest,0/50/0', 

390 MAP_ANNOT_OBLIQUE='6') 

391 else: 

392 gmtconf = dict( 

393 TICK_PEN='1.25p', 

394 TICK_LENGTH='0.2c', 

395 ANNOT_FONT_PRIMARY='1', 

396 ANNOT_FONT_SIZE_PRIMARY='12p', 

397 LABEL_FONT='1', 

398 LABEL_FONT_SIZE='12p', 

399 CHAR_ENCODING='ISOLatin1+', 

400 BASEMAP_TYPE='fancy', 

401 PLOT_DEGREE_FORMAT='D', 

402 PAPER_MEDIA='Custom_%ix%i' % ( 

403 w*gmtpy.cm, 

404 h*gmtpy.cm), 

405 GRID_PEN_PRIMARY='thinnest/0/50/0', 

406 DOTS_PR_INCH='1200', 

407 OBLIQUE_ANNOTATION='6') 

408 

409 gmtconf.update( 

410 (k.upper(), v) for (k, v) in self.gmt_config.items()) 

411 

412 gmt = gmtpy.GMT(config=gmtconf, version=self._gmtversion) 

413 

414 layout = gmt.default_layout() 

415 

416 layout.set_fixed_margins(*[x*cm for x in self._expand_margins()]) 

417 

418 widget = layout.get_widget() 

419 widget['P'] = widget['J'] 

420 widget['J'] = ('-JA%g/%g' % (self.lon, self.lat)) + '/%(width)gp' 

421 scaler['R'] = '-R%g/%g/%g/%gr' % self._corners 

422 

423 # aspect = gmtpy.aspect_for_projection( 

424 # gmt.installation['version'], *(widget.J() + scaler.R())) 

425 

426 aspect = self._map_aspect(jr=widget.J() + scaler.R()) 

427 widget.set_aspect(aspect) 

428 

429 self._gmt = gmt 

430 self._layout = layout 

431 self._widget = widget 

432 self._jxyr = self._widget.JXY() + self._scaler.R() 

433 self._pxyr = self._widget.PXY() + [ 

434 '-R%g/%g/%g/%g' % (0, widget.width(), 0, widget.height())] 

435 self._have_drawn_axes = False 

436 self._have_drawn_labels = False 

437 

438 def _draw_background(self): 

439 self._have_topo_land = False 

440 self._have_topo_ocean = False 

441 if self.show_topo: 

442 self._have_topo = self._draw_topo() 

443 

444 self._draw_basefeatures() 

445 

446 def _get_topo_tile(self, k): 

447 t = None 

448 demname = None 

449 for dem in self._dems[k]: 

450 t = topo.get(dem, self._wesn) 

451 demname = dem 

452 if t is not None: 

453 break 

454 

455 if not t: 

456 raise NoTopo() 

457 

458 return t, demname 

459 

460 def _prep_topo(self, k): 

461 gmt = self._gmt 

462 t, demname = self._get_topo_tile(k) 

463 

464 if demname not in self._prep_topo_have: 

465 

466 grdfile = gmt.tempfilename() 

467 

468 is_flat = num.all(t.data[0] == t.data) 

469 

470 gmtpy.savegrd( 

471 t.x(), t.y(), t.data, filename=grdfile, naming='lonlat') 

472 

473 if self.illuminate and not is_flat: 

474 if k == 'ocean': 

475 factor = self.illuminate_factor_ocean 

476 else: 

477 factor = self.illuminate_factor_land 

478 

479 ilumfn = gmt.tempfilename() 

480 gmt.grdgradient( 

481 grdfile, 

482 N='e%g' % factor, 

483 A=-45, 

484 G=ilumfn, 

485 out_discard=True) 

486 

487 ilumargs = ['-I%s' % ilumfn] 

488 else: 

489 ilumargs = [] 

490 

491 if self.replace_topo_color_only: 

492 t2 = self.replace_topo_color_only 

493 grdfile2 = gmt.tempfilename() 

494 

495 gmtpy.savegrd( 

496 t2.x(), t2.y(), t2.data, filename=grdfile2, 

497 naming='lonlat') 

498 

499 if gmt.is_gmt5(): 

500 gmt.grdsample( 

501 grdfile2, 

502 G=grdfile, 

503 n='l', 

504 I='%g/%g' % (t.dx, t.dy), # noqa 

505 R=grdfile, 

506 out_discard=True) 

507 else: 

508 gmt.grdsample( 

509 grdfile2, 

510 G=grdfile, 

511 Q='l', 

512 I='%g/%g' % (t.dx, t.dy), # noqa 

513 R=grdfile, 

514 out_discard=True) 

515 

516 gmt.grdmath( 

517 grdfile, '0.0', 'AND', '=', grdfile2, 

518 out_discard=True) 

519 

520 grdfile = grdfile2 

521 

522 self._prep_topo_have[demname] = grdfile, ilumargs 

523 

524 return self._prep_topo_have[demname] 

525 

526 def _draw_topo(self): 

527 widget = self._widget 

528 scaler = self._scaler 

529 gmt = self._gmt 

530 cres = self._coastline_resolution 

531 minarea = self._minarea 

532 

533 JXY = widget.JXY() 

534 R = scaler.R() 

535 

536 try: 

537 grdfile, ilumargs = self._prep_topo('ocean') 

538 gmt.pscoast(D=cres, S='c', A=minarea, *(JXY+R)) 

539 gmt.grdimage(grdfile, C=topo.cpt(self.topo_cpt_wet), 

540 *(ilumargs+JXY+R)) 

541 gmt.pscoast(Q=True, *(JXY+R)) 

542 self._have_topo_ocean = True 

543 except NoTopo: 

544 self._have_topo_ocean = False 

545 

546 try: 

547 grdfile, ilumargs = self._prep_topo('land') 

548 gmt.pscoast(D=cres, G='c', A=minarea, *(JXY+R)) 

549 gmt.grdimage(grdfile, C=topo.cpt(self.topo_cpt_dry), 

550 *(ilumargs+JXY+R)) 

551 gmt.pscoast(Q=True, *(JXY+R)) 

552 self._have_topo_land = True 

553 except NoTopo: 

554 self._have_topo_land = False 

555 

556 def _draw_topo_scale(self, label='Elevation [km]'): 

557 dry = read_cpt(topo.cpt(self.topo_cpt_dry)) 

558 wet = read_cpt(topo.cpt(self.topo_cpt_wet)) 

559 combi = cpt_merge_wet_dry(wet, dry) 

560 for level in combi.levels: 

561 level.vmin /= km 

562 level.vmax /= km 

563 

564 topo_cpt = self.gmt.tempfilename() + '.cpt' 

565 write_cpt(combi, topo_cpt) 

566 

567 (w, h), (xo, yo) = self.widget.get_size() 

568 self.gmt.psscale( 

569 D='%gp/%gp/%gp/%gph' % (xo + 0.5*w, yo - 2.0*gmtpy.cm, w, 

570 0.5*gmtpy.cm), 

571 C=topo_cpt, 

572 B='1:%s:' % label) 

573 

574 def _draw_basefeatures(self): 

575 gmt = self._gmt 

576 cres = self._coastline_resolution 

577 rivers = self._rivers 

578 minarea = self._minarea 

579 

580 color_wet = self.color_wet 

581 color_dry = self.color_dry 

582 

583 if self.show_rivers and rivers: 

584 rivers = ['-Ir/0.25p,%s' % gmtpy.color(self.color_wet)] 

585 else: 

586 rivers = [] 

587 

588 fill = {} 

589 if not self._have_topo_land: 

590 fill['G'] = color_dry 

591 

592 if not self._have_topo_ocean: 

593 fill['S'] = color_wet 

594 

595 if self.show_boundaries: 

596 fill['N'] = '1/1p,%s,%s' % ( 

597 gmtpy.color(self.color_boundaries), 'solid') 

598 

599 gmt.pscoast( 

600 D=cres, 

601 W='thinnest,%s' % gmtpy.color(darken(gmtpy.color_tup(color_dry))), 

602 A=minarea, 

603 *(rivers+self._jxyr), **fill) 

604 

605 if self.show_plates: 

606 self.draw_plates() 

607 

608 def _draw_axes(self): 

609 gmt = self._gmt 

610 scaler = self._scaler 

611 widget = self._widget 

612 

613 if self.axes_layout is None: 

614 if self.lat > 0.0: 

615 axes_layout = 'WSen' 

616 else: 

617 axes_layout = 'WseN' 

618 else: 

619 axes_layout = self.axes_layout 

620 

621 scale_km = nice_value(self.radius/5.) / 1000. 

622 

623 if self.show_center_mark: 

624 gmt.psxy( 

625 in_rows=[[self.lon, self.lat]], 

626 S='c20p', W='2p,black', 

627 *self._jxyr) 

628 

629 if self.show_grid: 

630 btmpl = ('%(xinc)gg%(xinc)g:%(xlabel)s:/' 

631 '%(yinc)gg%(yinc)g:%(ylabel)s:') 

632 else: 

633 btmpl = '%(xinc)g:%(xlabel)s:/%(yinc)g:%(ylabel)s:' 

634 

635 if self.show_scale: 

636 scale = 'x%gp/%gp/%g/%g/%gk' % ( 

637 6./7*widget.width(), 

638 widget.height()/7., 

639 self.lon, 

640 self.lat, 

641 scale_km) 

642 else: 

643 scale = False 

644 

645 gmt.psbasemap( 

646 B=(btmpl % scaler.get_params())+axes_layout, 

647 L=scale, 

648 *self._jxyr) 

649 

650 if self.comment: 

651 font_size = self.gmt.label_font_size() 

652 

653 _, east, south, _ = self._wesn 

654 if gmt.is_gmt5(): 

655 row = [ 

656 1, 0, 

657 '%gp,%s,%s' % (font_size, 0, 'black'), 'BR', 

658 self.comment] 

659 

660 farg = ['-F+f+j'] 

661 else: 

662 row = [1, 0, font_size, 0, 0, 'BR', self.comment] 

663 farg = [] 

664 

665 gmt.pstext( 

666 in_rows=[row], 

667 N=True, 

668 R=(0, 1, 0, 1), 

669 D='%gp/%gp' % (-font_size*0.2, font_size*0.3), 

670 *(widget.PXY() + farg)) 

671 

672 def draw_axes(self): 

673 if not self._have_drawn_axes: 

674 self._draw_axes() 

675 self._have_drawn_axes = True 

676 

677 def _have_coastlines(self): 

678 gmt = self._gmt 

679 cres = self._coastline_resolution 

680 minarea = self._minarea 

681 

682 checkfile = gmt.tempfilename() 

683 

684 gmt.pscoast( 

685 M=True, 

686 D=cres, 

687 W='thinnest,black', 

688 A=minarea, 

689 out_filename=checkfile, 

690 *self._jxyr) 

691 

692 points = [] 

693 with open(checkfile, 'r') as f: 

694 for line in f: 

695 ls = line.strip() 

696 if ls.startswith('#') or ls.startswith('>') or ls == '': 

697 continue 

698 plon, plat = [float(x) for x in ls.split()] 

699 points.append((plat, plon)) 

700 

701 points = num.array(points, dtype=float) 

702 return num.any(points_in_region(points, self._wesn)) 

703 

704 def have_coastlines(self): 

705 self.gmt 

706 return self._have_coastlines() 

707 

708 def project(self, lats, lons, jr=None): 

709 onepoint = False 

710 if isinstance(lats, float) and isinstance(lons, float): 

711 lats = [lats] 

712 lons = [lons] 

713 onepoint = True 

714 

715 if jr is not None: 

716 j, r = jr 

717 gmt = gmtpy.GMT(version=self._gmtversion) 

718 else: 

719 j, _, _, r = self.jxyr 

720 gmt = self.gmt 

721 

722 f = BytesIO() 

723 gmt.mapproject(j, r, in_columns=(lons, lats), out_stream=f, D='p') 

724 f.seek(0) 

725 data = num.loadtxt(f, ndmin=2) 

726 xs, ys = data.T 

727 if onepoint: 

728 xs = xs[0] 

729 ys = ys[0] 

730 return xs, ys 

731 

732 def _map_box(self, jr=None): 

733 ll_lon, ll_lat, ur_lon, ur_lat = self._corners 

734 

735 xs_corner, ys_corner = self.project( 

736 (ll_lat, ur_lat), (ll_lon, ur_lon), jr=jr) 

737 

738 w = xs_corner[1] - xs_corner[0] 

739 h = ys_corner[1] - ys_corner[0] 

740 

741 return w, h 

742 

743 def _map_aspect(self, jr=None): 

744 w, h = self._map_box(jr=jr) 

745 return h/w 

746 

747 def _draw_labels(self): 

748 points_taken = [] 

749 regions_taken = [] 

750 

751 def no_points_in_rect(xs, ys, xmin, ymin, xmax, ymax): 

752 xx = not num.any(la(la(xmin < xs, xs < xmax), 

753 la(ymin < ys, ys < ymax))) 

754 return xx 

755 

756 def roverlaps(a, b): 

757 return (a[0] < b[2] and b[0] < a[2] and 

758 a[1] < b[3] and b[1] < a[3]) 

759 

760 w, h = self._map_box() 

761 

762 label_font_size = self.gmt.label_font_size() 

763 

764 if self._labels: 

765 

766 n = len(self._labels) 

767 

768 lons, lats, texts, sx, sy, colors, fonts, font_sizes, \ 

769 angles, styles = list(zip(*self._labels)) 

770 

771 font_sizes = [ 

772 (font_size or label_font_size) for font_size in font_sizes] 

773 

774 sx = num.array(sx, dtype=float) 

775 sy = num.array(sy, dtype=float) 

776 

777 xs, ys = self.project(lats, lons) 

778 

779 points_taken.append((xs, ys)) 

780 

781 dxs = num.zeros(n) 

782 dys = num.zeros(n) 

783 

784 for i in range(n): 

785 dx, dy = gmtpy.text_box( 

786 texts[i], 

787 font=fonts[i], 

788 font_size=font_sizes[i], 

789 **styles[i]) 

790 

791 dxs[i] = dx 

792 dys[i] = dy 

793 

794 la = num.logical_and 

795 anchors_ok = ( 

796 la(xs + sx + dxs < w, ys + sy + dys < h), 

797 la(xs - sx - dxs > 0., ys - sy - dys > 0.), 

798 la(xs + sx + dxs < w, ys - sy - dys > 0.), 

799 la(xs - sx - dxs > 0., ys + sy + dys < h), 

800 ) 

801 

802 arects = [ 

803 (xs, ys, xs + sx + dxs, ys + sy + dys), 

804 (xs - sx - dxs, ys - sy - dys, xs, ys), 

805 (xs, ys - sy - dys, xs + sx + dxs, ys), 

806 (xs - sx - dxs, ys, xs, ys + sy + dys)] 

807 

808 for i in range(n): 

809 for ianch in range(4): 

810 anchors_ok[ianch][i] &= no_points_in_rect( 

811 xs, ys, *[xxx[i] for xxx in arects[ianch]]) 

812 

813 anchor_choices = [] 

814 anchor_take = [] 

815 for i in range(n): 

816 choices = [ianch for ianch in range(4) 

817 if anchors_ok[ianch][i]] 

818 anchor_choices.append(choices) 

819 if choices: 

820 anchor_take.append(choices[0]) 

821 else: 

822 anchor_take.append(None) 

823 

824 def cost(anchor_take): 

825 noverlaps = 0 

826 for i in range(n): 

827 for j in range(n): 

828 if i != j: 

829 i_take = anchor_take[i] 

830 j_take = anchor_take[j] 

831 if i_take is None or j_take is None: 

832 continue 

833 r_i = [xxx[i] for xxx in arects[i_take]] 

834 r_j = [xxx[j] for xxx in arects[j_take]] 

835 if roverlaps(r_i, r_j): 

836 noverlaps += 1 

837 

838 return noverlaps 

839 

840 cur_cost = cost(anchor_take) 

841 imax = 30 

842 while cur_cost != 0 and imax > 0: 

843 for i in range(n): 

844 for t in anchor_choices[i]: 

845 anchor_take_new = list(anchor_take) 

846 anchor_take_new[i] = t 

847 new_cost = cost(anchor_take_new) 

848 if new_cost < cur_cost: 

849 anchor_take = anchor_take_new 

850 cur_cost = new_cost 

851 

852 imax -= 1 

853 

854 while cur_cost != 0: 

855 for i in range(n): 

856 anchor_take_new = list(anchor_take) 

857 anchor_take_new[i] = None 

858 new_cost = cost(anchor_take_new) 

859 if new_cost < cur_cost: 

860 anchor_take = anchor_take_new 

861 cur_cost = new_cost 

862 break 

863 

864 anchor_strs = ['BL', 'TR', 'TL', 'BR'] 

865 

866 for i in range(n): 

867 ianchor = anchor_take[i] 

868 color = colors[i] 

869 if color is None: 

870 color = 'black' 

871 

872 if ianchor is not None: 

873 regions_taken.append([xxx[i] for xxx in arects[ianchor]]) 

874 

875 anchor = anchor_strs[ianchor] 

876 

877 yoff = [-sy[i], sy[i]][anchor[0] == 'B'] 

878 xoff = [-sx[i], sx[i]][anchor[1] == 'L'] 

879 if self.gmt.is_gmt5(): 

880 row = ( 

881 lons[i], lats[i], 

882 '%i,%s,%s' % (font_sizes[i], fonts[i], color), 

883 anchor, 

884 texts[i]) 

885 

886 farg = ['-F+f+j+a%g' % angles[i]] 

887 else: 

888 row = ( 

889 lons[i], lats[i], 

890 font_sizes[i], angles[i], fonts[i], anchor, 

891 texts[i]) 

892 farg = ['-G%s' % color] 

893 

894 self.gmt.pstext( 

895 in_rows=[row], 

896 D='%gp/%gp' % (xoff, yoff), 

897 *(self.jxyr + farg), 

898 **styles[i]) 

899 

900 if self._area_labels: 

901 

902 for lons, lats, text, color, font, font_size, style in \ 

903 self._area_labels: 

904 

905 if font_size is None: 

906 font_size = label_font_size 

907 

908 if color is None: 

909 color = 'black' 

910 

911 if self.gmt.is_gmt5(): 

912 farg = ['-F+f+j'] 

913 else: 

914 farg = ['-G%s' % color] 

915 

916 xs, ys = self.project(lats, lons) 

917 dx, dy = gmtpy.text_box( 

918 text, font=font, font_size=font_size, **style) 

919 

920 rects = [xs-0.5*dx, ys-0.5*dy, xs+0.5*dx, ys+0.5*dy] 

921 

922 locs_ok = num.ones(xs.size, dtype=bool) 

923 

924 for iloc in range(xs.size): 

925 rcandi = [xxx[iloc] for xxx in rects] 

926 

927 locs_ok[iloc] = True 

928 locs_ok[iloc] &= ( 

929 0 < rcandi[0] and rcandi[2] < w 

930 and 0 < rcandi[1] and rcandi[3] < h) 

931 

932 overlap = False 

933 for r in regions_taken: 

934 if roverlaps(r, rcandi): 

935 overlap = True 

936 break 

937 

938 locs_ok[iloc] &= not overlap 

939 

940 for xs_taken, ys_taken in points_taken: 

941 locs_ok[iloc] &= no_points_in_rect( 

942 xs_taken, ys_taken, *rcandi) 

943 

944 if not locs_ok[iloc]: 

945 break 

946 

947 rows = [] 

948 for iloc, (lon, lat) in enumerate(zip(lons, lats)): 

949 if not locs_ok[iloc]: 

950 continue 

951 

952 if self.gmt.is_gmt5(): 

953 row = ( 

954 lon, lat, 

955 '%i,%s,%s' % (font_size, font, color), 

956 'MC', 

957 text) 

958 

959 else: 

960 row = ( 

961 lon, lat, 

962 font_size, 0, font, 'MC', 

963 text) 

964 

965 rows.append(row) 

966 

967 regions_taken.append([xxx[iloc] for xxx in rects]) 

968 break 

969 

970 self.gmt.pstext( 

971 in_rows=rows, 

972 *(self.jxyr + farg), 

973 **style) 

974 

975 def draw_labels(self): 

976 self.gmt 

977 if not self._have_drawn_labels: 

978 self._draw_labels() 

979 self._have_drawn_labels = True 

980 

981 def add_label( 

982 self, lat, lon, text, 

983 offset_x=5., offset_y=5., 

984 color=None, 

985 font='1', 

986 font_size=None, 

987 angle=0, 

988 style={}): 

989 

990 if 'G' in style: 

991 style = style.copy() 

992 color = style.pop('G') 

993 

994 self._labels.append( 

995 (lon, lat, text, offset_x, offset_y, color, font, font_size, 

996 angle, style)) 

997 

998 def add_area_label( 

999 self, lat, lon, text, 

1000 color=None, 

1001 font='3', 

1002 font_size=None, 

1003 style={}): 

1004 

1005 self._area_labels.append( 

1006 (lon, lat, text, color, font, font_size, style)) 

1007 

1008 def cities_in_region(self): 

1009 from pyrocko.dataset import geonames 

1010 cities = geonames.get_cities_region(region=self.wesn, minpop=0) 

1011 cities.extend(self.custom_cities) 

1012 cities.sort(key=lambda x: x.population) 

1013 return cities 

1014 

1015 def draw_cities(self, 

1016 exact=None, 

1017 include=[], 

1018 exclude=[], 

1019 nmax_soft=10, 

1020 psxy_style=dict(S='s5p', G='black')): 

1021 

1022 cities = self.cities_in_region() 

1023 

1024 if exact is not None: 

1025 cities = [c for c in cities if c.name in exact] 

1026 minpop = None 

1027 else: 

1028 cities = [c for c in cities if c.name not in exclude] 

1029 minpop = 10**3 

1030 for minpop_new in [1e3, 3e3, 1e4, 3e4, 1e5, 3e5, 1e6, 3e6, 1e7]: 

1031 cities_new = [ 

1032 c for c in cities 

1033 if c.population > minpop_new or c.name in include] 

1034 

1035 if len(cities_new) == 0 or ( 

1036 len(cities_new) < 3 and len(cities) < nmax_soft*2): 

1037 break 

1038 

1039 cities = cities_new 

1040 minpop = minpop_new 

1041 if len(cities) <= nmax_soft: 

1042 break 

1043 

1044 if cities: 

1045 lats = [c.lat for c in cities] 

1046 lons = [c.lon for c in cities] 

1047 

1048 self.gmt.psxy( 

1049 in_columns=(lons, lats), 

1050 *self.jxyr, **psxy_style) 

1051 

1052 for c in cities: 

1053 try: 

1054 text = c.name.encode('iso-8859-1').decode('iso-8859-1') 

1055 except UnicodeEncodeError: 

1056 text = c.asciiname 

1057 

1058 self.add_label(c.lat, c.lon, text) 

1059 

1060 self._cities_minpop = minpop 

1061 

1062 def add_stations(self, stations, psxy_style=dict()): 

1063 

1064 default_psxy_style = { 

1065 'S': 't8p', 

1066 'G': 'black' 

1067 } 

1068 default_psxy_style.update(psxy_style) 

1069 

1070 lats, lons = zip(*[s.effective_latlon for s in stations]) 

1071 

1072 self.gmt.psxy( 

1073 in_columns=(lons, lats), 

1074 *self.jxyr, **default_psxy_style) 

1075 

1076 for station in stations: 

1077 self.add_label( 

1078 station.effective_lat, 

1079 station.effective_lon, 

1080 '.'.join(x for x in (station.network, station.station) if x)) 

1081 

1082 def add_kite_scene(self, scene): 

1083 tile = FloatTile( 

1084 scene.frame.llLon, 

1085 scene.frame.llLat, 

1086 scene.frame.dLon, 

1087 scene.frame.dLat, 

1088 scene.displacement) 

1089 

1090 return tile 

1091 

1092 def add_gnss_campaign(self, campaign, psxy_style=None, offset_scale=None, 

1093 labels=True, vertical=False, fontsize=10): 

1094 

1095 stations = campaign.stations 

1096 

1097 if offset_scale is None: 

1098 offset_scale = num.zeros(campaign.nstations) 

1099 for ista, sta in enumerate(stations): 

1100 for comp in sta.components.values(): 

1101 offset_scale[ista] += comp.shift 

1102 offset_scale = num.sqrt(offset_scale**2).max() 

1103 

1104 size = math.sqrt(self.height**2 + self.width**2) 

1105 scale = (size/10.) / offset_scale 

1106 logger.debug('GNSS: Using offset scale %f, map scale %f', 

1107 offset_scale, scale) 

1108 

1109 lats, lons = zip(*[s.effective_latlon for s in stations]) 

1110 

1111 if self.gmt.is_gmt6(): 

1112 sign_factor = 1. 

1113 arrow_head_placement = 'e' 

1114 else: 

1115 sign_factor = -1. 

1116 arrow_head_placement = 'b' 

1117 

1118 if vertical: 

1119 rows = [[lons[ista], lats[ista], 

1120 0., sign_factor * s.up.shift, 

1121 (s.east.sigma + s.north.sigma) if s.east.sigma else 0., 

1122 s.up.sigma, 0., 

1123 s.code if labels else None] 

1124 for ista, s in enumerate(stations) 

1125 if s.up is not None] 

1126 

1127 else: 

1128 rows = [[lons[ista], lats[ista], 

1129 sign_factor * s.east.shift, sign_factor * s.north.shift, 

1130 s.east.sigma, s.north.sigma, s.correlation_ne, 

1131 s.code if labels else None] 

1132 for ista, s in enumerate(stations) 

1133 if s.east is not None or s.north is not None] 

1134 

1135 default_psxy_style = { 

1136 'h': 0, 

1137 'W': '2p,black', 

1138 'A': '+p2p,black+{}+a40'.format(arrow_head_placement), 

1139 'G': 'black', 

1140 'L': True, 

1141 'S': 'e%dc/0.95/%d' % (scale, fontsize), 

1142 } 

1143 

1144 if not labels: 

1145 for row in rows: 

1146 row.pop(-1) 

1147 

1148 if psxy_style is not None: 

1149 default_psxy_style.update(psxy_style) 

1150 

1151 self.gmt.psvelo( 

1152 in_rows=rows, 

1153 *self.jxyr, 

1154 **default_psxy_style) 

1155 

1156 def draw_plates(self): 

1157 from pyrocko.dataset import tectonics 

1158 

1159 neast = 20 

1160 nnorth = max(1, int(round(num.round(self._hreg/self._wreg * neast)))) 

1161 norths = num.linspace(-self._hreg*0.5, self._hreg*0.5, nnorth) 

1162 easts = num.linspace(-self._wreg*0.5, self._wreg*0.5, neast) 

1163 norths2 = num.repeat(norths, neast) 

1164 easts2 = num.tile(easts, nnorth) 

1165 lats, lons = od.ne_to_latlon( 

1166 self.lat, self.lon, norths2, easts2) 

1167 

1168 bird = tectonics.PeterBird2003() 

1169 plates = bird.get_plates() 

1170 

1171 color_plates = gmtpy.color('aluminium5') 

1172 color_velocities = gmtpy.color('skyblue1') 

1173 color_velocities_lab = gmtpy.color(darken(gmtpy.color_tup('skyblue1'))) 

1174 

1175 points = num.vstack((lats, lons)).T 

1176 used = [] 

1177 for plate in plates: 

1178 mask = plate.contains_points(points) 

1179 if num.any(mask): 

1180 used.append((plate, mask)) 

1181 

1182 if len(used) > 1: 

1183 

1184 candi_fixed = {} 

1185 

1186 label_data = [] 

1187 for plate, mask in used: 

1188 

1189 mean_north = num.mean(norths2[mask]) 

1190 mean_east = num.mean(easts2[mask]) 

1191 iorder = num.argsort(num.sqrt( 

1192 (norths2[mask] - mean_north)**2 + 

1193 (easts2[mask] - mean_east)**2)) 

1194 

1195 lat_candis = lats[mask][iorder] 

1196 lon_candis = lons[mask][iorder] 

1197 

1198 candi_fixed[plate.name] = lat_candis.size 

1199 

1200 label_data.append(( 

1201 lat_candis, lon_candis, plate, color_plates)) 

1202 

1203 boundaries = bird.get_boundaries() 

1204 

1205 size = 1. 

1206 

1207 psxy_kwargs = [] 

1208 

1209 for boundary in boundaries: 

1210 if num.any(points_in_region(boundary.points, self._wesn)): 

1211 for typ, part in boundary.split_types( 

1212 [['SUB'], 

1213 ['OSR', 'CRB'], 

1214 ['OTF', 'CTF', 'OCB', 'CCB']]): 

1215 

1216 lats, lons = part.T 

1217 

1218 kwargs = {} 

1219 

1220 kwargs['in_columns'] = (lons, lats) 

1221 kwargs['W'] = '%gp,%s' % (size, color_plates) 

1222 

1223 if typ[0] == 'SUB': 

1224 if boundary.kind == '\\': 

1225 kwargs['S'] = 'f%g/%gp+t+r' % ( 

1226 0.45*size, 3.*size) 

1227 elif boundary.kind == '/': 

1228 kwargs['S'] = 'f%g/%gp+t+l' % ( 

1229 0.45*size, 3.*size) 

1230 

1231 kwargs['G'] = color_plates 

1232 

1233 elif typ[0] in ['OSR', 'CRB']: 

1234 kwargs_bg = {} 

1235 kwargs_bg['in_columns'] = (lons, lats) 

1236 kwargs_bg['W'] = '%gp,%s' % ( 

1237 size * 3, color_plates) 

1238 psxy_kwargs.append(kwargs_bg) 

1239 

1240 kwargs['W'] = '%gp,%s' % (size * 2, 'white') 

1241 

1242 psxy_kwargs.append(kwargs) 

1243 

1244 if boundary.kind == '\\': 

1245 if boundary.plate_name2 in candi_fixed: 

1246 candi_fixed[boundary.plate_name2] += \ 

1247 neast*nnorth 

1248 

1249 elif boundary.kind == '/': 

1250 if boundary.plate_name1 in candi_fixed: 

1251 candi_fixed[boundary.plate_name1] += \ 

1252 neast*nnorth 

1253 

1254 candi_fixed = [name for name in sorted( 

1255 list(candi_fixed.keys()), key=lambda name: -candi_fixed[name])] 

1256 

1257 candi_fixed.append(None) 

1258 

1259 gsrm = tectonics.GSRM1() 

1260 

1261 for name in candi_fixed: 

1262 if name not in gsrm.plate_names() \ 

1263 and name not in gsrm.plate_alt_names(): 

1264 

1265 continue 

1266 

1267 lats, lons, vnorth, veast, vnorth_err, veast_err, corr = \ 

1268 gsrm.get_velocities(name, region=self._wesn) 

1269 

1270 fixed_plate_name = name 

1271 

1272 if self.show_plate_velocities: 

1273 self.gmt.psvelo( 

1274 in_columns=( 

1275 lons, lats, veast, vnorth, veast_err, vnorth_err, 

1276 corr), 

1277 W='0.25p,%s' % color_velocities, 

1278 A='9p+e+g%s' % color_velocities, 

1279 S='e0.2p/0.95/10', 

1280 *self.jxyr) 

1281 

1282 for _ in range(len(lons) // 50 + 1): 

1283 ii = random.randint(0, len(lons)-1) 

1284 v = math.sqrt(vnorth[ii]**2 + veast[ii]**2) 

1285 self.add_label( 

1286 lats[ii], lons[ii], '%.0f' % v, 

1287 font_size=0.7*self.gmt.label_font_size(), 

1288 style=dict( 

1289 G=color_velocities_lab)) 

1290 

1291 break 

1292 

1293 if self.show_plate_names: 

1294 for (lat_candis, lon_candis, plate, color) in label_data: 

1295 full_name = bird.full_name(plate.name) 

1296 if plate.name == fixed_plate_name: 

1297 full_name = '@_' + full_name + '@_' 

1298 

1299 self.add_area_label( 

1300 lat_candis, lon_candis, 

1301 full_name, 

1302 color=color, 

1303 font='3') 

1304 

1305 for kwargs in psxy_kwargs: 

1306 self.gmt.psxy(*self.jxyr, **kwargs) 

1307 

1308 

1309def rand(mi, ma): 

1310 mi = float(mi) 

1311 ma = float(ma) 

1312 return random.random() * (ma-mi) + mi 

1313 

1314 

1315def split_region(region): 

1316 west, east, south, north = topo.positive_region(region) 

1317 if east > 180: 

1318 return [(west, 180., south, north), 

1319 (-180., east-360., south, north)] 

1320 else: 

1321 return [region] 

1322 

1323 

1324class CPTLevel(Object): 

1325 vmin = Float.T() 

1326 vmax = Float.T() 

1327 color_min = Tuple.T(3, Float.T()) 

1328 color_max = Tuple.T(3, Float.T()) 

1329 

1330 

1331class CPT(Object): 

1332 color_below = Tuple.T(3, Float.T(), optional=True) 

1333 color_above = Tuple.T(3, Float.T(), optional=True) 

1334 color_nan = Tuple.T(3, Float.T(), optional=True) 

1335 levels = List.T(CPTLevel.T()) 

1336 

1337 def scale(self, vmin, vmax): 

1338 vmin_old, vmax_old = self.levels[0].vmin, self.levels[-1].vmax 

1339 for level in self.levels: 

1340 level.vmin = (level.vmin - vmin_old) / (vmax_old - vmin_old) * \ 

1341 (vmax - vmin) + vmin 

1342 level.vmax = (level.vmax - vmin_old) / (vmax_old - vmin_old) * \ 

1343 (vmax - vmin) + vmin 

1344 

1345 def discretize(self, nlevels): 

1346 colors = [] 

1347 vals = [] 

1348 for level in self.levels: 

1349 vals.append(level.vmin) 

1350 vals.append(level.vmax) 

1351 colors.append(level.color_min) 

1352 colors.append(level.color_max) 

1353 

1354 r, g, b = num.array(colors, dtype=float).T 

1355 vals = num.array(vals, dtype=float) 

1356 

1357 vmin, vmax = self.levels[0].vmin, self.levels[-1].vmax 

1358 x = num.linspace(vmin, vmax, nlevels+1) 

1359 rd = num.interp(x, vals, r) 

1360 gd = num.interp(x, vals, g) 

1361 bd = num.interp(x, vals, b) 

1362 

1363 levels = [] 

1364 for ilevel in range(nlevels): 

1365 color = ( 

1366 float(0.5*(rd[ilevel]+rd[ilevel+1])), 

1367 float(0.5*(gd[ilevel]+gd[ilevel+1])), 

1368 float(0.5*(bd[ilevel]+bd[ilevel+1]))) 

1369 

1370 levels.append(CPTLevel( 

1371 vmin=x[ilevel], 

1372 vmax=x[ilevel+1], 

1373 color_min=color, 

1374 color_max=color)) 

1375 

1376 cpt = CPT( 

1377 color_below=self.color_below, 

1378 color_above=self.color_above, 

1379 color_nan=self.color_nan, 

1380 levels=levels) 

1381 

1382 return cpt 

1383 

1384 

1385class CPTParseError(Exception): 

1386 pass 

1387 

1388 

1389def read_cpt(filename): 

1390 with open(filename) as f: 

1391 color_below = None 

1392 color_above = None 

1393 color_nan = None 

1394 levels = [] 

1395 try: 

1396 for line in f: 

1397 line = line.strip() 

1398 toks = line.split() 

1399 

1400 if line.startswith('#'): 

1401 continue 

1402 

1403 elif line.startswith('B'): 

1404 color_below = tuple(map(float, toks[1:4])) 

1405 

1406 elif line.startswith('F'): 

1407 color_above = tuple(map(float, toks[1:4])) 

1408 

1409 elif line.startswith('N'): 

1410 color_nan = tuple(map(float, toks[1:4])) 

1411 

1412 else: 

1413 values = list(map(float, line.split())) 

1414 vmin = values[0] 

1415 color_min = tuple(values[1:4]) 

1416 vmax = values[4] 

1417 color_max = tuple(values[5:8]) 

1418 levels.append(CPTLevel( 

1419 vmin=vmin, 

1420 vmax=vmax, 

1421 color_min=color_min, 

1422 color_max=color_max)) 

1423 

1424 except Exception: 

1425 raise CPTParseError() 

1426 

1427 return CPT( 

1428 color_below=color_below, 

1429 color_above=color_above, 

1430 color_nan=color_nan, 

1431 levels=levels) 

1432 

1433 

1434def color_to_int(color): 

1435 return tuple(max(0, min(255, int(round(x)))) for x in color) 

1436 

1437 

1438def write_cpt(cpt, filename): 

1439 with open(filename, 'w') as f: 

1440 for level in cpt.levels: 

1441 f.write( 

1442 '%e %i %i %i %e %i %i %i\n' % 

1443 ((level.vmin, ) + color_to_int(level.color_min) + 

1444 (level.vmax, ) + color_to_int(level.color_max))) 

1445 

1446 if cpt.color_below: 

1447 f.write('B %i %i %i\n' % color_to_int(cpt.color_below)) 

1448 

1449 if cpt.color_above: 

1450 f.write('F %i %i %i\n' % color_to_int(cpt.color_above)) 

1451 

1452 if cpt.color_nan: 

1453 f.write('N %i %i %i\n' % color_to_int(cpt.color_nan)) 

1454 

1455 

1456def cpt_merge_wet_dry(wet, dry): 

1457 levels = [] 

1458 for level in wet.levels: 

1459 if level.vmin < 0.: 

1460 if level.vmax > 0.: 

1461 level.vmax = 0. 

1462 

1463 levels.append(level) 

1464 

1465 for level in dry.levels: 

1466 if level.vmax > 0.: 

1467 if level.vmin < 0.: 

1468 level.vmin = 0. 

1469 

1470 levels.append(level) 

1471 

1472 combi = CPT( 

1473 color_below=wet.color_below, 

1474 color_above=dry.color_above, 

1475 color_nan=dry.color_nan, 

1476 levels=levels) 

1477 

1478 return combi 

1479 

1480 

1481if __name__ == '__main__': 

1482 from pyrocko import util 

1483 util.setup_logging('pyrocko.automap', 'info') 

1484 

1485 import sys 

1486 if len(sys.argv) == 2: 

1487 

1488 n = int(sys.argv[1]) 

1489 

1490 for i in range(n): 

1491 m = Map( 

1492 lat=rand(-60., 60.), 

1493 lon=rand(-180., 180.), 

1494 radius=math.exp(rand(math.log(500*km), math.log(3000*km))), 

1495 width=30., height=30., 

1496 show_grid=True, 

1497 show_topo=True, 

1498 color_dry=(238, 236, 230), 

1499 topo_cpt_wet='light_sea_uniform', 

1500 topo_cpt_dry='light_land_uniform', 

1501 illuminate=True, 

1502 illuminate_factor_ocean=0.15, 

1503 show_rivers=False, 

1504 show_plates=True) 

1505 

1506 m.draw_cities() 

1507 print(m) 

1508 m.save('map_%02i.pdf' % i)