-
Notifications
You must be signed in to change notification settings - Fork 15
/
arcapi.py
2813 lines (2348 loc) · 99.7 KB
/
arcapi.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
"""
#-------------------------------------------------------------------------------
# Name: arcapi.arcapi
# Purpose: Core module for convenient API for arcpy
#
# Authors: Filip Kral, Caleb Mackey
#
# Created: 01/02/2014
# Licence: LGPL v3
#-------------------------------------------------------------------------------
# The core module of the arcapi package.
#
# All this content gets imported when you import the arcapi package.
# See arcapi __init__.py for more notes.
#
#-------------------------------------------------------------------------------
"""
import os
import sys
import time
import httplib
import urllib
import urllib2
import json
import urlparse
from contextlib import closing
import datetime
try:
import arcpy
except ImportError:
from ArcpyMockup import ArcpyMockup
arcpy = ArcpyMockup()
__version__ = '0.3.0'
"""Version number of arcapi"""
def names(x, filterer = None):
"""Return list of column names of a table.
Required:
x -- input table or table view
Optional:
filterer -- function, only fields where filterer returns True are listed
Example:
>>> names('c:\\foo\\bar.shp', lambda f: f.name.startswith('eggs'))
"""
flds = arcpy.ListFields(x)
if filterer is None: filterer = lambda a: True
return [f.name for f in flds if filterer(f)]
def types(x, filterer = None):
"""Return list of column types of a table.
Required:
x -- input table or table view
Optional:
filterer -- function, only fields where filterer returns True are listed
Example:
>>> types('c:\\foo\\bar.shp', lambda f: f.name.startswith('eggs'))
"""
flds = arcpy.ListFields(x)
if filterer is None: filterer = lambda a: True
return [f.type for f in flds if filterer(f)]
def nrow(x):
"""Return number of rows in a table as integer.
Required:
x -- input table or table view
Example:
>>> nrow('c:\\foo\\bar.shp')
"""
return int(arcpy.GetCount_management(x).getOutput(0))
def values(tbl, col, w='', o=None):
"""Return a list of all values in column col in table tbl.
If col is a single column, returns a list of values, otherwise returns
a list of tuples of values where each tuple is one row.
Columns included in the o parameter must be included in the col parameter!
Required:
tbl -- input table or table view
col -- input column name(s) as string or a list; valid options are:
col='colA'
col=['colA']
col=['colA', 'colB', 'colC']
col='colA,colB,colC'
col='colA;colB;colC'
Optional:
w -- where clause
o -- order by clause like '"OBJECTID" ASC, "Shape_Area" DESC',
default is None, which means order by object id if exists
Example:
>>> values('c:\\foo\\bar.shp', 'Shape_Length')
>>> values('c:\\foo\\bar.shp', 'SHAPE@XY')
>>> values('c:\\foo\\bar.shp', 'SHAPE@XY;Shape_Length', 'Shape_Length ASC')
>>> # columns in 'o' must be in 'col', otherwise RuntimeError is raised:
>>> values('c:\\foo\\bar.shp', 'SHAPE@XY', 'Shape_Length DESC') # Error!
"""
# unpack column names
if isinstance(col, (list, tuple)):
cols = col
else:
col = str(col)
separ = ';' if ';' in col else ','
cols = [c.strip() for c in col.split(separ)]
# indicate whether one or more than one columns were specified
multicols = False
if len(cols) > 1:
multicols = True
# construct order by clause
if o is not None:
o = 'ORDER BY ' + str(o)
else:
pass
# retrieve values with search cursor
ret = []
with arcpy.da.SearchCursor(tbl, cols, where_clause = w, sql_clause=(None, o)) as sc:
for row in sc:
if multicols:
ret.append(row)
else:
ret.append(row[0])
return ret
def frequency(x):
"""Return a dict of counts of each value in iterable x.
Values in x must be hashable in order to work as dictionary keys.
Required:
x -- input iterable object like list or tuple
Example:
>>> frequency([1,1,2,3,4,4,4]) # {1: 2, 2: 1, 3: 1, 4: 3}
>>> frequency(values('c:\\foo\\bar.shp', 'STATE'))
"""
x.sort()
fq = {}
for i in x:
if i in fq: #has_key deprecated in 3.x
fq[i] += 1
else:
fq[i] = 1
return fq
def distinct(tbl, col, w=''):
"""Return a list of distinct values in column col in table tbl.
Required:
tbl -- input table or table view
col -- input column name as string
Optional:
w -- where clause
Example:
>>> distinct('c:\\foo\\bar.shp', "CATEGORY")
>>> distinct('c:\\foo\\bar.shp', "SHAPE@XY")
"""
return list(set(values(tbl, col, w)))
def print_tuples(x, delim=" ", tbl=None, geoms=None, fillchar=" ", padding=1, verbose=True, returnit = False):
"""Print and/or return list of tuples formatted as a table.
Intended for quick printing of lists of tuples in the terminal.
Returns None or the formatted table depending on value of returnit.
Required:
x -- input list of tuples to print (can be tuple of tuples, list of lists).
Optional:
delim -- delimiter to use between columns
tbl -- table or list of arcpy.Field objects to take column headings from (default is None)
geoms -- if None (default), print geometries 'as is', else as str(geom).
Works only is valid tbl is specified.
filchar -- string to be used to pad values
padding -- how many extra fillchars to use in cells
verbose -- suppress printing when False, default is True
returnit -- if True, return the formatted table, else return None (default)
"""
lpadding, rpadding = padding, padding
fch = fillchar
# find column widths
gi = None
if tbl is None:
nms = ["V" + str(a) for a in range(len(x[0]))]
tps = ["LONG" if str(ti).isdigit() else "TEXT" for ti in x[0]]
geoms = None
else:
nms,tps = [],[]
i = 0
if isinstance(tbl, list) or isinstance(tbl, tuple):
fields = tbl
else:
fields = arcpy.ListFields(tbl)
for f in fields:
nms.append(f.name)
tps.append(f.type)
if f.type.lower() == "geometry" and geoms is not None:
gi = i # index of geometry column
i += 1
nmirange = range(len(nms))
toLeft = []
leftTypes = ("STRING", "TEXT") # field types to be left justified
for nmi in range(len(nms)):
if tps[nmi].upper() in leftTypes:
toLeft.append(nmi)
widths = []
for nmi in range(len(nms)):
widths.append(len(str(nms[nmi])))
for tpl in x:
for nmi in range(len(nms)):
if geoms is not None and nmi == gi:
clen = len(str(geoms))
else:
clen = len(str(tpl[nmi]))
if clen > widths[nmi]:
widths[nmi] = clen
sbuilder = []
frmtd = []
for nmi in range(len(nms)):
pad = widths[nmi] + lpadding + rpadding
frmtd.append(str(nms[nmi]).center(pad, fch))
hdr = delim.join(frmtd)
if verbose: print hdr # print header
sbuilder.append(hdr)
for r in x:
frmtd = []
for nmi in range(len(nms)):
if nmi in toLeft:
if geoms is not None and nmi == gi:
pad = widths[nmi] + rpadding
padfull = pad + lpadding
valf = str(geoms).ljust(pad, fch).rjust(padfull, fch)
else:
pad = widths[nmi] + rpadding
padfull = pad + lpadding
valf = str(r[nmi]).ljust(pad, fch).rjust(padfull, fch)
else:
if geoms is not None and nmi == gi:
pad = widths[nmi] + lpadding
padfull = pad + rpadding
valf = str(geoms).rjust(pad, fch).ljust(padfull, fch)
else:
pad = widths[nmi] + lpadding
padfull = pad + rpadding
valf = str(r[nmi]).rjust(pad, fch).ljust(padfull, fch)
frmtd.append(valf)
rw = delim.join(frmtd)
if verbose:
print rw # print row
sbuilder.append(rw)
ret = "\n".join(sbuilder) if returnit else None
return ret
def head(tbl, n=10, t=True, delimiter="; ", geoms=None, cols=["*"], w="", verbose=True):
"""Return top rows of table tbl.
Returns a list where the first element is a list of tuples representing
first n rows of table tbl, second element is a dictionary like:
{i: {"name":f.name, "values":[1,2,3,4 ...]}} for each field index i.
Optional:
n -- number of rows to read, default is 10
t -- if True (default), columns are printed as rows, otherwise as columns
delimiter -- string to be used to separate values (if t is True)
geoms -- if None (default), print geometries 'as is', else as str(geom).
cols -- list of columns to include, include all by default, case insensitive
w, where clause to limit selection from tbl
verbose -- suppress printing if False, default is True
Example:
>>> tmp = head('c:\\foo\\bar.shp', 5, True, "|", " ")
"""
allcols = ['*', ['*'], ('*'), [], ()]
colslower = [c.lower() for c in cols]
flds = arcpy.ListFields(arcpy.Describe(tbl).catalogPath)
if cols not in allcols:
flds = [f for f in flds if f.name.lower() in colslower]
fs = {}
nflds = len(flds)
fieldnames = []
for i in range(nflds):
f = flds[i]
if cols in allcols or f.name in cols:
fieldnames.append(f.name)
fs.update({i: {"name":f.name, "values":[]}})
i = 0
hd = []
with arcpy.da.SearchCursor(tbl, fieldnames, where_clause = w) as sc:
for row in sc:
i += 1
if i > n: break
hd.append(row)
for j in range(nflds):
fs[j]["values"].append(row[j])
if t:
labels = []
values = []
for fld in range(nflds):
f = fs[fld]
fl = flds[fld]
labels.append(str(fl.name) + " (" + str(fl.type) + "," + str(fl.length) + ")")
if fl.type.lower() == 'geometry' and (geoms is not None):
values.append(delimiter.join(map(str, len(f["values"]) * [geoms])))
else:
values.append(delimiter.join(map(str, f["values"])))
longestLabel = max(map(len, labels))
for l,v in zip(labels, values):
toprint = l.ljust(longestLabel, ".") + ": " + v
arcpy.AddMessage(toprint)
if verbose:
print toprint
else:
if verbose:
print_tuples(hd, delim=delimiter, tbl=flds, geoms=geoms, returnit=False)
return [hd, fs]
def chart(x, out_file='c:\\temp\\chart.jpg', texts={}, template=None, resolution=95, openit=True):
"""Create and open a map (JPG) showing x and return path to the figure path.
Required:
x -- input feature class, raster dataset, or a layer
Optional:
out_file -- path to output jpeg file, default is 'c:\\temp\\chart.jpg'
texts -- dict of strings to include in text elements on the map (by name)
template -- path to the .mxd to be used, default None points to mxd with
a single text element called "txt"
resolution -- output resolution in DPI (dots per inch)
openit -- if True (default), exported jpg is opened in a webbrowser
Example:
>>> chart('c:\\foo\\bar.shp')
>>> chart('c:\\foo\\bar.shp', texts = {'txt': 'A Map'}, resolution = 300)
"""
todel = []
import re
if template is None: template = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'chart.mxd')
if not re.findall(".mxd", template, flags=re.IGNORECASE): template += ".mxd"
if not re.findall(".jpe?g", out_file, flags=re.IGNORECASE): out_file += ".jpg"
mxd = arcpy.mapping.MapDocument(template)
if not arcpy.Exists(x):
x = arcpy.CopyFeatures_management(x, arcpy.CreateScratchName('tmp', workspace = 'in_memory')).getOutput(0)
todel = [x]
dtype = arcpy.Describe(x).dataType
df = arcpy.mapping.ListDataFrames(mxd)[0]
lr = "chart" + tstamp(tf = "%H%M%S")
if arcpy.Exists(lr) and arcpy.Describe(lr).dataType in ('FeatureLayer', 'RasterLayer'):
arcpy.Delete_management(lr)
if "raster" in dtype.lower():
arcpy.MakeRasterLayer_management(x, lr)
else:
arcpy.MakeFeatureLayer_management(x, lr)
lyr = arcpy.mapping.Layer(lr)
arcpy.mapping.AddLayer(df, lyr)
# try to update text elements if any requested:
for tel in texts.iterkeys():
try:
texel = arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT", tel)[0]
texel.text = str(texts[tel])
except Exception, e:
arcpy.AddMessage("Error when updating text element " + str(tel) + ": "+ str(e))
arcpy.RefreshActiveView()
arcpy.mapping.ExportToJPEG(mxd, out_file, resolution=resolution)
# cleanup
arcpy.Delete_management(lr)
del mxd
if todel: arcpy.Delete_management(todel[0])
# open the chart in a browser if requested
if openit:
import webbrowser
webbrowser.open_new_tab(out_file)
return arcpy.Describe(out_file).catalogPath
def plot(x, y=None, out_file="c:\\temp\\plot.png", main="Arcapi Plot", xlab="X", ylab="Y", pch="+", color="r", openit=True):
"""
Create and display a plot (PNG) showing x (and y).
Uses matplotlib.pyplot.scatter.
Required:
x -- values to plot on x axis
Optional:
y -- values to plot on y axis or None (default), then x will be plotted
on y axis, using index for x axis.
out_file -- path to output file, default is 'c:\\temp\\plot.png'
main -- title of the plot
xlab -- label for x axis
ylab -- label for y axis
pch
color -- color of points:
'r': red (default), 'b': blue, 'g': green, 'c': cyan, 'm': magenta,
'y': yellow, 'k': black, 'w': white, hexadecimal code like '#eeefff',
shades of grey as '0.75', 3-tuple like (0.1, 0.9, 0.5) for (R, G, B).
pch -- character for matplotlib plot marks, default is '+', can also be:
+: plus sign, .: dot, o: circle, *: star, p: pentagon, s:square, x: X,
D: diamond, h: hexagon, ^: triangle
openit -- if True (default), exported figure is opened in a webbrowser
Example:
>>> x = xrange(20)
>>> plot(x)
>>> plot(x, out_file='c:\\temp\\pic.png')
>>> y = xrange(50,70)
>>> plot(x, y, 'c:\\temp\\pic.png', 'Main', 'X [m]', 'Y [m]', 'o', 'k')
"""
import re
if not re.findall(".png", out_file, flags=re.IGNORECASE): out_file += ".png"
if y is None:
y = x
len(x)
x = xrange(len(y))
lx = len(x)
ly = len(y)
if lx != ly:
raise ArcapiError('x and y have different length, %s and %s' % (lx, ly))
from matplotlib import pyplot as plt
plt.scatter(x, y, c=color, marker=pch)
plt.title(str(main))
plt.xlabel(str(xlab))
plt.ylabel(str(ylab))
plt.savefig(out_file)
plt.close()
if openit:
import webbrowser
webbrowser.open_new_tab("file://" + out_file)
return
def hist(x, out_file='c:\\temp\\hist.png', openit=True, **args):
"""
Create and display a plot (PNG) showing histogram of x and return computed
histogram of values, breaks, and patches.
Uses matplotlib.pyplot.hist, for details see help(matplotlib.pyplot.hist).
Draws an empty plot if x is empty.
Required:
x -- Input data (not empty!); histogram is computed over the flattened array.
Optional:
bins -- int or sequence of scalars defining the number of equal-width bins.
or the bin edges including the rightmost edge. Default is 10.
range -- (float, float), the lower and upper range of the bins,
default is (min(x), max(x))
normed -- counts normalized to form a probability density if True, default False
weights -- array_like array of weights for each element of x.
cumulative -- cumulative counts from left are calculated if True, default False
histtype -- 'bar'(default)|'barstacked'|'step'|'stepfilled'
align -- 'left'|'mid'(default)|'right' to align bars to bin edges.
orientation -- 'horizontal'(default)|'vertical'
rwidth -- relative width [0.0 to 1.0] of the bars, default is None (automatic)
log -- if True, empty bins are filtered out and log scale set; default False
color -- scalar or array-like, the colors of the bar faces:
'r': red (default), 'b': blue, 'g': green, 'c': cyan, 'm': magenta,
'y': yellow, 'k': black, 'w': white, hexadecimal code like '#eeefff',
shades of grey as '0.75', 3-tuple like (0.1, 0.9, 0.5) for (R, G, B).
Can also be full color and style specification.
label -- label for legend if x has multiple datasets
out_file -- path to output file, default is 'c:\\temp\\hist.png'
main -- string, histogram main title
xlab -- string, label for the ordinate (independent) axis
openit -- if True (default), exported figure is opened in a webbrowser
Example:
>>> x = numpy.random.randn(10000)
>>> hist(x)
>>> hist(x, bins=20, color='r', main='A Title", xlab='Example')
"""
import matplotlib.pyplot as plt
# sort out parameters
extras = ('main', 'xlab', 'ylab')
pars = dict([(k,v) for k,v in args.iteritems() if k not in extras])
h = plt.hist(x, **pars)
plt.title(str(args.get('main', 'Histogram')))
xlab = str(args.get('xlab', 'Value'))
ylab = 'Count'
if args.get('Density', False):
ylab = 'Density'
if args.get('orientation', 'horizontal') == 'vertical':
lab = xlab
xlab = ylab
ylab = lab
plt.xlabel(str(xlab))
plt.ylabel(str(ylab))
plt.savefig(out_file)
plt.close()
if openit:
import webbrowser
webbrowser.open_new_tab("file://" + out_file)
return h
def bars(x, out_file='c:\\temp\\hist.png', openit=True, **args):
"""
Create and display a plot (PNG) showing barchart of x.
Uses matplotlib.plt.bar, draws an empty plot if x is empty.
Parameter width is always 1.0.
Use matplotlib colors for coloring;
'r': red, 'b': blue (default), 'g': green, 'c': cyan, 'm': magenta,
'y': yellow, 'k': black, 'w': white, hexadecimal code like '#eeefff',
shades of grey as '0.75', 3-tuple like (0.1, 0.9, 0.5) for (R, G, B).
Required:
x -- Input data. list-like of bar heights.
Optional:
color -- scalar or array-like, the colors of the bar faces
edgecolor -- scalar or array-like, the colors of the bar edges
linewidth -- scalar or array-like, default: None width of bar edge(s).
If None, use default linewidth; If 0, don't draw edges.
xerr -- scalar or array-like, use to generate errorbar(s) if not None (default)
yerr -- scalar or array-like, use to generate errorbar(s) if not None (default)
ecolor -- scalar or array-like, use as color of errorbar(s) if not None (default)
capsize -- integer, length of error bar caps in points, default: 3
orientation -- 'vertical'(default)|'horizontal', orientation of the bars
log -- boolean, set the axis to be log scale if True, default is False
# other
out_file -- path to output file, default is 'c:\\temp\\hist.png'
labels -- list-like of labels for each bar to display on x axis
main -- string, histogram main title
xlab -- string, label for the ordinate (independent) axis
openit -- if True (default), exported figure is opened in a webbrowser
Example:
>>> x = [1,2,3,4,5]
>>> lb = ['A','B','C','D','E']
>>> bars(x)
>>> bars(x, labels=lb, color='r', main='A Title', orientation='vertical')
"""
import matplotlib.pyplot as plt
import numpy
width = 1.0
# unpack arguments
bpars = ['width', 'color', 'edgecolor', 'linewidth', 'xerr', 'yerr',
'ecolor', 'capsize','error_kw', 'orientation', 'log']
barpars = dict([(i, args.get(i, None)) for i in args if i in bpars])
barpars['align'] = 'center'
center = range(len(x))
labels = args.get('labels', center)
barpars['width'] = width
orientation = barpars.get('orientation', 'vertical')
fig, ax = plt.subplots()
fig.canvas.draw()
# the orientation parameter seems to have no effect on pyplot.bar, therefore
# it is handled by calling barh instead of bar if orientation is horizontal
if orientation == 'horizontal':
a = barpars.pop('width', None)
a = barpars.pop('orientation', None)
plt.barh(center, x, **barpars)
else:
plt.bar(center, x, **barpars)
xlab = str(args.get('xlab', 'Item'))
ylab = str(args.get('ylab', 'Value'))
if orientation == 'horizontal':
lab = xlab
xlab = ylab
ylab = lab
ax.set_yticks(center)
ax.set_yticklabels(labels)
else:
ax.set_xticks(center)
ax.set_xticklabels(labels)
ax.set_xlabel(xlab)
ax.set_ylabel(str(ylab))
ax.set_title(str(args.get('main', 'Barplot')))
plt.savefig(out_file)
plt.close()
if openit:
import webbrowser
webbrowser.open_new_tab("file://" + out_file)
return
def pie(x, y=None, **kwargs):
"""
Create and display a plot (PNG) showing pie chart of x.
Uses matplotlib.pyplot.pie, draws an empty plot if x is empty.
The fractional area of each wedge is given by x/sum(x). If sum(x) <= 1,
then the values of x will be used as the fractional area directly.
Use matplotlib colors for coloring;
'r': red, 'b': blue, 'g': green, 'c': cyan, 'm': magenta,
'y': yellow, 'k': black, 'w': white, hexadecimal code like '#eeefff',
shades of grey as '0.75', 3-tuple like (0.1, 0.9, 0.5) for (R, G, B).
Required:
x -- Input data. list-like of bar heights.
Optional keyword arguments (see matplotlib.pyplot.pie for further details):
y -- Groupping data - list of factor values, len(x) == len(y),
values of x will be groupped by y and before the pie chart is plotted.
If y is specified, labels will include the relevant y value.
out_file -- output file, default is 'c:\\temp\\hist.png'
color -- scalar or array-like, the colors of the bar faces
labels -- list-like of labels for each wedge, or None for default labels
explode -- scalar or array like for offsetting wedges, default None (0.0)
main -- string, main title of the plot
openit -- Open exported figure in a webbrowser? True(default)|False.
autopct -- None, format string or function for labelling wedges.
pctdistance -- scalar or array like for fine tuning placment of text
labeldistance -- labels will be drawn this far from the pie (default is 1.1)
shadow -- Shadow beneath the pie? False(default)|True.
mainbox -- bbox properties of the main title, ignored if main is None
tight -- Apply tight layout? True(default)|False
Example:
>>> x = [1,2,3,4,5]
>>> lb = ['A','B','C','D','E']
>>> pie(x)
>>> pie(x, labels=lb, main='A Title')
>>> pie([1,2,3,4,5,6,7], y=[1,1,2,2,3,3,3], autopct='%1.1f%%')
>>> pie([1,2,3,4,5,6], y=[(1,'a'),(1,'a'),2,2,'b','b'], autopct='%1.1f%%')
"""
import matplotlib.pyplot as plt
# unpack arguments
#y = kwargs.get('y', None) # more convenient to get as a named argument
out_file =kwargs.get('out_file', 'c:\\temp\\hist.png')
openit = kwargs.get('openit', True)
#
explode = kwargs.get('explode', None)
labels = kwargs.get('labels', None)
colors = kwargs.get('colors', ('b', 'g', 'r', 'c', 'm', 'y', 'k', 'w'))
autopct = kwargs.get('autopct', None)
pctdistance = kwargs.get('pctdistance', 0.6)
labeldistance = kwargs.get('labeldistance', 1.1)
shadow = kwargs.get('shadow', False)
startangle = kwargs.get('startangle', 90)
#
main = kwargs.get('main', None)
mainbox = kwargs.get('mainbox', None)
legend = kwargs.get('legend', True)
legloc = kwargs.get('legloc', 'best')
tight = kwargs.get('tight', True)
# handle the cases when y parameter is supplied
# i.e. summarize x by y, construct labels etc.
n = len(x)
if y is not None:
if n != len(y):
raise ArcapiError("Lenghts of x and y must match, %s != %s" %
(n, len(y))
)
freqs = {}
for xi,yi in zip(x,y):
if yi in freqs:
freqs[yi] += xi
else:
freqs[yi] = xi
x,y = [],[]
for k,v in freqs.iteritems():
x.append(v)
y.append(k)
labels = y
# expand explode, labels, colors, etc. to the right length
n = len(x)
if explode is not None:
if isinstance(explode, list) or isinstance(explode, tuple):
if len(explode) != n:
explode = ( explode * n )[0:n]
else:
explode = [explode] * n
if labels is not None:
if isinstance(labels, list) or isinstance(labels, tuple):
if len(labels) != n:
labels = ( labels * n )[0:n]
else:
labels = [labels] * n
if colors is not None:
if isinstance(colors, list) or isinstance(colors, tuple):
if len(colors) != n:
colors = ( colors * n )[0:n]
else:
colors = [colors] * n
plt.figure(1)
plt.subplot(1,1,1)
pieresult = plt.pie(
x,
explode=explode,
labels=labels,
colors=colors,
autopct=autopct,
pctdistance=pctdistance,
shadow=shadow,
labeldistance=labeldistance
)
patches = pieresult[0]
texts = pieresult[1]
# add title
if main is not None:
plt.title(main, bbox=mainbox)
# add legend
if legend:
if labels is None:
labels = map(str, x)
plt.legend(patches, labels, loc=legloc)
# make output square and tight
plt.axis('equal')
if tight:
plt.tight_layout()
# save and display
plt.savefig(out_file)
plt.close()
if openit:
import webbrowser
webbrowser.open_new_tab("file://" + out_file)
return
def rename_col(tbl, col, newcol, alias = ''):
"""Rename column in table tbl and return the new name of the column.
This function first adds column newcol, re-calculates values of col into it,
and deletes column col.
Uses arcpy.ValidateFieldName to adjust newcol if not valid.
Raises ArcapiError if col is not found or if newcol already exists.
Required:
tbl -- table with the column to rename
col -- name of the column to rename
newcol -- new name of the column
Optional:
alias -- field alias for newcol, default is '' to use newcol for alias too
"""
if col != newcol:
d = arcpy.Describe(tbl)
dcp = d.catalogPath
flds = arcpy.ListFields(tbl)
fnames = [f.name.lower() for f in flds]
newcol = arcpy.ValidateFieldName(newcol, tbl) #os.path.dirname(dcp))
if col.lower() not in fnames:
raise ArcapiError("Field %s not found in %s." % (col, dcp))
if newcol.lower() in fnames:
raise ArcapiError("Field %s already exists in %s" % (newcol, dcp))
oldF = [f for f in flds if f.name.lower() == col.lower()][0]
if alias == "": alias = newcol
arcpy.AddField_management(tbl, newcol, oldF.type, oldF.precision, oldF.scale, oldF.length, alias, oldF.isNullable, oldF.required, oldF.domain)
arcpy.CalculateField_management(tbl, newcol, "!" + col + "!", "PYTHON_9.3")
arcpy.DeleteField_management(tbl, col)
return newcol
def tlist_to_table(x, out_tbl, cols, nullNumber=None, nullText=None):
"""Save a list of tuples as table out_tbl and return catalog path to it.
Required:
x -- list of tuples (no nesting!), can be list of lists or tuple of tuples
out_tbl -- path to the output table
cols -- list of tuples defining columns of x. Can be defined as:
[('colname1', 'type1'), ('colname2', 'type2'), ...]
['colname1:type1:lgt1', 'colname2:type2', ('colname3', 'type3')]
[('colname1', 'type1'), 'colname2:type2:lgt2, ...]
where types are case insensitive members of:
('SHORT', 'SMALLINTEGER', 'LONG', 'INTEGER', 'TEXT', 'STRING', 'DOUBLE',
'FLOAT')
Each column definition can have third element for length of the field,
e.g.: ('ATextColumn', 'TEXT', 250).
To leave out length, simply leave it out or set to '#'
Optional:
nullNumber -- a value to replace null (None) values in numeric columns, default is None and does no replacement
nullText -- a value to replace null (None) values in text columns, default is None and does no replacement
Example:
>>> x = [(...),(...),(...),(...),(...), ...]
>>> ot = 'c:\\temp\\foo.dbf'
>>> tlist_to_table(x, ot, [('IDO', 'SHORT'), ('NAME', 'TEXT', 200)]
>>> tlist_to_table(x, ot, ['IDO:SHORT', 'NAME:TEXT:200']
"""
# decode column names, types, and lengths
cols = [tuple(c.split(":")) if type(c) not in (tuple, list) else c for c in cols]
# remember what indexes to replace if values are null
replaceNumbers, replacesText = [], []
for i in range(len(cols)):
if cols[i][1].upper() in ('TEXT', 'STRING'):
replacesText.append(i)
else:
replaceNumbers.append(i)
doReplaceNumber = False if nullNumber is None else True
doReplaceText = False if nullText is None else True
doReplace = doReplaceNumber or doReplaceText
dname = os.path.dirname(out_tbl)
if dname in('', u''): dname = arcpy.env.workspace
r = arcpy.CreateTable_management(dname, os.path.basename(out_tbl))
out_tbl = r.getOutput(0)
# add the specified fields
for f in cols:
fname = f[0]
ftype = f[1].upper()
flength = '#'
if len(f) > 2:
flength = int(f[2]) if str(f[2]).isdigit() else '#'
arcpy.AddField_management(out_tbl, fname, ftype, '#', '#', flength)
# rewrite all tuples
fields = [c[0] for c in cols]
with arcpy.da.InsertCursor(out_tbl, fields) as ic:
for rw in x:
if doReplace:
rw = list(rw)
if i in replaceNumbers:
if rw[i] is None:
rw[i] = nullNumber
if i in replacesText:
if rw[i] is None:
rw[i] = nullText
rw = tuple(rw)
ic.insertRow(rw)
return out_tbl
def docu(x, n = None):
"""Print x.__doc__ string of the argument line by line using Python's print.
Similar to builtin help() but allows to limit number of rows printed.
Optional:
n -- print only n first rows (or everything if n > number of rows or None)
"""
dc = x.__doc__
dc = dc.split("\n")
nrows = len(dc)
n = nrows if n is None else n
n = min(n, nrows)
j = 0
for i in dc:
print i
j += 1
if j == n: break
return
def meta(datasource, mode="PREPEND", **args):
"""Read/write metadata of ArcGIS Feature Class, Raster Dataset, Table, etc.
Returns a dictionary of all accessible (if readonly) or all editted entries.
*** This function may irreversibly alter metadata, see details below! ***
The following entries (XML elements) can be read or updated:
Title ("dataIdInfo/idCitation/resTitle")
Purpose ("dataIdInfo/idPurp")
Abstract ("dataIdInfo/idAbs")
This function exports metadata of the datasource to XML file using template
'Metadata\Stylesheets\gpTools\exact copy of.xslt' from ArcGIS installation
directory. Then it loads the exported XML file into memory using Pythons
xml.etree.ElementTree, modifies supported elements, writes a new XML file,
and imports this new XML file as metadata to the datasource.
If the content of exported metada does not contain element dataInfo,
it is assumend the metadata is not up to date with current ArcGIS version
and UpgradeMetadata_conversion(datasource, 'ESRIISO_TO_ARCGIS') is applied!
Try whether this function is appropriate for your work flows on dummy data.
Required:
datasource -- path to the data source to update metadata for
mode -- {PREPEND|APPEND|OVERWRITE}, indicates whether new entries will be
prepended or appended to existing entries, or whether new entries will
overwrite existing entries. Case insensitive.
**args, keyword arguments of type string indicating what entries to update:
title, string to use in Title
purpose, string to use in Purpose
abstract, string to use in Abstract
If no keyword argument is specifed, metadata are read only, not edited.
Example:
>>> fc = 'c:\\foo\\bar.shp'
>>> meta(fc) # reads existing entries
>>> meta(fc, 'OVERWRITE', title="Bar") # updates title
>>> meta(fc, 'append', purpose='example', abstract='Column Spam means eggs')
"""
import xml.etree.ElementTree as ET
xslt = None # metadata template, could be exposed as a parameter
sf = arcpy.env.scratchFolder
tmpmetadatafile = arcpy.CreateScratchName('tmpmetadatafile', workspace=sf)
# checks
if xslt is None:
template = 'Metadata\Stylesheets\gpTools\exact copy of.xslt'
arcdir = arcpy.GetInstallInfo()['InstallDir']
xslt = os.path.join(arcdir, template)
if not os.path.isfile(xslt):
raise ArcapiError("Cannot find xslt file " + str(xslt))
mode = mode.upper()
lut_name_by_node = {
'dataIdInfo/idCitation/resTitle': 'title',
'dataIdInfo/idPurp': 'purpose',
'dataIdInfo/idAbs': 'abstract'
}
# work
r = arcpy.XSLTransform_conversion(datasource, xslt, tmpmetadatafile)
tmpmetadatafile = r.getOutput(0)
with file(tmpmetadatafile, "r") as f:
mf = f.read()
tree = ET.fromstring(mf)
# check if read-only access requested (no entries supplied)
readonly = True if len(args) == 0 else False
reader = {}
if readonly:
args = {'title':'', 'purpose':'', 'abstract': ''}
else:
# Update the metadata version if it is not up to date
if tree.find('dataIdInfo') is None:
arcpy.conversion.UpgradeMetadata(datasource, 'ESRIISO_TO_ARCGIS')
os.remove(tmpmetadatafile)
r = arcpy.XSLTransform_conversion(datasource, xslt, tmpmetadatafile)
tmpmetadatafile = r.getOutput(0)
with file(tmpmetadatafile, "r") as f:
mf = f.read()
tree = ET.fromstring(mf)
# get what user wants to update
entries = {}
if args.get('title', None) is not None:
entries.update({'dataIdInfo/idCitation/resTitle': args.get('title')})
if args.get('purpose', None) is not None:
entries.update({'dataIdInfo/idPurp': args.get('purpose')})