-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmapping_tools.py
1529 lines (1226 loc) · 47 KB
/
mapping_tools.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 04 14:55:21 2013
@author: tallen
"""
def print_functions():
txt = open('U:/Code/pycode/mapping_tools.py').readlines()
for line in txt:
if line.find('def') >= 0:
print(line.strip('def ').strip('\n'))
def load_shape(shpfile):
import shapefile
return shapefile.Reader(shpfile)
def get_shp_polygons(shpfile):
import shapefile
from shapely.geometry import Polygon
sf = shapefile.Reader(shpfile)
shapes = sf.shapes()
polygons = []
for poly in shapes:
polygons.append(Polygon(poly.points))
return sf, polygons
def get_field_index(sf, field):
fields = sf.fields[1:]
findex = -1
for i, f in enumerate(fields):
if f[0] == field:
findex = i
return findex
def get_field_data(sf, field, datatype):
'''
datatype = float, str
'''
from misc_tools import checkfloat, checkint
from numpy import array
# get index
index = get_field_index(sf, field)
# get records
recs = sf.records()
# now loop thru recs and get data
data = []
for rec in recs:
if datatype == 'str':
data.append(rec[index])
elif datatype == 'float':
data.append(checkfloat(rec[index]))
elif datatype == 'int':
data.append(checkint(rec[index]))
return array(data)
def shapepoly2shapley(shpfile):
import shapefile
from shapely.geometry import Polygon
sf = shapefile.Reader(shpfile)
shapes = sf.shapes()
polygons = []
for poly in shapes:
polygons.append(Polygon(poly.points))
return polygons
# returns list of shapely polygons of different shape parts
def split_shape_parts(sf):
from shapely.geometry import Polygon
from numpy import array
shapes = sf.shapes()
polygons = []
for i, shape in enumerate(shapes):
parts = shape.parts
print(parts)
parts.append(len(shape.points)-1) # adding last point
for i in range (0, len(parts)-1):
polygons.append(Polygon(shape.points[parts[i]:parts[i+1]]))
print(array(polygons[-1].bounds))
return polygons
'''
# get colour map and vector of colour indexes
sf = shapefile object
field = relevant field in shapefile
colmap = colourmap to be used
ncolours = number of colour ranges
kwargs:
zmin
zmax
'''
def getshapecolour(sf, field, colmap, ncolours, **kwargs):
import matplotlib.cm as cm
from numpy import arange, isnan, nan
# if assigned, set kwargs
zmin = nan
zmax = nan
for key in ('zmin', 'zmax'):
if key in kwargs:
# min value
if key == 'zmin':
zmin = kwargs[key]
# set scaling relation
if key == 'zmax':
zmax = kwargs[key]
# get field index
findex = get_field_index(sf, field)
# get max/min value in field
fvect = []
recs = sf.records()
for rec in recs:
fvect.append(float(rec[findex]))
if isnan(zmin):
zmin = min(fvect)
if isnan(zmax):
zmax = max(fvect)
zrng = zmax - zmin
# make colourmap
cmap = cm.get_cmap(colmap, ncolours)
cs = (cmap(arange(ncolours)))
# get colour index
ci = []
for f in fvect:
print(f)
ci.append(round((ncolours-1.) / zrng * (f-zmin)))
return cs, ci, cmap, zmin, zmax
def drawshapepoly(m, plt, sf, label='null', fillcolor='none', edgecolor='k', alpha=1, cmap=-99, zorder=5000, **kwargs):
from numpy import arange, isnan, nan
# get kwargs
ncolours = 256
lw = 0.5
ls = '-'
fillshape = False
polyline = False # do not close polygon
for key in ('col', 'cindex', 'cmap', 'ncolours', 'lw', 'ls', 'fillshape', 'polyline'):
if key in kwargs:
if key == 'col':
col = kwargs[key]
if key == 'cindex':
cindex = kwargs[key]
if key == 'cmap':
cmap = kwargs[key]
if key == 'ncolours':
ncolours = kwargs[key]
if key == 'ls':
ls = kwargs[key]
if key == 'lw':
lw = kwargs[key]
if key == 'fillshape':
fillshape = kwargs[key]
if key == 'polyline':
polyline = kwargs[key]
shapes = sf.shapes()
return_polys = []
for i, shape in enumerate(shapes):
newfill = True
# get colour
try:
cs = (cmap(arange(ncolours)))
if isnan(cindex[i]) == False and cindex[i] != -1:
col = [cs[int(cindex[i])][0],cs[int(cindex[i])][1],cs[int(cindex[i])][2]]
else:
newfill = False
col = '0.9'
#col = 'none'
except:
try:
col = col
except:
col = 'w'
'''
if fillshape == True:
fillcol = col
linecol = 'k'
else:
linecol = col
'''
# get xy coords
x = []
y = []
p = 0
parts = shape.parts
parts.append(len(shape.points))
for prt in parts[1:]:
#print('part',prt
while p < prt:
x.append(shape.points[p][0])
y.append(shape.points[p][1])
p += 1
# close polygon if not polyline
if polyline == False:
if x[0] != x[-1] or y[0] != y[-1]:
x.append(x[0])
y.append(y[0])
try:
# plot each polygon
xx, yy = m(x,y)
#print(edgecolor)
if fillshape == True and cmap != -99:
plt.fill(xx,yy, facecolor=col, edgecolor=edgecolor, linewidth=lw, label=label, alpha=alpha)
#m.plot(xx, yy, linewidth=lw, color=edgecolor, ls=ls, zorder=1)
elif fillshape == True and newfill == True:
#print(fillcolor)
if label == 'null':
plt.fill(xx,yy, facecolor=fillcolor, edgecolor=edgecolor, linewidth=lw, alpha=alpha)
m.plot(xx, yy, linewidth=lw, color=edgecolor, ls=ls, zorder=1)
else:
plt.fill(xx,yy, facecolor=fillcolor, edgecolor=edgecolor, linewidth=lw, label=label, alpha=alpha)
m.plot(xx, yy, linewidth=lw, color=edgecolor, ls=ls, zorder=1)
label = 'null' # set to null after first plot
elif label == 'null':
m.plot(xx, yy, linewidth=lw, color=edgecolor, linestyle=ls, zorder=zorder)
else:
m.plot(xx, yy, linewidth=lw, color=edgecolor, linestyle=ls, label=label, zorder=zorder)
label = 'null' # set to null after first plot
except:
print('Skipping polygon...')
return_polys.append([x,y])
x = []
y = []
return return_polys
'''
end of drawshapepoly
'''
def drawoneshapepoly(m, plt, sf, field, value, **kwargs):
from numpy import arange
# get kwargs
ncolours = 256
col = 'k'
lw = 1.0
ls = '-'
fillshape = False
polyline = False # do not close polygon
for key in ('col', 'cindex', 'cmap', 'ncolours', 'lw', 'ls', 'fillshape', 'polyline'):
if key in kwargs:
if key == 'col':
col = kwargs[key]
if key == 'cindex':
cindex = kwargs[key]
if key == 'cmap':
cmap = kwargs[key]
if key == 'ncolours':
ncolours = kwargs[key]
if key == 'ls':
ls = kwargs[key]
if key == 'lw':
lw = kwargs[key]
if key == 'fillshape':
fillshape = kwargs[key]
if key == 'polyline':
polyline = kwargs[key]
shapes = sf.shapes()
recs = sf.records()
# get field index
findex = get_field_index(sf, field)
#print('findex', findex)
return_polys = []
for i, shape in enumerate(shapes):
#print('i', i)
if recs[i][findex] == value:
# get colour
try:
cs = (cmap(arange(ncolours)))
col = [cs[int(cindex[i])][0],cs[int(cindex[i])][1],cs[int(cindex[i])][2]]
except:
try:
col = col
except:
col = 'k'
if fillshape == True:
fillcol = col
linecol = 'k'
else:
linecol = col
# get xy coords
x = []
y = []
p = 0
parts = shape.parts
parts.append(len(shape.points)-1)
for prt in range(0,len(parts)-1):
while p <= parts[prt+1]:
x.append(shape.points[p][0])
y.append(shape.points[p][1])
p += 1
# close polygon if not polyline
if polyline == False:
if x[0] != x[-1] or y[0] != y[-1]:
x.append(x[0])
y.append(y[0])
# plot each polygon
xx, yy = m(x,y)
if fillshape == True:
plt.fill(xx,yy,color=fillcol)
m.plot(xx, yy, linewidth=lw, color=linecol, linestyle=ls, zorder=1)
return_polys.append([x,y])
x = []
y = []
return return_polys
'''
end of drawshapepoly
'''
def drawmanualshapepoly(m, plt, sf, label='null', fillcolor='none', edgecolor='k', alpha=1, cmap=-99, zorder=20000, **kwargs):
from numpy import arange, isnan, nan
# get kwargs
ncolours = 256
lw = 0.5
ls = '-'
fillshape = False
polyline = False # do not close polygon
for key in ('col', 'cindex', 'cmap', 'ncolours', 'lw', 'ls', 'fillshape', 'polyline'):
if key in kwargs:
if key == 'col':
col = kwargs[key]
if key == 'cindex':
cindex = kwargs[key]
if key == 'cmap':
cmap = kwargs[key]
if key == 'ncolours':
ncolours = kwargs[key]
if key == 'ls':
ls = kwargs[key]
if key == 'lw':
lw = kwargs[key]
if key == 'fillshape':
fillshape = kwargs[key]
if key == 'polyline':
polyline = kwargs[key]
shapes = sf.shapes()
for i, shape in enumerate(shapes):
newfill = True
# get colour
try:
cs = (cmap(arange(ncolours)))
if isnan(cindex[i]) == False and cindex[i] != -1:
col = [cs[int(cindex[i])][0],cs[int(cindex[i])][1],cs[int(cindex[i])][2]]
else:
newfill = False
col = '0.9'
#col = 'none'
except:
try:
col = col
except:
col = 'w'
'''
if fillshape == True:
fillcol = col
linecol = 'k'
else:
linecol = col
'''
# get xy coords
x = []
y = []
p = 0
parts = shape.parts
parts.append(len(shape.points))
for prt in parts[1:]:
#print('part',prt
while p < prt:
x.append(shape.points[p][0])
y.append(shape.points[p][1])
p += 1
# close polygon if not polyline
if polyline == False:
if x[0] != x[-1] or y[0] != y[-1]:
x.append(x[0])
y.append(y[0])
try:
# plot each polygon
xx, yy = m(x,y)
#print(edgecolor)
if fillshape == True :
plt.fill(xx,yy, facecolor=col, edgecolor=edgecolor, linewidth=lw, label=label, alpha=alpha)
#m.plot(xx, yy, linewidth=lw, color=edgecolor, ls=ls, zorder=1)
elif fillshape == True and newfill == True:
#print(fillcolor)
if label == 'null':
plt.fill(xx,yy, facecolor=fillcolor, edgecolor=edgecolor, linewidth=lw, alpha=alpha)
m.plot(xx, yy, linewidth=lw, color=edgecolor, ls=ls, zorder=1)
else:
plt.fill(xx,yy, facecolor=fillcolor, edgecolor=edgecolor, linewidth=lw, label=label, alpha=alpha)
m.plot(xx, yy, linewidth=lw, color=edgecolor, ls=ls, zorder=1)
label = 'null' # set to null after first plot
except:
print('Skipping polygon...')
x = []
y = []
'''
end of drawshapepoly
'''
# label polygon with a field in shapefile
def labelpolygon(m, plt, sf, field, addOutline=False, **kwargs):
'''
fstyle = ['normal', 'italic', 'oblique']
fweight = ['light', 'normal', 'medium', 'semibold', 'bold', 'heavy', 'black']
'''
from shapely.geometry import Polygon
from mapping_tools import get_field_index
import matplotlib as mpl
import matplotlib.patheffects as path_effects
from numpy import array
mpl.rcParams['pdf.fonttype'] = 42
xoff = 0.
yoff = 0.
fsize = 10
col = 'k'
fstyle = 'normal'
fweight = 'normal'
value = None
for key in ('xoff', 'yoff', 'fsize', 'fweight', 'col', 'fstyle', 'value'):
if key in kwargs:
if key == 'xoff':
xoff = kwargs[key]
if key == 'yoff':
yoff = kwargs[key]
if key == 'fsize':
fsize = kwargs[key]
if key == 'fweight':
fweight = kwargs[key]
if key == 'fstyle':
fstyle = kwargs[key]
if key == 'col':
col = kwargs[key]
if key == 'value':
value = kwargs[key]
shapes = sf.shapes()
recs = sf.records()
# get field index
findex = get_field_index(sf, field)
xcentroids = []
ycentroids = []
for i, shape in enumerate(shapes):
centroid = Polygon(shape.points).centroid.wkt
centroid = centroid.strip('PIONT').replace('(',' ').replace(')',' ').split()
tx, ty = m(float(centroid[0]),float(centroid[1]))
if tx > m.xmin and tx < m.xmax and ty > m.ymin and ty < m.ymax:
if value == None or value == recs[i][findex]:
if addOutline == False:
#path_effect=[path_effects.Normal()]
path_effect=[]
else:
lineWidth= 3.
backColour = 'w'
path_effect=[path_effects.withStroke(linewidth=lineWidth, foreground=backColour)]
plt.text(tx + xoff, ty + yoff, recs[i][findex], size=fsize, \
weight=fweight, color=col, style=fstyle, va='center', \
ha='center', path_effects=path_effect)
'''
centroidx = []
centroidy = []
for j in range(0,len(shape.points)):
centroidx.append(shape.points[j][0])
centroidy.append(shape.points[j][1])
tx, ty = m(mean(centroidx),mean(centroidy))
'''
xcentroids.append(float(centroid[0]))
ycentroids.append(float(centroid[1]))
return array(xcentroids), array(ycentroids)
def return_map_shape_points(m, shpfile):
import shapefile
sf = shapefile.Reader(shpfile)
shapes = sf.shapes()
shplon = []
shplat = []
for shape in shapes:
shplon.append(shape.points[0][0])
shplat.append(shape.points[0][1])
x, y = m(shplon, shplat)
return x, y
def xy2shp(xycsv, headerlines=1, lola=True):
'''
lola = order of coords - True if lon/lat
'''
import shapefile
from numpy import array, hstack
lines = open(xycsv).readlines()
# get WA polygons
lons = []
lats = []
for line in lines[headerlines:]:
if lola==True:
lons.append(float(line.split(',')[0]))
lats.append(float(line.split(',')[1]))
else:
lons.append(float(line.split(',')[1]))
lats.append(float(line.split(',')[0]))
lats = array(lats).reshape(len(lons),1)
lons = array(lons).reshape(len(lons),1)
# write shapefile
w = shapefile.Writer(xycsv.split('.')[0]+'.shp', shapeType=5)
#w.field(xycsv.split('.')[0],'C','5')
xy = [hstack((lons, lats)).tolist()]
w.poly(xy)
#w.record('1')
w.close()
# Add background to text to highlight
def addTextOutline(textHandle, lineWidth, backColour):
'''
e.g.:
textHandle = plt.text(2,2,'This is a test', size=11, color='black')
'''
import matplotlib.patheffects as PathEffects
textHandle.set_path_effects([PathEffects.withStroke(linewidth=lineWidth, foreground=backColour)])
def labelCentroid(plt, m, txt, xarray, yarray, xoff=0, fsize=8):
from shapely.geometry import Polygon
col = 'k'
# make pts array
pts = []
for x, y in zip(xarray, yarray):
pts.append([x+xoff, y])
centroid = Polygon(pts).centroid.wkt
centroid = centroid.strip('PIONT').replace('(',' ').replace(')',' ').split()
tx, ty = m(float(centroid[0]),float(centroid[1]))
plt.text(tx, ty, txt, size=fsize, color=col, va='center', ha='center')
# join two epicentres with a line
def joinpoints(m,plt,joinfile):
data = open(joinfile).readlines()
for line in data:
pts = map(float, line.split(','))
# draw connecting line
xx, yy = m([pts[0],pts[2]],[pts[1],pts[3]])
m.plot(xx,yy,'k-',linewidth=0.5)
# plot points
x1, y1 = m(pts[0],pts[1])
x2, y2 = m(pts[2],pts[3])
p1 = m.plot(x1,y1,'o',color='g',markersize=5) # SHEEF
p2 = m.plot(x2,y2,'o',color='orange',ms=5) # WHITE
return p1, p2
# map single points
def mappoints(m,plt,ptfile):
data = open(ptfile).readlines()
for line in data:
pts = map(float, line.split(','))
# plot points
x, y = m(pts[0],pts[1])
p = m.plot(x,y,'o',color='purple',markersize=5)
return p
# calculate lat lon from range (km) and bearing (degrees)
# code adapted from: http://stackoverflow.com/questions/7222382/get-lat-long-given-current-point-distance-and-bearing
def reckon(lat1d, lon1d, rngkm, brngd):
from math import radians, asin, sin, cos, atan2, degrees
R = 6378.1 #Radius of the Earth
brng = radians(brngd)
lat1r = radians(lat1d) #Current lat point converted to radians
lon1r = radians(lon1d) #Current long point converted to radians
lat2r = asin(sin(lat1r)*cos(rngkm/R) + cos(lat1r)*sin(rngkm/R)*cos(brng))
lon2r = lon1r + atan2(sin(brng)*sin(rngkm/R)*cos(lat1r), \
cos(rngkm/R)-sin(lat1r)*sin(lat2r))
lat2d = degrees(lat2r)
lon2d = degrees(lon2r)
return [lon2d, lat2d]
# check to see if a point is inside a polygon
def checkPointInPoly(shpfile, lon, lat):
import shapefile
from shapely.geometry import Point, Polygon
#parese shapefile
sf = shapefile.Reader(shpfile)
shapes = sf.shapes()
poly = Polygon(shapes[0].points)
pt = Point(lon, lat)
if pt.within(poly):
value = True
else:
value = False
return value
def get_line_parallels(pts, rngkm):
from obspy.geodetics.base import gps2dist_azimuth
from mapping_tools import reckon
'''
pts are an N x [lon, lat] matrix, i.e.:
[[lon1, lat1],
[lon2, lat2]]
'''
# set outputs
posazpts = []
negazpts = []
for j, pt in enumerate(pts):
# if 1st point
if j == 0:
rngm, az, baz = gps2dist_azimuth(pts[j][1], pts[j][0], \
pts[j+1][1], pts[j+1][0])
# if last point
elif j == len(pts)-1:
rngm, az, baz = gps2dist_azimuth(pts[j-1][1], pts[j-1][0], \
pts[j][1], pts[j][0])
# use points either side (assumes evenly spaced)
else:
rngm, az, baz = gps2dist_azimuth(pts[j-1][1], pts[j-1][0], \
pts[j+1][1], pts[j+1][0])
# get azimuth for new points
azpos = az + 90.
azneg = az - 90.
# get points
posazpts.append(reckon(pts[j][1], pts[j][0], rngkm, azpos))
negazpts.append(reckon(pts[j][1], pts[j][0], rngkm, azneg))
'''
# for testing only
x=[]
y=[]
xx=[]
yy=[]
xxx=[]
yyy=[]
for j, pt in enumerate(pts):
x.append(pt[0])
y.append(pt[1])
xx.append(posazpts[j][0])
yy.append(posazpts[j][1])
xxx.append(negazpts[j][0])
yyy.append(negazpts[j][1])
plt.plot(x,y,'b-')
plt.plot(xx,yy,'r-')
plt.plot(xxx,yyy,'g-')
plt.show()
'''
return posazpts, negazpts
# renames obspy tool to something I remember
# returns rngkm (km), az, baz (degrees)
def distance(lat1, lon1, lat2, lon2):
#from obspy.core.util.geodetics import gps2DistAzimuth
from obspy.geodetics.base import gps2dist_azimuth
#print(lat1, lon1, lat2, lon2)
#rngm, az, baz = gps2DistAzimuth(lat1, lon1, lat2, lon2)
rngm, az, baz = gps2dist_azimuth(lat1, lon1, lat2, lon2)
rngkm = rngm / 1000.
return rngkm, az, baz
def km2deg(rngkm):
from obspy.geodetics.base import kilometer2degrees
return kilometer2degrees(rngkm, radius=6371.)
# function to get linear profile of lat/lons
def get_profile_locs(lat1, lon1, lat2, lon2, npts):
from mapping_tools import reckon, distance
from numpy import array
'''
npts = 1 more than number of steps
'''
'''
lon1 = 131.0
lat1 = -11.5
lon2 = 134.5
lat2 = -17.0
'''
rngkm, az, baz = distance(lat1, lon1, lat2, lon2)
# get inc distance
inckm = rngkm / (npts-1)
plats = []
plons = []
csvtxt = ''
for i in range(0, npts):
lon2d, lat2d = reckon(lat1, lon1, i*inckm, az)
plats.append(lat2d)
plons.append(lon2d)
csvtxt += ','.join((str('%0.4f' % lon2d), str('%0.4f' % lat2d))) + '\n'
f = open('profile.csv', 'wb')
f.write(csvtxt)
f.close()
return array(plons), array(plats)
# function to evenly discretise random xy points
def discretize_xy_profile(lons, lats, disckm, remainder=0.0):
'''
remainder is offset in km if first point is not equal to input points
'''
from numpy import arange
# set remainder to disckm
if remainder == 0.0:
remainder = disckm
discLon = []
discLat = []
discAzm = []
#remainder = discLen
for i in range(1, len(lons)):
# get dist from point 1 to point 2
rng, az, baz = distance(lats[i-1], lons[i-1], lats[i], lons[i])
lens = arange(disckm-remainder, rng, disckm)
# get xy locs for lens
if len(lens) > 0:
for l in lens:
discPos = reckon(lats[i-1], lons[i-1], l, az)
discLon.append(discPos[0])
discLat.append(discPos[1])
discAzm.append(az)
remainder = rng - lens[-1]
else:
remainder += rng
return discLon, discLat, discAzm
# add dip direction along faults with non-uniform xy coords
def map_fault_dip_dirn(m, plt, lons, lats, disckm, trikm, triScale=1.0, remainder=0.0, \
fc='k', ec='none', lw=0.5, invArrow=False, zorder=10000):
'''
trikm = length of equilateral triangle
triScale = vertical scaling for triangle
disckm = separation of points along line
remainder = offset in km if first point is not equal to first input points
'''
from mapping_tools import distance, reckon, discretize_xy_profile
from numpy import sqrt
halfTrikm = trikm / 2.
# set orientation
print('invArrow', invArrow)
if invArrow == False:
arrowDirn = 90.
else:
arrowDirn = -90.
discLon, discLat, discAzm = discretize_xy_profile(lons, lats, disckm, remainder=remainder)
# now, at each point, make dip triangle
for dlo, dla, daz in zip(discLon, discLat, discAzm):
# pt1
triLons = [reckon(dla, dlo, halfTrikm, daz)[0]]
triLats = [reckon(dla, dlo, halfTrikm, daz)[1]]
# pt2
triLons.append(reckon(dla, dlo, halfTrikm, daz+180)[0])
triLats.append(reckon(dla, dlo, halfTrikm, daz+180)[1])
# pt3 - assum equilateral triange
triHeight = triScale * sqrt(trikm**2 - halfTrikm**2)
triLons.append(reckon(dla, dlo, triHeight, daz-arrowDirn)[0])
triLats.append(reckon(dla, dlo, triHeight, daz-arrowDirn)[1])
xx, yy = m(triLons, triLats)
plt.fill(xx,yy, facecolor=fc, edgecolor=ec, linewidth=lw, alpha=1, zorder=zorder)
# generates a vector of distance, azimuth & back azimuth using "distance"
# returns rngkm (km), az, baz (degrees)
def dist_vect(lastlat, lastlon, latvect, lonvect):
from numpy import array
from mapping_tools import distance
rng = []
az = []
baz = []
for l in range(0,len(latvect)):
rngtmp, aztmp, baztmp = distance(lastlat, lastlon, latvect[l], lonvect[l])
rng.append(rngtmp)
az.append(aztmp)
baz.append(baztmp)
return array(rng), array(az), array(baz)
# read shapfile and get plotting coords in metres
def get_mapping_extent_from_shp(shpfile, lonoff):
import shapefile
from numpy import mean, ceil, floor
sf = shapefile.Reader(shpfile)
shapes = sf.shapes()
bbox = [180, 90, -180, -90]
padboxlat = 1
padboxlon = 1
for shape in shapes:
sbbox = shape.bbox
if sbbox[0] < bbox[0]:
bbox[0] = sbbox[0]
if sbbox[1] < bbox[1]:
bbox[1] = sbbox[1]
if sbbox[2] > bbox[2]:
bbox[2] = sbbox[2]
if sbbox[3] > bbox[3]:
bbox[3] = sbbox[3]
# pad bounding box and round to nearest degree
bbox[0] = floor(bbox[0] - padboxlon)
bbox[1] = floor(bbox[1] - padboxlat)
bbox[2] = ceil(bbox[2] + padboxlon)
bbox[3] = ceil(bbox[3] + padboxlat)
# get central lon/lat
lon_0 = mean([bbox[0], bbox[2]]) + float(lonoff)
lat_0 = mean([bbox[1], bbox[3]])
# get xy extents
xkm, az, baz = distance(lat_0, bbox[0], lat_0, bbox[2])
ykm, az, baz = distance(bbox[1], lon_0, bbox[3], lon_0)
xm = 1000 * xkm
ym = 1000 * ykm
return lon_0, lat_0, xm, ym
# read shapfile and get plotting coords
def get_mapping_extent_in_metres(bbox, lonoff):
'''
bbox is an array of [lonmin, lonmax, latmin, latmax]
'''
from numpy import mean, ceil
# get central lon/lat
lon_0 = mean([bbox[0], bbox[1]]) + float(lonoff)
lat_0 = mean([bbox[2], bbox[3]])
# get xy extents
xkm, az, baz = distance(lat_0, bbox[0], lat_0, bbox[1])
ykm, az, baz = distance(bbox[2], lon_0, bbox[3], lon_0)
xm = 1000 * xkm
ym = 1000 * ykm
return lon_0, lat_0, xm, ym
# get
def get_map_extent(gmtbounds):
'''
assumes GMT format lon/lat params
e.g. gmtbounds = [llcrnrlon, urcrnrlon, llcrnrlat, urcrnrlat]
'''
from numpy import mean
llcrnrlon = gmtbounds[0]
urcrnrlon = gmtbounds[1]
llcrnrlat = gmtbounds[2]
urcrnrlat = gmtbounds[3]
lon_0 = mean([gmtbounds[0], gmtbounds[1]])
lat_0 = mean([gmtbounds[2], gmtbounds[3]])
return llcrnrlon, llcrnrlat, urcrnrlon, urcrnrlat, lat_0, lon_0
# sets map extent for Lambert Conic Conformal projection
def set_lcc_basemap(llcrnrlon, llcrnrlat, urcrnrlon, urcrnrlat, resolution):