forked from jblindsay/whitebox-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwhitebox_tools.py
8879 lines (7354 loc) · 392 KB
/
whitebox_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
#!/usr/bin/env python3
''' This file is intended to be a helper for running whitebox-tools plugins from a Python script.
See whitebox_example.py for an example of how to use it.
'''
# This script is part of the WhiteboxTools geospatial library.
# Authors: Dr. John Lindsay
# Created: 28/11/2017
# Last Modified: 09/12/2019
# License: MIT
from __future__ import print_function
import os
from os import path
import sys
import platform
import re
# import shutil
from subprocess import CalledProcessError, Popen, PIPE, STDOUT
running_windows = platform.system() == 'Windows'
if running_windows:
from subprocess import STARTUPINFO, STARTF_USESHOWWINDOW
def default_callback(value):
'''
A simple default callback that outputs using the print function. When
tools are called without providing a custom callback, this function
will be used to print to standard output.
'''
print(value)
def to_camelcase(name):
'''
Convert snake_case name to CamelCase name
'''
return ''.join(x.title() for x in name.split('_'))
def to_snakecase(name):
'''
Convert CamelCase name to snake_case name
'''
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
class WhiteboxTools(object):
'''
An object for interfacing with the WhiteboxTools executable.
'''
def __init__(self):
if running_windows:
self.ext = '.exe'
else:
self.ext = ''
self.exe_name = "whitebox_tools{}".format(self.ext)
# self.exe_path = os.path.dirname(shutil.which(
# self.exe_name) or path.dirname(path.abspath(__file__)))
# self.exe_path = os.path.dirname(os.path.join(os.path.realpath(__file__)))
self.exe_path = path.dirname(path.abspath(__file__))
self.work_dir = ""
self.verbose = True
self.cancel_op = False
self.default_callback = default_callback
self.start_minimized = False
self.__compress_rasters = False
def set_whitebox_dir(self, path_str):
'''
Sets the directory to the WhiteboxTools executable file.
'''
self.exe_path = path_str
def set_working_dir(self, path_str):
'''
Sets the working directory, i.e. the directory in which
the data files are located. By setting the working
directory, tool input parameters that are files need only
specify the file name rather than the complete file path.
'''
self.work_dir = path.normpath(path_str)
def set_verbose_mode(self, val=True):
'''
Sets verbose mode. If verbose mode is False, tools will not
print output messages. Tools will frequently provide substantial
feedback while they are operating, e.g. updating progress for
various sub-routines. When the user has scripted a workflow
that ties many tools in sequence, this level of tool output
can be problematic. By setting verbose mode to False, these
messages are suppressed and tools run as background processes.
'''
self.verbose = val
try:
callback = self.default_callback
os.chdir(self.exe_path)
args2 = []
args2.append("." + path.sep + self.exe_name)
if self.verbose:
args2.append("-v")
else:
args2.append("-v=false")
print(args2)
proc = None
if running_windows and self.start_minimized == True:
si = STARTUPINFO()
si.dwFlags = STARTF_USESHOWWINDOW
si.wShowWindow = 6 #Set window minimized
proc = Popen(args2, shell=False, stdout=PIPE,
stderr=STDOUT, bufsize=1, universal_newlines=True,
startupinfo=si)
else:
proc = Popen(args2, shell=False, stdout=PIPE,
stderr=STDOUT, bufsize=1, universal_newlines=True)
while proc is not None:
line = proc.stdout.readline()
sys.stdout.flush()
if line != '':
if not self.cancel_op:
callback(line.strip())
else:
self.cancel_op = False
proc.terminate()
return 2
else:
break
return 0
except (OSError, ValueError, CalledProcessError) as err:
callback(str(err))
return 1
def set_default_callback(self, callback_func):
'''
Sets the default callback used for handling tool text outputs.
'''
self.default_callback = callback_func
def set_compress_rasters(self, compress_rasters):
'''
Sets the flag used by WhiteboxTools to determine whether to use compression for output rasters.
'''
self.__compress_rasters = compress_rasters
def get_compress_rasters(self):
return self.__compress_rasters
def run_tool(self, tool_name, args, callback=None):
'''
Runs a tool and specifies tool arguments.
Returns 0 if completes without error.
Returns 1 if error encountered (details are sent to callback).
Returns 2 if process is cancelled by user.
'''
try:
if callback is None:
callback = self.default_callback
os.chdir(self.exe_path)
args2 = []
args2.append("." + path.sep + self.exe_name)
args2.append("--run=\"{}\"".format(to_camelcase(tool_name)))
if self.work_dir.strip() != "":
args2.append("--wd=\"{}\"".format(self.work_dir))
for arg in args:
args2.append(arg)
# args_str = args_str[:-1]
# a.append("--args=\"{}\"".format(args_str))
# if self.verbose:
# args2.append("-v")
# else:
# args2.append("-v=false")
if self.__compress_rasters:
args2.append("--compress_rasters")
if self.verbose:
cl = ""
for v in args2:
cl += v + " "
callback(cl.strip() + "\n")
proc = None
if running_windows and self.start_minimized == True:
si = STARTUPINFO()
si.dwFlags = STARTF_USESHOWWINDOW
si.wShowWindow = 6 #Set window minimized
proc = Popen(args2, shell=False, stdout=PIPE,
stderr=STDOUT, bufsize=1, universal_newlines=True,
startupinfo=si)
else:
proc = Popen(args2, shell=False, stdout=PIPE,
stderr=STDOUT, bufsize=1, universal_newlines=True)
while proc is not None:
line = proc.stdout.readline()
sys.stdout.flush()
if line != '':
if not self.cancel_op:
callback(line.strip())
else:
self.cancel_op = False
proc.terminate()
return 2
else:
break
return 0
except (OSError, ValueError, CalledProcessError) as err:
callback(str(err))
return 1
def help(self):
'''
Retrieves the help description for WhiteboxTools.
'''
try:
os.chdir(self.exe_path)
args = []
args.append("." + os.path.sep + self.exe_name)
args.append("-h")
proc = Popen(args, shell=False, stdout=PIPE,
stderr=STDOUT, bufsize=1, universal_newlines=True)
ret = ""
while True:
line = proc.stdout.readline()
if line != '':
ret += line
else:
break
return ret
except (OSError, ValueError, CalledProcessError) as err:
return err
def license(self, toolname=None):
'''
Retrieves the license information for WhiteboxTools.
'''
try:
os.chdir(self.exe_path)
args = []
args.append("." + os.path.sep + self.exe_name)
args.append("--license")
if toolname is not None:
args.append(f"={toolname}")
proc = Popen(args, shell=False, stdout=PIPE,
stderr=STDOUT, bufsize=1, universal_newlines=True)
ret = ""
while True:
line = proc.stdout.readline()
if line != '':
ret += line
else:
break
return ret
except (OSError, ValueError, CalledProcessError) as err:
return err
def version(self):
'''
Retrieves the version information for WhiteboxTools.
'''
try:
os.chdir(self.exe_path)
args = []
args.append("." + os.path.sep + self.exe_name)
args.append("--version")
proc = Popen(args, shell=False, stdout=PIPE,
stderr=STDOUT, bufsize=1, universal_newlines=True)
ret = ""
while True:
line = proc.stdout.readline()
if line != '':
ret += line
else:
break
return ret
except (OSError, ValueError, CalledProcessError) as err:
return err
def tool_help(self, tool_name=''):
'''
Retrieves the help description for a specific tool.
'''
try:
os.chdir(self.exe_path)
args = []
args.append("." + os.path.sep + self.exe_name)
args.append("--toolhelp={}".format(to_camelcase(tool_name)))
proc = Popen(args, shell=False, stdout=PIPE,
stderr=STDOUT, bufsize=1, universal_newlines=True)
ret = ""
while True:
line = proc.stdout.readline()
if line != '':
ret += line
else:
break
return ret
except (OSError, ValueError, CalledProcessError) as err:
return err
def tool_parameters(self, tool_name):
'''
Retrieves the tool parameter descriptions for a specific tool.
'''
try:
os.chdir(self.exe_path)
args = []
args.append("." + os.path.sep + self.exe_name)
args.append("--toolparameters={}".format(to_camelcase(tool_name)))
proc = Popen(args, shell=False, stdout=PIPE,
stderr=STDOUT, bufsize=1, universal_newlines=True)
ret = ""
while True:
line = proc.stdout.readline()
if line != '':
ret += line
else:
break
return ret
except (OSError, ValueError, CalledProcessError) as err:
return err
def toolbox(self, tool_name=''):
'''
Retrieve the toolbox for a specific tool.
'''
try:
os.chdir(self.exe_path)
args = []
args.append("." + os.path.sep + self.exe_name)
args.append("--toolbox={}".format(to_camelcase(tool_name)))
proc = Popen(args, shell=False, stdout=PIPE,
stderr=STDOUT, bufsize=1, universal_newlines=True)
ret = ""
while True:
line = proc.stdout.readline()
if line != '':
ret += line
else:
break
return ret
except (OSError, ValueError, CalledProcessError) as err:
return err
def view_code(self, tool_name):
'''
Opens a web browser to view the source code for a specific tool
on the projects source code repository.
'''
try:
os.chdir(self.exe_path)
args = []
args.append("." + os.path.sep + self.exe_name)
args.append("--viewcode={}".format(to_camelcase(tool_name)))
proc = Popen(args, shell=False, stdout=PIPE,
stderr=STDOUT, bufsize=1, universal_newlines=True)
ret = ""
while True:
line = proc.stdout.readline()
if line != '':
ret += line
else:
break
return ret
except (OSError, ValueError, CalledProcessError) as err:
return err
def list_tools(self, keywords=[]):
'''
Lists all available tools in WhiteboxTools.
'''
try:
os.chdir(self.exe_path)
args = []
args.append("." + os.path.sep + self.exe_name)
args.append("--listtools")
if len(keywords) > 0:
for kw in keywords:
args.append(kw)
proc = Popen(args, shell=False, stdout=PIPE,
stderr=STDOUT, bufsize=1, universal_newlines=True)
ret = {}
line = proc.stdout.readline() # skip number of available tools header
while True:
line = proc.stdout.readline()
if line != '':
if line.strip() != '':
name, descr = line.split(':')
ret[to_snakecase(name.strip())] = descr.strip()
else:
break
return ret
except (OSError, ValueError, CalledProcessError) as err:
return err
########################################################################
# The following methods are convenience methods for each available tool.
# This needs updating whenever new tools are added to the WhiteboxTools
# library. They can be generated automatically using the
# whitebox_plugin_generator.py script. It would also be possible to
# discover plugins at runtime and monkey-patch their methods using
# MethodType. However, this would not be as useful since it would
# restrict the ability for text editors and IDEs to use autocomplete.
########################################################################
##############
# Data Tools #
##############
def add_point_coordinates_to_table(self, i, callback=None):
"""Modifies the attribute table of a point vector by adding fields containing each point's X and Y coordinates.
Keyword arguments:
i -- Input vector Points file.
callback -- Custom function for handling tool text outputs.
"""
args = []
args.append("--input='{}'".format(i))
return self.run_tool('add_point_coordinates_to_table', args, callback) # returns 1 if error
def clean_vector(self, i, output, callback=None):
"""Removes null features and lines/polygons with fewer than the required number of vertices.
Keyword arguments:
i -- Input vector file.
output -- Output vector file.
callback -- Custom function for handling tool text outputs.
"""
args = []
args.append("--input='{}'".format(i))
args.append("--output='{}'".format(output))
return self.run_tool('clean_vector', args, callback) # returns 1 if error
def convert_nodata_to_zero(self, i, output, callback=None):
"""Converts nodata values in a raster to zero.
Keyword arguments:
i -- Input raster file.
output -- Output raster file.
callback -- Custom function for handling tool text outputs.
"""
args = []
args.append("--input='{}'".format(i))
args.append("--output='{}'".format(output))
return self.run_tool('convert_nodata_to_zero', args, callback) # returns 1 if error
def convert_raster_format(self, i, output, callback=None):
"""Converts raster data from one format to another.
Keyword arguments:
i -- Input raster file.
output -- Output raster file.
callback -- Custom function for handling tool text outputs.
"""
args = []
args.append("--input='{}'".format(i))
args.append("--output='{}'".format(output))
return self.run_tool('convert_raster_format', args, callback) # returns 1 if error
def csv_points_to_vector(self, i, output, xfield=0, yfield=1, epsg=None, callback=None):
"""Converts a CSV text file to vector points.
Keyword arguments:
i -- Input CSV file (i.e. source of data to be imported).
output -- Output vector file.
xfield -- X field number (e.g. 0 for first field).
yfield -- Y field number (e.g. 1 for second field).
epsg -- EPSG projection (e.g. 2958).
callback -- Custom function for handling tool text outputs.
"""
args = []
args.append("--input='{}'".format(i))
args.append("--output='{}'".format(output))
args.append("--xfield={}".format(xfield))
args.append("--yfield={}".format(yfield))
if epsg is not None: args.append("--epsg='{}'".format(epsg))
return self.run_tool('csv_points_to_vector', args, callback) # returns 1 if error
def export_table_to_csv(self, i, output, headers=True, callback=None):
"""Exports an attribute table to a CSV text file.
Keyword arguments:
i -- Input vector file.
output -- Output raster file.
headers -- Export field names as file header?.
callback -- Custom function for handling tool text outputs.
"""
args = []
args.append("--input='{}'".format(i))
args.append("--output='{}'".format(output))
if headers: args.append("--headers")
return self.run_tool('export_table_to_csv', args, callback) # returns 1 if error
def join_tables(self, input1, pkey, input2, fkey, import_field, callback=None):
"""Merge a vector's attribute table with another table based on a common field.
Keyword arguments:
input1 -- Input primary vector file (i.e. the table to be modified).
pkey -- Primary key field.
input2 -- Input foreign vector file (i.e. source of data to be imported).
fkey -- Foreign key field.
import_field -- Imported field (all fields will be imported if not specified).
callback -- Custom function for handling tool text outputs.
"""
args = []
args.append("--input1='{}'".format(input1))
args.append("--pkey='{}'".format(pkey))
args.append("--input2='{}'".format(input2))
args.append("--fkey='{}'".format(fkey))
args.append("--import_field='{}'".format(import_field))
return self.run_tool('join_tables', args, callback) # returns 1 if error
def lines_to_polygons(self, i, output, callback=None):
"""Converts vector polylines to polygons.
Keyword arguments:
i -- Input vector line file.
output -- Output vector polygon file.
callback -- Custom function for handling tool text outputs.
"""
args = []
args.append("--input='{}'".format(i))
args.append("--output='{}'".format(output))
return self.run_tool('lines_to_polygons', args, callback) # returns 1 if error
def merge_table_with_csv(self, i, pkey, csv, fkey, import_field=None, callback=None):
"""Merge a vector's attribute table with a table contained within a CSV text file.
Keyword arguments:
i -- Input primary vector file (i.e. the table to be modified).
pkey -- Primary key field.
csv -- Input CSV file (i.e. source of data to be imported).
fkey -- Foreign key field.
import_field -- Imported field (all fields will be imported if not specified).
callback -- Custom function for handling tool text outputs.
"""
args = []
args.append("--input='{}'".format(i))
args.append("--pkey='{}'".format(pkey))
args.append("--csv='{}'".format(csv))
args.append("--fkey='{}'".format(fkey))
if import_field is not None: args.append("--import_field='{}'".format(import_field))
return self.run_tool('merge_table_with_csv', args, callback) # returns 1 if error
def merge_vectors(self, inputs, output, callback=None):
"""Combines two or more input vectors of the same ShapeType creating a single, new output vector.
Keyword arguments:
inputs -- Input vector files.
output -- Output vector file.
callback -- Custom function for handling tool text outputs.
"""
args = []
args.append("--inputs='{}'".format(inputs))
args.append("--output='{}'".format(output))
return self.run_tool('merge_vectors', args, callback) # returns 1 if error
def modify_no_data_value(self, i, new_value="-32768.0", callback=None):
"""Converts nodata values in a raster to zero.
Keyword arguments:
i -- Input raster file.
new_value -- New NoData value.
callback -- Custom function for handling tool text outputs.
"""
args = []
args.append("--input='{}'".format(i))
args.append("--new_value={}".format(new_value))
return self.run_tool('modify_no_data_value', args, callback) # returns 1 if error
def multi_part_to_single_part(self, i, output, exclude_holes=True, callback=None):
"""Converts a vector file containing multi-part features into a vector containing only single-part features.
Keyword arguments:
i -- Input vector line or polygon file.
output -- Output vector line or polygon file.
exclude_holes -- Exclude hole parts from the feature splitting? (holes will continue to belong to their features in output.).
callback -- Custom function for handling tool text outputs.
"""
args = []
args.append("--input='{}'".format(i))
args.append("--output='{}'".format(output))
if exclude_holes: args.append("--exclude_holes")
return self.run_tool('multi_part_to_single_part', args, callback) # returns 1 if error
def new_raster_from_base(self, base, output, value="nodata", data_type="float", callback=None):
"""Creates a new raster using a base image.
Keyword arguments:
base -- Input base raster file.
output -- Output raster file.
value -- Constant value to fill raster with; either 'nodata' or numeric value.
data_type -- Output raster data type; options include 'double' (64-bit), 'float' (32-bit), and 'integer' (signed 16-bit) (default is 'float').
callback -- Custom function for handling tool text outputs.
"""
args = []
args.append("--base='{}'".format(base))
args.append("--output='{}'".format(output))
args.append("--value={}".format(value))
args.append("--data_type={}".format(data_type))
return self.run_tool('new_raster_from_base', args, callback) # returns 1 if error
def polygons_to_lines(self, i, output, callback=None):
"""Converts vector polygons to polylines.
Keyword arguments:
i -- Input vector polygon file.
output -- Output vector lines file.
callback -- Custom function for handling tool text outputs.
"""
args = []
args.append("--input='{}'".format(i))
args.append("--output='{}'".format(output))
return self.run_tool('polygons_to_lines', args, callback) # returns 1 if error
def print_geo_tiff_tags(self, i, callback=None):
"""Prints the tags within a GeoTIFF.
Keyword arguments:
i -- Input GeoTIFF file.
callback -- Custom function for handling tool text outputs.
"""
args = []
args.append("--input='{}'".format(i))
return self.run_tool('print_geo_tiff_tags', args, callback) # returns 1 if error
def raster_to_vector_lines(self, i, output, callback=None):
"""Converts a raster lines features into a vector of the POLYLINE shapetype.
Keyword arguments:
i -- Input raster lines file.
output -- Output raster file.
callback -- Custom function for handling tool text outputs.
"""
args = []
args.append("--input='{}'".format(i))
args.append("--output='{}'".format(output))
return self.run_tool('raster_to_vector_lines', args, callback) # returns 1 if error
def raster_to_vector_points(self, i, output, callback=None):
"""Converts a raster dataset to a vector of the POINT shapetype.
Keyword arguments:
i -- Input raster file.
output -- Output vector points file.
callback -- Custom function for handling tool text outputs.
"""
args = []
args.append("--input='{}'".format(i))
args.append("--output='{}'".format(output))
return self.run_tool('raster_to_vector_points', args, callback) # returns 1 if error
def raster_to_vector_polygons(self, i, output, callback=None):
"""Converts a raster dataset to a vector of the POLYGON shapetype.
Keyword arguments:
i -- Input raster file.
output -- Output vector polygons file.
callback -- Custom function for handling tool text outputs.
"""
args = []
args.append("--input='{}'".format(i))
args.append("--output='{}'".format(output))
return self.run_tool('raster_to_vector_polygons', args, callback) # returns 1 if error
def reinitialize_attribute_table(self, i, callback=None):
"""Reinitializes a vector's attribute table deleting all fields but the feature ID (FID).
Keyword arguments:
i -- Input vector file.
callback -- Custom function for handling tool text outputs.
"""
args = []
args.append("--input='{}'".format(i))
return self.run_tool('reinitialize_attribute_table', args, callback) # returns 1 if error
def remove_polygon_holes(self, i, output, callback=None):
"""Removes holes within the features of a vector polygon file.
Keyword arguments:
i -- Input vector polygon file.
output -- Output vector polygon file.
callback -- Custom function for handling tool text outputs.
"""
args = []
args.append("--input='{}'".format(i))
args.append("--output='{}'".format(output))
return self.run_tool('remove_polygon_holes', args, callback) # returns 1 if error
def set_nodata_value(self, i, output, back_value=0.0, callback=None):
"""Assign a specified value in an input image to the NoData value.
Keyword arguments:
i -- Input raster file.
output -- Output raster file.
back_value -- Background value to set to nodata.
callback -- Custom function for handling tool text outputs.
"""
args = []
args.append("--input='{}'".format(i))
args.append("--output='{}'".format(output))
args.append("--back_value={}".format(back_value))
return self.run_tool('set_nodata_value', args, callback) # returns 1 if error
def single_part_to_multi_part(self, i, output, field=None, callback=None):
"""Converts a vector file containing multi-part features into a vector containing only single-part features.
Keyword arguments:
i -- Input vector line or polygon file.
field -- Grouping ID field name in attribute table.
output -- Output vector line or polygon file.
callback -- Custom function for handling tool text outputs.
"""
args = []
args.append("--input='{}'".format(i))
if field is not None: args.append("--field='{}'".format(field))
args.append("--output='{}'".format(output))
return self.run_tool('single_part_to_multi_part', args, callback) # returns 1 if error
def vector_lines_to_raster(self, i, output, field="FID", nodata=True, cell_size=None, base=None, callback=None):
"""Converts a vector containing polylines into a raster.
Keyword arguments:
i -- Input vector lines file.
field -- Input field name in attribute table.
output -- Output raster file.
nodata -- Background value to set to NoData. Without this flag, it will be set to 0.0.
cell_size -- Optionally specified cell size of output raster. Not used when base raster is specified.
base -- Optionally specified input base raster file. Not used when a cell size is specified.
callback -- Custom function for handling tool text outputs.
"""
args = []
args.append("--input='{}'".format(i))
args.append("--field={}".format(field))
args.append("--output='{}'".format(output))
if nodata: args.append("--nodata")
if cell_size is not None: args.append("--cell_size='{}'".format(cell_size))
if base is not None: args.append("--base='{}'".format(base))
return self.run_tool('vector_lines_to_raster', args, callback) # returns 1 if error
def vector_points_to_raster(self, i, output, field="FID", assign="last", nodata=True, cell_size=None, base=None, callback=None):
"""Converts a vector containing points into a raster.
Keyword arguments:
i -- Input vector Points file.
field -- Input field name in attribute table.
output -- Output raster file.
assign -- Assignment operation, where multiple points are in the same grid cell; options include 'first', 'last' (default), 'min', 'max', 'sum'.
nodata -- Background value to set to NoData. Without this flag, it will be set to 0.0.
cell_size -- Optionally specified cell size of output raster. Not used when base raster is specified.
base -- Optionally specified input base raster file. Not used when a cell size is specified.
callback -- Custom function for handling tool text outputs.
"""
args = []
args.append("--input='{}'".format(i))
args.append("--field={}".format(field))
args.append("--output='{}'".format(output))
args.append("--assign={}".format(assign))
if nodata: args.append("--nodata")
if cell_size is not None: args.append("--cell_size='{}'".format(cell_size))
if base is not None: args.append("--base='{}'".format(base))
return self.run_tool('vector_points_to_raster', args, callback) # returns 1 if error
def vector_polygons_to_raster(self, i, output, field="FID", nodata=True, cell_size=None, base=None, callback=None):
"""Converts a vector containing polygons into a raster.
Keyword arguments:
i -- Input vector polygons file.
field -- Input field name in attribute table.
output -- Output raster file.
nodata -- Background value to set to NoData. Without this flag, it will be set to 0.0.
cell_size -- Optionally specified cell size of output raster. Not used when base raster is specified.
base -- Optionally specified input base raster file. Not used when a cell size is specified.
callback -- Custom function for handling tool text outputs.
"""
args = []
args.append("--input='{}'".format(i))
args.append("--field={}".format(field))
args.append("--output='{}'".format(output))
if nodata: args.append("--nodata")
if cell_size is not None: args.append("--cell_size='{}'".format(cell_size))
if base is not None: args.append("--base='{}'".format(base))
return self.run_tool('vector_polygons_to_raster', args, callback) # returns 1 if error
################
# GIS Analysis #
################
def aggregate_raster(self, i, output, agg_factor=2, type="mean", callback=None):
"""Aggregates a raster to a lower resolution.
Keyword arguments:
i -- Input raster file.
output -- Output raster file.
agg_factor -- Aggregation factor, in pixels.
type -- Statistic used to fill output pixels.
callback -- Custom function for handling tool text outputs.
"""
args = []
args.append("--input='{}'".format(i))
args.append("--output='{}'".format(output))
args.append("--agg_factor={}".format(agg_factor))
args.append("--type={}".format(type))
return self.run_tool('aggregate_raster', args, callback) # returns 1 if error
def block_maximum_gridding(self, i, field, output, use_z=False, cell_size=None, base=None, callback=None):
"""Creates a raster grid based on a set of vector points and assigns grid values using a block maximum scheme.
Keyword arguments:
i -- Input vector Points file.
field -- Input field name in attribute table.
use_z -- Use z-coordinate instead of field?.
output -- Output raster file.
cell_size -- Optionally specified cell size of output raster. Not used when base raster is specified.
base -- Optionally specified input base raster file. Not used when a cell size is specified.
callback -- Custom function for handling tool text outputs.
"""
args = []
args.append("--input='{}'".format(i))
args.append("--field='{}'".format(field))
if use_z: args.append("--use_z")
args.append("--output='{}'".format(output))
if cell_size is not None: args.append("--cell_size='{}'".format(cell_size))
if base is not None: args.append("--base='{}'".format(base))
return self.run_tool('block_maximum_gridding', args, callback) # returns 1 if error
def block_minimum_gridding(self, i, field, output, use_z=False, cell_size=None, base=None, callback=None):
"""Creates a raster grid based on a set of vector points and assigns grid values using a block minimum scheme.
Keyword arguments:
i -- Input vector Points file.
field -- Input field name in attribute table.
use_z -- Use z-coordinate instead of field?.
output -- Output raster file.
cell_size -- Optionally specified cell size of output raster. Not used when base raster is specified.
base -- Optionally specified input base raster file. Not used when a cell size is specified.
callback -- Custom function for handling tool text outputs.
"""
args = []
args.append("--input='{}'".format(i))
args.append("--field='{}'".format(field))
if use_z: args.append("--use_z")
args.append("--output='{}'".format(output))
if cell_size is not None: args.append("--cell_size='{}'".format(cell_size))
if base is not None: args.append("--base='{}'".format(base))
return self.run_tool('block_minimum_gridding', args, callback) # returns 1 if error
def centroid(self, i, output, text_output=False, callback=None):
"""Calculates the centroid, or average location, of raster polygon objects.
Keyword arguments:
i -- Input raster file.
output -- Output raster file.
text_output -- Optional text output.
callback -- Custom function for handling tool text outputs.
"""
args = []
args.append("--input='{}'".format(i))
args.append("--output='{}'".format(output))
if text_output: args.append("--text_output")
return self.run_tool('centroid', args, callback) # returns 1 if error
def centroid_vector(self, i, output, callback=None):
"""Identifes the centroid point of a vector polyline or polygon feature or a group of vector points.
Keyword arguments:
i -- Input vector file.
output -- Output vector file.
callback -- Custom function for handling tool text outputs.
"""
args = []
args.append("--input='{}'".format(i))
args.append("--output='{}'".format(output))
return self.run_tool('centroid_vector', args, callback) # returns 1 if error
def clump(self, i, output, diag=True, zero_back=False, callback=None):
"""Groups cells that form discrete areas, assigning them unique identifiers.
Keyword arguments:
i -- Input raster file.
output -- Output raster file.
diag -- Flag indicating whether diagonal connections should be considered.
zero_back -- Flag indicating whether zero values should be treated as a background.
callback -- Custom function for handling tool text outputs.
"""
args = []
args.append("--input='{}'".format(i))
args.append("--output='{}'".format(output))
if diag: args.append("--diag")
if zero_back: args.append("--zero_back")
return self.run_tool('clump', args, callback) # returns 1 if error
def construct_vector_tin(self, i, output, field=None, use_z=False, max_triangle_edge_length=None, callback=None):
"""Creates a vector triangular irregular network (TIN) for a set of vector points.
Keyword arguments:
i -- Input vector points file.