1# http://pyrocko.org - GPLv3
2#
3# The Pyrocko Developers, 21st Century
4# ---|P------/S----------~Lg----------
5from __future__ import absolute_import, print_function
7import math
8import random
9import logging
11try:
12 from StringIO import StringIO as BytesIO
13except ImportError:
14 from io import BytesIO
16import numpy as num
18from pyrocko.guts import (Object, Float, Bool, Int, Tuple, String, List,
19 Unicode, Dict)
20from pyrocko.guts_array import Array
21from pyrocko.dataset import topo
22from pyrocko import orthodrome as od
23from . import gmtpy
25try:
26 newstr = unicode
27except NameError:
28 newstr = str
30points_in_region = od.points_in_region
32logger = logging.getLogger('pyrocko.plot.automap')
34earthradius = 6371000.0
35r2d = 180./math.pi
36d2r = 1./r2d
37km = 1000.
38d2m = d2r*earthradius
39m2d = 1./d2m
40cm = gmtpy.cm
43def darken(c, f=0.7):
44 return (c[0]*f, c[1]*f, c[2]*f)
47def corners(lon, lat, w, h):
48 ll_lat, ll_lon = od.ne_to_latlon(lat, lon, -0.5*h, -0.5*w)
49 ur_lat, ur_lon = od.ne_to_latlon(lat, lon, 0.5*h, 0.5*w)
50 return ll_lon, ll_lat, ur_lon, ur_lat
53def extent(lon, lat, w, h, n):
54 x = num.linspace(-0.5*w, 0.5*w, n)
55 y = num.linspace(-0.5*h, 0.5*h, n)
56 slats, slons = od.ne_to_latlon(lat, lon, y[0], x)
57 nlats, nlons = od.ne_to_latlon(lat, lon, y[-1], x)
58 south = slats.min()
59 north = nlats.max()
61 wlats, wlons = od.ne_to_latlon(lat, lon, y, x[0])
62 elats, elons = od.ne_to_latlon(lat, lon, y, x[-1])
63 elons = num.where(elons < wlons, elons + 360., elons)
65 if elons.max() - elons.min() > 180 or wlons.max() - wlons.min() > 180.:
66 west = -180.
67 east = 180.
68 else:
69 west = wlons.min()
70 east = elons.max()
72 return topo.positive_region((west, east, south, north))
75class NoTopo(Exception):
76 pass
79class OutOfBounds(Exception):
80 pass
83class FloatTile(Object):
84 xmin = Float.T()
85 ymin = Float.T()
86 dx = Float.T()
87 dy = Float.T()
88 data = Array.T(shape=(None, None), dtype=float, serialize_as='table')
90 def __init__(self, xmin, ymin, dx, dy, data):
91 Object.__init__(self, init_props=False)
92 self.xmin = float(xmin)
93 self.ymin = float(ymin)
94 self.dx = float(dx)
95 self.dy = float(dy)
96 self.data = data
97 self._set_maxes()
99 def _set_maxes(self):
100 self.ny, self.nx = self.data.shape
101 self.xmax = self.xmin + (self.nx-1) * self.dx
102 self.ymax = self.ymin + (self.ny-1) * self.dy
104 def x(self):
105 return self.xmin + num.arange(self.nx) * self.dx
107 def y(self):
108 return self.ymin + num.arange(self.ny) * self.dy
110 def get(self, x, y):
111 ix = int(round((x - self.xmin) / self.dx))
112 iy = int(round((y - self.ymin) / self.dy))
113 if 0 <= ix < self.nx and 0 <= iy < self.ny:
114 return self.data[iy, ix]
115 else:
116 raise OutOfBounds()
119class City(Object):
120 def __init__(self, name, lat, lon, population=None, asciiname=None):
121 name = newstr(name)
122 lat = float(lat)
123 lon = float(lon)
124 if asciiname is None:
125 asciiname = name.encode('ascii', errors='replace')
127 if population is None:
128 population = 0
129 else:
130 population = int(population)
132 Object.__init__(self, name=name, lat=lat, lon=lon,
133 population=population, asciiname=asciiname)
135 name = Unicode.T()
136 lat = Float.T()
137 lon = Float.T()
138 population = Int.T()
139 asciiname = String.T()
142class Map(Object):
143 lat = Float.T(optional=True)
144 lon = Float.T(optional=True)
145 radius = Float.T(optional=True)
146 width = Float.T(default=20.)
147 height = Float.T(default=14.)
148 margins = List.T(Float.T())
149 illuminate = Bool.T(default=True)
150 skip_feature_factor = Float.T(default=0.02)
151 show_grid = Bool.T(default=False)
152 show_topo = Bool.T(default=True)
153 show_scale = Bool.T(default=False)
154 show_topo_scale = Bool.T(default=False)
155 show_center_mark = Bool.T(default=False)
156 show_rivers = Bool.T(default=True)
157 show_plates = Bool.T(default=False)
158 show_plate_names = Bool.T(default=False)
159 show_plate_velocities = Bool.T(default=False)
160 show_boundaries = Bool.T(default=False)
161 illuminate_factor_land = Float.T(default=0.5)
162 illuminate_factor_ocean = Float.T(default=0.25)
163 color_wet = Tuple.T(3, Int.T(), default=(216, 242, 254))
164 color_dry = Tuple.T(3, Int.T(), default=(172, 208, 165))
165 color_boundaries = Tuple.T(3, Int.T(), default=(1, 1, 1))
166 topo_resolution_min = Float.T(
167 default=40.,
168 help='minimum resolution of topography [dpi]')
169 topo_resolution_max = Float.T(
170 default=200.,
171 help='maximum resolution of topography [dpi]')
172 replace_topo_color_only = FloatTile.T(
173 optional=True,
174 help='replace topo color while keeping topographic shading')
175 topo_cpt_wet = String.T(default='light_sea')
176 topo_cpt_dry = String.T(default='light_land')
177 axes_layout = String.T(optional=True)
178 custom_cities = List.T(City.T())
179 gmt_config = Dict.T(String.T(), String.T())
180 comment = String.T(optional=True)
182 def __init__(self, gmtversion='newest', **kwargs):
183 Object.__init__(self, **kwargs)
184 self._gmt = None
185 self._scaler = None
186 self._widget = None
187 self._corners = None
188 self._wesn = None
189 self._minarea = None
190 self._coastline_resolution = None
191 self._rivers = None
192 self._dems = None
193 self._have_topo_land = None
194 self._have_topo_ocean = None
195 self._jxyr = None
196 self._prep_topo_have = None
197 self._labels = []
198 self._area_labels = []
199 self._gmtversion = gmtversion
201 def save(self, outpath, resolution=75., oversample=2., size=None,
202 width=None, height=None, psconvert=False):
204 '''
205 Save the image.
207 Save the image to ``outpath``. The format is determined by the filename
208 extension. Formats are handled as follows: ``'.eps'`` and ``'.ps'``
209 produce EPS and PS, respectively, directly with GMT. If the file name
210 ends with ``'.pdf'``, GMT output is fed through ``gmtpy-epstopdf`` to
211 create a PDF file. For any other filename extension, output is first
212 converted to PDF with ``gmtpy-epstopdf``, then with ``pdftocairo`` to
213 PNG with a resolution oversampled by the factor ``oversample`` and
214 finally the PNG is downsampled and converted to the target format with
215 ``convert``. The resolution of rasterized target image can be
216 controlled either by ``resolution`` in DPI or by specifying ``width``
217 or ``height`` or ``size``, where the latter fits the image into a
218 square with given side length. To save transparency use
219 ``psconvert=True``.
220 '''
222 gmt = self.gmt
223 self.draw_labels()
224 self.draw_axes()
225 if self.show_topo and self.show_topo_scale:
226 self._draw_topo_scale()
228 gmt.save(outpath, resolution=resolution, oversample=oversample,
229 size=size, width=width, height=height, psconvert=psconvert)
231 @property
232 def scaler(self):
233 if self._scaler is None:
234 self._setup_geometry()
236 return self._scaler
238 @property
239 def wesn(self):
240 if self._wesn is None:
241 self._setup_geometry()
243 return self._wesn
245 @property
246 def widget(self):
247 if self._widget is None:
248 self._setup()
250 return self._widget
252 @property
253 def layout(self):
254 if self._layout is None:
255 self._setup()
257 return self._layout
259 @property
260 def jxyr(self):
261 if self._jxyr is None:
262 self._setup()
264 return self._jxyr
266 @property
267 def pxyr(self):
268 if self._pxyr is None:
269 self._setup()
271 return self._pxyr
273 @property
274 def gmt(self):
275 if self._gmt is None:
276 self._setup()
278 if self._have_topo_ocean is None:
279 self._draw_background()
281 return self._gmt
283 def _setup(self):
284 if not self._widget:
285 self._setup_geometry()
287 self._setup_lod()
288 self._setup_gmt()
290 def _setup_geometry(self):
291 wpage, hpage = self.width, self.height
292 ml, mr, mt, mb = self._expand_margins()
293 wpage -= ml + mr
294 hpage -= mt + mb
296 wreg = self.radius * 2.0
297 hreg = self.radius * 2.0
298 if wpage >= hpage:
299 wreg *= wpage/hpage
300 else:
301 hreg *= hpage/wpage
303 self._wreg = wreg
304 self._hreg = hreg
306 self._corners = corners(self.lon, self.lat, wreg, hreg)
307 west, east, south, north = extent(self.lon, self.lat, wreg, hreg, 10)
309 x, y, z = ((west, east), (south, north), (-6000., 4500.))
311 xax = gmtpy.Ax(mode='min-max', approx_ticks=4.)
312 yax = gmtpy.Ax(mode='min-max', approx_ticks=4.)
313 zax = gmtpy.Ax(mode='min-max', inc=1000., label='Height',
314 scaled_unit='km', scaled_unit_factor=0.001)
316 scaler = gmtpy.ScaleGuru(data_tuples=[(x, y, z)], axes=(xax, yax, zax))
318 par = scaler.get_params()
320 west = par['xmin']
321 east = par['xmax']
322 south = par['ymin']
323 north = par['ymax']
325 self._wesn = west, east, south, north
326 self._scaler = scaler
328 def _setup_lod(self):
329 w, e, s, n = self._wesn
330 if self.radius > 1500.*km:
331 coastline_resolution = 'i'
332 rivers = False
333 else:
334 coastline_resolution = 'f'
335 rivers = True
337 self._minarea = (self.skip_feature_factor * self.radius/km)**2
339 self._coastline_resolution = coastline_resolution
340 self._rivers = rivers
342 self._prep_topo_have = {}
343 self._dems = {}
345 cm2inch = gmtpy.cm/gmtpy.inch
347 dmin = 2.0 * self.radius * m2d / (self.topo_resolution_max *
348 (self.height * cm2inch))
349 dmax = 2.0 * self.radius * m2d / (self.topo_resolution_min *
350 (self.height * cm2inch))
352 for k in ['ocean', 'land']:
353 self._dems[k] = topo.select_dem_names(k, dmin, dmax, self._wesn)
354 if self._dems[k]:
355 logger.debug('using topography dataset %s for %s'
356 % (','.join(self._dems[k]), k))
358 def _expand_margins(self):
359 if len(self.margins) == 0 or len(self.margins) > 4:
360 ml = mr = mt = mb = 2.0
361 elif len(self.margins) == 1:
362 ml = mr = mt = mb = self.margins[0]
363 elif len(self.margins) == 2:
364 ml = mr = self.margins[0]
365 mt = mb = self.margins[1]
366 elif len(self.margins) == 4:
367 ml, mr, mt, mb = self.margins
369 return ml, mr, mt, mb
371 def _setup_gmt(self):
372 w, h = self.width, self.height
373 scaler = self._scaler
375 if gmtpy.is_gmt5(self._gmtversion):
376 gmtconf = dict(
377 MAP_TICK_PEN_PRIMARY='1.25p',
378 MAP_TICK_PEN_SECONDARY='1.25p',
379 MAP_TICK_LENGTH_PRIMARY='0.2c',
380 MAP_TICK_LENGTH_SECONDARY='0.6c',
381 FONT_ANNOT_PRIMARY='12p,1,black',
382 FONT_LABEL='12p,1,black',
383 PS_CHAR_ENCODING='ISOLatin1+',
384 MAP_FRAME_TYPE='fancy',
385 FORMAT_GEO_MAP='D',
386 PS_MEDIA='Custom_%ix%i' % (
387 w*gmtpy.cm,
388 h*gmtpy.cm),
389 PS_PAGE_ORIENTATION='portrait',
390 MAP_GRID_PEN_PRIMARY='thinnest,0/50/0',
391 MAP_ANNOT_OBLIQUE='6')
392 else:
393 gmtconf = dict(
394 TICK_PEN='1.25p',
395 TICK_LENGTH='0.2c',
396 ANNOT_FONT_PRIMARY='1',
397 ANNOT_FONT_SIZE_PRIMARY='12p',
398 LABEL_FONT='1',
399 LABEL_FONT_SIZE='12p',
400 CHAR_ENCODING='ISOLatin1+',
401 BASEMAP_TYPE='fancy',
402 PLOT_DEGREE_FORMAT='D',
403 PAPER_MEDIA='Custom_%ix%i' % (
404 w*gmtpy.cm,
405 h*gmtpy.cm),
406 GRID_PEN_PRIMARY='thinnest/0/50/0',
407 DOTS_PR_INCH='1200',
408 OBLIQUE_ANNOTATION='6')
410 gmtconf.update(
411 (k.upper(), v) for (k, v) in self.gmt_config.items())
413 gmt = gmtpy.GMT(config=gmtconf, version=self._gmtversion)
415 layout = gmt.default_layout()
417 layout.set_fixed_margins(*[x*cm for x in self._expand_margins()])
419 widget = layout.get_widget()
420 widget['P'] = widget['J']
421 widget['J'] = ('-JA%g/%g' % (self.lon, self.lat)) + '/%(width)gp'
422 scaler['R'] = '-R%g/%g/%g/%gr' % self._corners
424 # aspect = gmtpy.aspect_for_projection(
425 # gmt.installation['version'], *(widget.J() + scaler.R()))
427 aspect = self._map_aspect(jr=widget.J() + scaler.R())
428 widget.set_aspect(aspect)
430 self._gmt = gmt
431 self._layout = layout
432 self._widget = widget
433 self._jxyr = self._widget.JXY() + self._scaler.R()
434 self._pxyr = self._widget.PXY() + [
435 '-R%g/%g/%g/%g' % (0, widget.width(), 0, widget.height())]
436 self._have_drawn_axes = False
437 self._have_drawn_labels = False
439 def _draw_background(self):
440 self._have_topo_land = False
441 self._have_topo_ocean = False
442 if self.show_topo:
443 self._have_topo = self._draw_topo()
445 self._draw_basefeatures()
447 def _get_topo_tile(self, k):
448 t = None
449 demname = None
450 for dem in self._dems[k]:
451 t = topo.get(dem, self._wesn)
452 demname = dem
453 if t is not None:
454 break
456 if not t:
457 raise NoTopo()
459 return t, demname
461 def _prep_topo(self, k):
462 gmt = self._gmt
463 t, demname = self._get_topo_tile(k)
465 if demname not in self._prep_topo_have:
467 grdfile = gmt.tempfilename()
469 is_flat = num.all(t.data[0] == t.data)
471 gmtpy.savegrd(
472 t.x(), t.y(), t.data, filename=grdfile, naming='lonlat')
474 if self.illuminate and not is_flat:
475 if k == 'ocean':
476 factor = self.illuminate_factor_ocean
477 else:
478 factor = self.illuminate_factor_land
480 ilumfn = gmt.tempfilename()
481 gmt.grdgradient(
482 grdfile,
483 N='e%g' % factor,
484 A=-45,
485 G=ilumfn,
486 out_discard=True)
488 ilumargs = ['-I%s' % ilumfn]
489 else:
490 ilumargs = []
492 if self.replace_topo_color_only:
493 t2 = self.replace_topo_color_only
494 grdfile2 = gmt.tempfilename()
496 gmtpy.savegrd(
497 t2.x(), t2.y(), t2.data, filename=grdfile2,
498 naming='lonlat')
500 if gmt.is_gmt5():
501 gmt.grdsample(
502 grdfile2,
503 G=grdfile,
504 n='l',
505 I='%g/%g' % (t.dx, t.dy), # noqa
506 R=grdfile,
507 out_discard=True)
508 else:
509 gmt.grdsample(
510 grdfile2,
511 G=grdfile,
512 Q='l',
513 I='%g/%g' % (t.dx, t.dy), # noqa
514 R=grdfile,
515 out_discard=True)
517 gmt.grdmath(
518 grdfile, '0.0', 'AND', '=', grdfile2,
519 out_discard=True)
521 grdfile = grdfile2
523 self._prep_topo_have[demname] = grdfile, ilumargs
525 return self._prep_topo_have[demname]
527 def _draw_topo(self):
528 widget = self._widget
529 scaler = self._scaler
530 gmt = self._gmt
531 cres = self._coastline_resolution
532 minarea = self._minarea
534 JXY = widget.JXY()
535 R = scaler.R()
537 try:
538 grdfile, ilumargs = self._prep_topo('ocean')
539 gmt.pscoast(D=cres, S='c', A=minarea, *(JXY+R))
540 gmt.grdimage(grdfile, C=topo.cpt(self.topo_cpt_wet),
541 *(ilumargs+JXY+R))
542 gmt.pscoast(Q=True, *(JXY+R))
543 self._have_topo_ocean = True
544 except NoTopo:
545 self._have_topo_ocean = False
547 try:
548 grdfile, ilumargs = self._prep_topo('land')
549 gmt.pscoast(D=cres, G='c', A=minarea, *(JXY+R))
550 gmt.grdimage(grdfile, C=topo.cpt(self.topo_cpt_dry),
551 *(ilumargs+JXY+R))
552 gmt.pscoast(Q=True, *(JXY+R))
553 self._have_topo_land = True
554 except NoTopo:
555 self._have_topo_land = False
557 def _draw_topo_scale(self, label='Elevation [km]'):
558 dry = read_cpt(topo.cpt(self.topo_cpt_dry))
559 wet = read_cpt(topo.cpt(self.topo_cpt_wet))
560 combi = cpt_merge_wet_dry(wet, dry)
561 for level in combi.levels:
562 level.vmin /= km
563 level.vmax /= km
565 topo_cpt = self.gmt.tempfilename() + '.cpt'
566 write_cpt(combi, topo_cpt)
568 (w, h), (xo, yo) = self.widget.get_size()
569 self.gmt.psscale(
570 D='%gp/%gp/%gp/%gph' % (xo + 0.5*w, yo - 2.0*gmtpy.cm, w,
571 0.5*gmtpy.cm),
572 C=topo_cpt,
573 B='1:%s:' % label)
575 def _draw_basefeatures(self):
576 gmt = self._gmt
577 cres = self._coastline_resolution
578 rivers = self._rivers
579 minarea = self._minarea
581 color_wet = self.color_wet
582 color_dry = self.color_dry
584 if self.show_rivers and rivers:
585 rivers = ['-Ir/0.25p,%s' % gmtpy.color(self.color_wet)]
586 else:
587 rivers = []
589 fill = {}
590 if not self._have_topo_land:
591 fill['G'] = color_dry
593 if not self._have_topo_ocean:
594 fill['S'] = color_wet
596 if self.show_boundaries:
597 fill['N'] = '1/1p,%s,%s' % (
598 gmtpy.color(self.color_boundaries), 'solid')
600 gmt.pscoast(
601 D=cres,
602 W='thinnest,%s' % gmtpy.color(darken(gmtpy.color_tup(color_dry))),
603 A=minarea,
604 *(rivers+self._jxyr), **fill)
606 if self.show_plates:
607 self.draw_plates()
609 def _draw_axes(self):
610 gmt = self._gmt
611 scaler = self._scaler
612 widget = self._widget
614 if self.axes_layout is None:
615 if self.lat > 0.0:
616 axes_layout = 'WSen'
617 else:
618 axes_layout = 'WseN'
619 else:
620 axes_layout = self.axes_layout
622 scale_km = gmtpy.nice_value(self.radius/5.) / 1000.
624 if self.show_center_mark:
625 gmt.psxy(
626 in_rows=[[self.lon, self.lat]],
627 S='c20p', W='2p,black',
628 *self._jxyr)
630 if self.show_grid:
631 btmpl = ('%(xinc)gg%(xinc)g:%(xlabel)s:/'
632 '%(yinc)gg%(yinc)g:%(ylabel)s:')
633 else:
634 btmpl = '%(xinc)g:%(xlabel)s:/%(yinc)g:%(ylabel)s:'
636 if self.show_scale:
637 scale = 'x%gp/%gp/%g/%g/%gk' % (
638 6./7*widget.width(),
639 widget.height()/7.,
640 self.lon,
641 self.lat,
642 scale_km)
643 else:
644 scale = False
646 gmt.psbasemap(
647 B=(btmpl % scaler.get_params())+axes_layout,
648 L=scale,
649 *self._jxyr)
651 if self.comment:
652 font_size = self.gmt.label_font_size()
654 _, east, south, _ = self._wesn
655 if gmt.is_gmt5():
656 row = [
657 1, 0,
658 '%gp,%s,%s' % (font_size, 0, 'black'), 'BR',
659 self.comment]
661 farg = ['-F+f+j']
662 else:
663 row = [1, 0, font_size, 0, 0, 'BR', self.comment]
664 farg = []
666 gmt.pstext(
667 in_rows=[row],
668 N=True,
669 R=(0, 1, 0, 1),
670 D='%gp/%gp' % (-font_size*0.2, font_size*0.3),
671 *(widget.PXY() + farg))
673 def draw_axes(self):
674 if not self._have_drawn_axes:
675 self._draw_axes()
676 self._have_drawn_axes = True
678 def _have_coastlines(self):
679 gmt = self._gmt
680 cres = self._coastline_resolution
681 minarea = self._minarea
683 checkfile = gmt.tempfilename()
685 gmt.pscoast(
686 M=True,
687 D=cres,
688 W='thinnest,black',
689 A=minarea,
690 out_filename=checkfile,
691 *self._jxyr)
693 points = []
694 with open(checkfile, 'r') as f:
695 for line in f:
696 ls = line.strip()
697 if ls.startswith('#') or ls.startswith('>') or ls == '':
698 continue
699 plon, plat = [float(x) for x in ls.split()]
700 points.append((plat, plon))
702 points = num.array(points, dtype=float)
703 return num.any(points_in_region(points, self._wesn))
705 def have_coastlines(self):
706 self.gmt
707 return self._have_coastlines()
709 def project(self, lats, lons, jr=None):
710 onepoint = False
711 if isinstance(lats, float) and isinstance(lons, float):
712 lats = [lats]
713 lons = [lons]
714 onepoint = True
716 if jr is not None:
717 j, r = jr
718 gmt = gmtpy.GMT(version=self._gmtversion)
719 else:
720 j, _, _, r = self.jxyr
721 gmt = self.gmt
723 f = BytesIO()
724 gmt.mapproject(j, r, in_columns=(lons, lats), out_stream=f, D='p')
725 f.seek(0)
726 data = num.loadtxt(f, ndmin=2)
727 xs, ys = data.T
728 if onepoint:
729 xs = xs[0]
730 ys = ys[0]
731 return xs, ys
733 def _map_box(self, jr=None):
734 ll_lon, ll_lat, ur_lon, ur_lat = self._corners
736 xs_corner, ys_corner = self.project(
737 (ll_lat, ur_lat), (ll_lon, ur_lon), jr=jr)
739 w = xs_corner[1] - xs_corner[0]
740 h = ys_corner[1] - ys_corner[0]
742 return w, h
744 def _map_aspect(self, jr=None):
745 w, h = self._map_box(jr=jr)
746 return h/w
748 def _draw_labels(self):
749 points_taken = []
750 regions_taken = []
752 def no_points_in_rect(xs, ys, xmin, ymin, xmax, ymax):
753 xx = not num.any(la(la(xmin < xs, xs < xmax),
754 la(ymin < ys, ys < ymax)))
755 return xx
757 def roverlaps(a, b):
758 return (a[0] < b[2] and b[0] < a[2] and
759 a[1] < b[3] and b[1] < a[3])
761 w, h = self._map_box()
763 label_font_size = self.gmt.label_font_size()
765 if self._labels:
767 n = len(self._labels)
769 lons, lats, texts, sx, sy, colors, fonts, font_sizes, \
770 angles, styles = list(zip(*self._labels))
772 font_sizes = [
773 (font_size or label_font_size) for font_size in font_sizes]
775 sx = num.array(sx, dtype=float)
776 sy = num.array(sy, dtype=float)
778 xs, ys = self.project(lats, lons)
780 points_taken.append((xs, ys))
782 dxs = num.zeros(n)
783 dys = num.zeros(n)
785 for i in range(n):
786 dx, dy = gmtpy.text_box(
787 texts[i],
788 font=fonts[i],
789 font_size=font_sizes[i],
790 **styles[i])
792 dxs[i] = dx
793 dys[i] = dy
795 la = num.logical_and
796 anchors_ok = (
797 la(xs + sx + dxs < w, ys + sy + dys < h),
798 la(xs - sx - dxs > 0., ys - sy - dys > 0.),
799 la(xs + sx + dxs < w, ys - sy - dys > 0.),
800 la(xs - sx - dxs > 0., ys + sy + dys < h),
801 )
803 arects = [
804 (xs, ys, xs + sx + dxs, ys + sy + dys),
805 (xs - sx - dxs, ys - sy - dys, xs, ys),
806 (xs, ys - sy - dys, xs + sx + dxs, ys),
807 (xs - sx - dxs, ys, xs, ys + sy + dys)]
809 for i in range(n):
810 for ianch in range(4):
811 anchors_ok[ianch][i] &= no_points_in_rect(
812 xs, ys, *[xxx[i] for xxx in arects[ianch]])
814 anchor_choices = []
815 anchor_take = []
816 for i in range(n):
817 choices = [ianch for ianch in range(4)
818 if anchors_ok[ianch][i]]
819 anchor_choices.append(choices)
820 if choices:
821 anchor_take.append(choices[0])
822 else:
823 anchor_take.append(None)
825 def cost(anchor_take):
826 noverlaps = 0
827 for i in range(n):
828 for j in range(n):
829 if i != j:
830 i_take = anchor_take[i]
831 j_take = anchor_take[j]
832 if i_take is None or j_take is None:
833 continue
834 r_i = [xxx[i] for xxx in arects[i_take]]
835 r_j = [xxx[j] for xxx in arects[j_take]]
836 if roverlaps(r_i, r_j):
837 noverlaps += 1
839 return noverlaps
841 cur_cost = cost(anchor_take)
842 imax = 30
843 while cur_cost != 0 and imax > 0:
844 for i in range(n):
845 for t in anchor_choices[i]:
846 anchor_take_new = list(anchor_take)
847 anchor_take_new[i] = t
848 new_cost = cost(anchor_take_new)
849 if new_cost < cur_cost:
850 anchor_take = anchor_take_new
851 cur_cost = new_cost
853 imax -= 1
855 while cur_cost != 0:
856 for i in range(n):
857 anchor_take_new = list(anchor_take)
858 anchor_take_new[i] = None
859 new_cost = cost(anchor_take_new)
860 if new_cost < cur_cost:
861 anchor_take = anchor_take_new
862 cur_cost = new_cost
863 break
865 anchor_strs = ['BL', 'TR', 'TL', 'BR']
867 for i in range(n):
868 ianchor = anchor_take[i]
869 color = colors[i]
870 if color is None:
871 color = 'black'
873 if ianchor is not None:
874 regions_taken.append([xxx[i] for xxx in arects[ianchor]])
876 anchor = anchor_strs[ianchor]
878 yoff = [-sy[i], sy[i]][anchor[0] == 'B']
879 xoff = [-sx[i], sx[i]][anchor[1] == 'L']
880 if self.gmt.is_gmt5():
881 row = (
882 lons[i], lats[i],
883 '%i,%s,%s' % (font_sizes[i], fonts[i], color),
884 anchor,
885 texts[i])
887 farg = ['-F+f+j+a%g' % angles[i]]
888 else:
889 row = (
890 lons[i], lats[i],
891 font_sizes[i], angles[i], fonts[i], anchor,
892 texts[i])
893 farg = ['-G%s' % color]
895 self.gmt.pstext(
896 in_rows=[row],
897 D='%gp/%gp' % (xoff, yoff),
898 *(self.jxyr + farg),
899 **styles[i])
901 if self._area_labels:
903 for lons, lats, text, color, font, font_size, style in \
904 self._area_labels:
906 if font_size is None:
907 font_size = label_font_size
909 if color is None:
910 color = 'black'
912 if self.gmt.is_gmt5():
913 farg = ['-F+f+j']
914 else:
915 farg = ['-G%s' % color]
917 xs, ys = self.project(lats, lons)
918 dx, dy = gmtpy.text_box(
919 text, font=font, font_size=font_size, **style)
921 rects = [xs-0.5*dx, ys-0.5*dy, xs+0.5*dx, ys+0.5*dy]
923 locs_ok = num.ones(xs.size, dtype=num.bool)
925 for iloc in range(xs.size):
926 rcandi = [xxx[iloc] for xxx in rects]
928 locs_ok[iloc] = True
929 locs_ok[iloc] &= (
930 0 < rcandi[0] and rcandi[2] < w
931 and 0 < rcandi[1] and rcandi[3] < h)
933 overlap = False
934 for r in regions_taken:
935 if roverlaps(r, rcandi):
936 overlap = True
937 break
939 locs_ok[iloc] &= not overlap
941 for xs_taken, ys_taken in points_taken:
942 locs_ok[iloc] &= no_points_in_rect(
943 xs_taken, ys_taken, *rcandi)
945 if not locs_ok[iloc]:
946 break
948 rows = []
949 for iloc, (lon, lat) in enumerate(zip(lons, lats)):
950 if not locs_ok[iloc]:
951 continue
953 if self.gmt.is_gmt5():
954 row = (
955 lon, lat,
956 '%i,%s,%s' % (font_size, font, color),
957 'MC',
958 text)
960 else:
961 row = (
962 lon, lat,
963 font_size, 0, font, 'MC',
964 text)
966 rows.append(row)
968 regions_taken.append([xxx[iloc] for xxx in rects])
969 break
971 self.gmt.pstext(
972 in_rows=rows,
973 *(self.jxyr + farg),
974 **style)
976 def draw_labels(self):
977 self.gmt
978 if not self._have_drawn_labels:
979 self._draw_labels()
980 self._have_drawn_labels = True
982 def add_label(
983 self, lat, lon, text,
984 offset_x=5., offset_y=5.,
985 color=None,
986 font='1',
987 font_size=None,
988 angle=0,
989 style={}):
991 if 'G' in style:
992 style = style.copy()
993 color = style.pop('G')
995 self._labels.append(
996 (lon, lat, text, offset_x, offset_y, color, font, font_size,
997 angle, style))
999 def add_area_label(
1000 self, lat, lon, text,
1001 color=None,
1002 font='3',
1003 font_size=None,
1004 style={}):
1006 self._area_labels.append(
1007 (lon, lat, text, color, font, font_size, style))
1009 def cities_in_region(self):
1010 from pyrocko.dataset import geonames
1011 cities = geonames.get_cities_region(region=self.wesn, minpop=0)
1012 cities.extend(self.custom_cities)
1013 cities.sort(key=lambda x: x.population)
1014 return cities
1016 def draw_cities(self,
1017 exact=None,
1018 include=[],
1019 exclude=[],
1020 nmax_soft=10,
1021 psxy_style=dict(S='s5p', G='black')):
1023 cities = self.cities_in_region()
1025 if exact is not None:
1026 cities = [c for c in cities if c.name in exact]
1027 minpop = None
1028 else:
1029 cities = [c for c in cities if c.name not in exclude]
1030 minpop = 10**3
1031 for minpop_new in [1e3, 3e3, 1e4, 3e4, 1e5, 3e5, 1e6, 3e6, 1e7]:
1032 cities_new = [
1033 c for c in cities
1034 if c.population > minpop_new or c.name in include]
1036 if len(cities_new) == 0 or (
1037 len(cities_new) < 3 and len(cities) < nmax_soft*2):
1038 break
1040 cities = cities_new
1041 minpop = minpop_new
1042 if len(cities) <= nmax_soft:
1043 break
1045 if cities:
1046 lats = [c.lat for c in cities]
1047 lons = [c.lon for c in cities]
1049 self.gmt.psxy(
1050 in_columns=(lons, lats),
1051 *self.jxyr, **psxy_style)
1053 for c in cities:
1054 try:
1055 text = c.name.encode('iso-8859-1').decode('iso-8859-1')
1056 except UnicodeEncodeError:
1057 text = c.asciiname
1059 self.add_label(c.lat, c.lon, text)
1061 self._cities_minpop = minpop
1063 def add_stations(self, stations, psxy_style=dict()):
1065 default_psxy_style = {
1066 'S': 't8p',
1067 'G': 'black'
1068 }
1069 default_psxy_style.update(psxy_style)
1071 lats, lons = zip(*[s.effective_latlon for s in stations])
1073 self.gmt.psxy(
1074 in_columns=(lons, lats),
1075 *self.jxyr, **default_psxy_style)
1077 for station in stations:
1078 self.add_label(
1079 station.effective_lat,
1080 station.effective_lon,
1081 '.'.join(x for x in (station.network, station.station) if x))
1083 def add_kite_scene(self, scene):
1084 tile = FloatTile(
1085 scene.frame.llLon,
1086 scene.frame.llLat,
1087 scene.frame.dLon,
1088 scene.frame.dLat,
1089 scene.displacement)
1091 return tile
1093 def add_gnss_campaign(self, campaign, psxy_style=None, offset_scale=None,
1094 labels=True, vertical=False, fontsize=10):
1096 stations = campaign.stations
1098 if offset_scale is None:
1099 offset_scale = num.zeros(campaign.nstations)
1100 for ista, sta in enumerate(stations):
1101 for comp in sta.components.values():
1102 offset_scale[ista] += comp.shift
1103 offset_scale = num.sqrt(offset_scale**2).max()
1105 size = math.sqrt(self.height**2 + self.width**2)
1106 scale = (size/10.) / offset_scale
1107 logger.debug('GNSS: Using offset scale %f, map scale %f',
1108 offset_scale, scale)
1110 lats, lons = zip(*[s.effective_latlon for s in stations])
1112 if vertical:
1113 rows = [[lons[ista], lats[ista],
1114 0., -s.up.shift,
1115 (s.east.sigma + s.north.sigma) if s.east.sigma else 0.,
1116 s.up.sigma, 0.,
1117 s.code if labels else None]
1118 for ista, s in enumerate(stations)
1119 if s.up is not None]
1121 else:
1122 rows = [[lons[ista], lats[ista],
1123 -s.east.shift, -s.north.shift,
1124 s.east.sigma, s.north.sigma, s.correlation_ne,
1125 s.code if labels else None]
1126 for ista, s in enumerate(stations)
1127 if s.east is not None or s.north is not None]
1129 default_psxy_style = {
1130 'h': 0,
1131 'W': '2p,black',
1132 'A': '+p2p,black+b+a40',
1133 'G': 'black',
1134 'L': True,
1135 'S': 'e%dc/0.95/%d' % (scale, fontsize),
1136 }
1138 if not labels:
1139 for row in rows:
1140 row.pop(-1)
1142 if psxy_style is not None:
1143 default_psxy_style.update(psxy_style)
1145 self.gmt.psvelo(
1146 in_rows=rows,
1147 *self.jxyr,
1148 **default_psxy_style)
1150 def draw_plates(self):
1151 from pyrocko.dataset import tectonics
1153 neast = 20
1154 nnorth = max(1, int(round(num.round(self._hreg/self._wreg * neast))))
1155 norths = num.linspace(-self._hreg*0.5, self._hreg*0.5, nnorth)
1156 easts = num.linspace(-self._wreg*0.5, self._wreg*0.5, neast)
1157 norths2 = num.repeat(norths, neast)
1158 easts2 = num.tile(easts, nnorth)
1159 lats, lons = od.ne_to_latlon(
1160 self.lat, self.lon, norths2, easts2)
1162 bird = tectonics.PeterBird2003()
1163 plates = bird.get_plates()
1165 color_plates = gmtpy.color('aluminium5')
1166 color_velocities = gmtpy.color('skyblue1')
1167 color_velocities_lab = gmtpy.color(darken(gmtpy.color_tup('skyblue1')))
1169 points = num.vstack((lats, lons)).T
1170 used = []
1171 for plate in plates:
1172 mask = plate.contains_points(points)
1173 if num.any(mask):
1174 used.append((plate, mask))
1176 if len(used) > 1:
1178 candi_fixed = {}
1180 label_data = []
1181 for plate, mask in used:
1183 mean_north = num.mean(norths2[mask])
1184 mean_east = num.mean(easts2[mask])
1185 iorder = num.argsort(num.sqrt(
1186 (norths2[mask] - mean_north)**2 +
1187 (easts2[mask] - mean_east)**2))
1189 lat_candis = lats[mask][iorder]
1190 lon_candis = lons[mask][iorder]
1192 candi_fixed[plate.name] = lat_candis.size
1194 label_data.append((
1195 lat_candis, lon_candis, plate, color_plates))
1197 boundaries = bird.get_boundaries()
1199 size = 2
1201 psxy_kwargs = []
1203 for boundary in boundaries:
1204 if num.any(points_in_region(boundary.points, self._wesn)):
1205 for typ, part in boundary.split_types(
1206 [['SUB'],
1207 ['OSR', 'OTF', 'OCB', 'CTF', 'CCB', 'CRB']]):
1209 lats, lons = part.T
1211 kwargs = {}
1212 if typ[0] == 'SUB':
1213 if boundary.kind == '\\':
1214 kwargs['S'] = 'f%g/%gp+t+r' % (
1215 0.45*size, 3.*size)
1216 elif boundary.kind == '/':
1217 kwargs['S'] = 'f%g/%gp+t+l' % (
1218 0.45*size, 3.*size)
1220 kwargs['G'] = color_plates
1222 kwargs['in_columns'] = (lons, lats)
1223 kwargs['W'] = '%gp,%s' % (size, color_plates),
1225 psxy_kwargs.append(kwargs)
1227 if boundary.kind == '\\':
1228 if boundary.plate_name2 in candi_fixed:
1229 candi_fixed[boundary.plate_name2] += \
1230 neast*nnorth
1232 elif boundary.kind == '/':
1233 if boundary.plate_name1 in candi_fixed:
1234 candi_fixed[boundary.plate_name1] += \
1235 neast*nnorth
1237 candi_fixed = [name for name in sorted(
1238 list(candi_fixed.keys()), key=lambda name: -candi_fixed[name])]
1240 candi_fixed.append(None)
1242 gsrm = tectonics.GSRM1()
1244 for name in candi_fixed:
1245 if name not in gsrm.plate_names() \
1246 and name not in gsrm.plate_alt_names():
1248 continue
1250 lats, lons, vnorth, veast, vnorth_err, veast_err, corr = \
1251 gsrm.get_velocities(name, region=self._wesn)
1253 fixed_plate_name = name
1255 if self.show_plate_velocities:
1256 self.gmt.psvelo(
1257 in_columns=(
1258 lons, lats, veast, vnorth, veast_err, vnorth_err,
1259 corr),
1260 W='0.25p,%s' % color_velocities,
1261 A='9p+e+g%s' % color_velocities,
1262 S='e0.2p/0.95/10',
1263 *self.jxyr)
1265 for _ in range(len(lons) // 50 + 1):
1266 ii = random.randint(0, len(lons)-1)
1267 v = math.sqrt(vnorth[ii]**2 + veast[ii]**2)
1268 self.add_label(
1269 lats[ii], lons[ii], '%.0f' % v,
1270 font_size=0.7*self.gmt.label_font_size(),
1271 style=dict(
1272 G=color_velocities_lab))
1274 break
1276 if self.show_plate_names:
1277 for (lat_candis, lon_candis, plate, color) in label_data:
1278 full_name = bird.full_name(plate.name)
1279 if plate.name == fixed_plate_name:
1280 full_name = '@_' + full_name + '@_'
1282 self.add_area_label(
1283 lat_candis, lon_candis,
1284 full_name,
1285 color=color,
1286 font='3')
1288 for kwargs in psxy_kwargs:
1289 self.gmt.psxy(*self.jxyr, **kwargs)
1292def rand(mi, ma):
1293 mi = float(mi)
1294 ma = float(ma)
1295 return random.random() * (ma-mi) + mi
1298def split_region(region):
1299 west, east, south, north = topo.positive_region(region)
1300 if east > 180:
1301 return [(west, 180., south, north),
1302 (-180., east-360., south, north)]
1303 else:
1304 return [region]
1307class CPTLevel(Object):
1308 vmin = Float.T()
1309 vmax = Float.T()
1310 color_min = Tuple.T(3, Float.T())
1311 color_max = Tuple.T(3, Float.T())
1314class CPT(Object):
1315 color_below = Tuple.T(3, Float.T(), optional=True)
1316 color_above = Tuple.T(3, Float.T(), optional=True)
1317 color_nan = Tuple.T(3, Float.T(), optional=True)
1318 levels = List.T(CPTLevel.T())
1320 def scale(self, vmin, vmax):
1321 vmin_old, vmax_old = self.levels[0].vmin, self.levels[-1].vmax
1322 for level in self.levels:
1323 level.vmin = (level.vmin - vmin_old) / (vmax_old - vmin_old) * \
1324 (vmax - vmin) + vmin
1325 level.vmax = (level.vmax - vmin_old) / (vmax_old - vmin_old) * \
1326 (vmax - vmin) + vmin
1328 def discretize(self, nlevels):
1329 colors = []
1330 vals = []
1331 for level in self.levels:
1332 vals.append(level.vmin)
1333 vals.append(level.vmax)
1334 colors.append(level.color_min)
1335 colors.append(level.color_max)
1337 r, g, b = num.array(colors, dtype=float).T
1338 vals = num.array(vals, dtype=float)
1340 vmin, vmax = self.levels[0].vmin, self.levels[-1].vmax
1341 x = num.linspace(vmin, vmax, nlevels+1)
1342 rd = num.interp(x, vals, r)
1343 gd = num.interp(x, vals, g)
1344 bd = num.interp(x, vals, b)
1346 levels = []
1347 for ilevel in range(nlevels):
1348 color = (
1349 float(0.5*(rd[ilevel]+rd[ilevel+1])),
1350 float(0.5*(gd[ilevel]+gd[ilevel+1])),
1351 float(0.5*(bd[ilevel]+bd[ilevel+1])))
1353 levels.append(CPTLevel(
1354 vmin=x[ilevel],
1355 vmax=x[ilevel+1],
1356 color_min=color,
1357 color_max=color))
1359 cpt = CPT(
1360 color_below=self.color_below,
1361 color_above=self.color_above,
1362 color_nan=self.color_nan,
1363 levels=levels)
1365 return cpt
1368class CPTParseError(Exception):
1369 pass
1372def read_cpt(filename):
1373 with open(filename) as f:
1374 color_below = None
1375 color_above = None
1376 color_nan = None
1377 levels = []
1378 try:
1379 for line in f:
1380 line = line.strip()
1381 toks = line.split()
1383 if line.startswith('#'):
1384 continue
1386 elif line.startswith('B'):
1387 color_below = tuple(map(float, toks[1:4]))
1389 elif line.startswith('F'):
1390 color_above = tuple(map(float, toks[1:4]))
1392 elif line.startswith('N'):
1393 color_nan = tuple(map(float, toks[1:4]))
1395 else:
1396 values = list(map(float, line.split()))
1397 vmin = values[0]
1398 color_min = tuple(values[1:4])
1399 vmax = values[4]
1400 color_max = tuple(values[5:8])
1401 levels.append(CPTLevel(
1402 vmin=vmin,
1403 vmax=vmax,
1404 color_min=color_min,
1405 color_max=color_max))
1407 except Exception:
1408 raise CPTParseError()
1410 return CPT(
1411 color_below=color_below,
1412 color_above=color_above,
1413 color_nan=color_nan,
1414 levels=levels)
1417def color_to_int(color):
1418 return tuple(max(0, min(255, int(round(x)))) for x in color)
1421def write_cpt(cpt, filename):
1422 with open(filename, 'w') as f:
1423 for level in cpt.levels:
1424 f.write(
1425 '%e %i %i %i %e %i %i %i\n' %
1426 ((level.vmin, ) + color_to_int(level.color_min) +
1427 (level.vmax, ) + color_to_int(level.color_max)))
1429 if cpt.color_below:
1430 f.write('B %i %i %i\n' % color_to_int(cpt.color_below))
1432 if cpt.color_above:
1433 f.write('F %i %i %i\n' % color_to_int(cpt.color_above))
1435 if cpt.color_nan:
1436 f.write('N %i %i %i\n' % color_to_int(cpt.color_nan))
1439def cpt_merge_wet_dry(wet, dry):
1440 levels = []
1441 for level in wet.levels:
1442 if level.vmin < 0.:
1443 if level.vmax > 0.:
1444 level.vmax = 0.
1446 levels.append(level)
1448 for level in dry.levels:
1449 if level.vmax > 0.:
1450 if level.vmin < 0.:
1451 level.vmin = 0.
1453 levels.append(level)
1455 combi = CPT(
1456 color_below=wet.color_below,
1457 color_above=dry.color_above,
1458 color_nan=dry.color_nan,
1459 levels=levels)
1461 return combi
1464if __name__ == '__main__':
1465 from pyrocko import util
1466 util.setup_logging('pyrocko.automap', 'info')
1468 import sys
1469 if len(sys.argv) == 2:
1471 n = int(sys.argv[1])
1473 for i in range(n):
1474 m = Map(
1475 lat=rand(-60., 60.),
1476 lon=rand(-180., 180.),
1477 radius=math.exp(rand(math.log(500*km), math.log(3000*km))),
1478 width=30., height=30.,
1479 show_grid=True,
1480 show_topo=True,
1481 color_dry=(238, 236, 230),
1482 topo_cpt_wet='light_sea_uniform',
1483 topo_cpt_dry='light_land_uniform',
1484 illuminate=True,
1485 illuminate_factor_ocean=0.15,
1486 show_rivers=False,
1487 show_plates=True)
1489 m.draw_cities()
1490 print(m)
1491 m.save('map_%02i.pdf' % i)