-
Notifications
You must be signed in to change notification settings - Fork 161
/
whitebox_tools.py
executable file
·10701 lines (8889 loc) · 482 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 urllib.request
import zipfile
import shutil
import os
from os import path
import sys
import platform
import re
import json
# 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.__compress_rasters = False
self.__max_procs = -1
if os.path.isfile('settings.json'):
# read the settings.json file if it exists
with open('settings.json', 'r') as settings_file:
data = settings_file.read()
# parse file
settings = json.loads(data)
self.work_dir = str(settings['working_directory'])
self.verbose = str(settings['verbose_mode'])
self.__compress_rasters = settings['compress_rasters']
self.__max_procs = settings['max_procs']
self.cancel_op = False
self.default_callback = default_callback
self.start_minimized = 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 get_working_dir(self):
return self.work_dir
def get_verbose_mode(self):
return self.verbose
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")
proc = None
if running_windows and self.start_minimized == True:
si = STARTUPINFO()
si.dwFlags = STARTF_USESHOWWINDOW
si.wShowWindow = 7 #Set window minimized and not activated
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, val=True):
'''
Sets the flag used by WhiteboxTools to determine whether to use compression for output rasters.
'''
self.__compress_rasters = val
try:
callback = self.default_callback
os.chdir(self.exe_path)
args2 = []
args2.append("." + path.sep + self.exe_name)
if self.__compress_rasters:
args2.append("--compress_rasters=true")
else:
args2.append("--compress_rasters=false")
proc = None
if running_windows and self.start_minimized == True:
si = STARTUPINFO()
si.dwFlags = STARTF_USESHOWWINDOW
si.wShowWindow = 7 #Set window minimized and not activated
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 get_compress_rasters(self):
return self.__compress_rasters
def set_max_procs(self, val=-1):
'''
Sets the flag used by WhiteboxTools to determine whether to use compression for output rasters.
'''
self.__max_procs = val
try:
callback = self.default_callback
os.chdir(self.exe_path)
args2 = []
args2.append("." + path.sep + self.exe_name)
args2.append(f"--max_procs={val}")
proc = None
if running_windows and self.start_minimized == True:
si = STARTUPINFO()
si.dwFlags = STARTF_USESHOWWINDOW
si.wShowWindow = 7 # Set window minimized and not activated
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 get_max_procs(self):
return self.__max_procs
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=True")
else:
args2.append("--compress_rasters=False")
if self.verbose:
cl = " ".join(args2)
callback(cl.strip() + "\n")
proc = None
if running_windows and self.start_minimized == True:
si = STARTUPINFO()
si.dwFlags = STARTF_USESHOWWINDOW
si.wShowWindow = 7 #Set window minimized and not activated
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:
if self.verbose:
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
def install_wbt_extension(self, ext_name=""):
try:
if len(ext_name) == 0:
ext_name = input(
'''Which extension would you like to install? (gte/lidar/dem/agri) ''')
# Figure out the appropriate URL to download the extension binary from.
url = "https://www.whiteboxgeo.com/GTE_Windows/GeneralToolsetExtension_win.zip" # default
unzipped_dir_name = "GeneralToolsetExtension"
if "agri" in ext_name.lower():
if platform.system() == 'Windows':
url = "https://www.whiteboxgeo.com/AgricultureToolset/AgricultureToolset_win.zip"
elif platform.system() == 'Darwin':
url = "https://www.whiteboxgeo.com/AgricultureToolset/AgricultureToolset_MacOS_Intel.zip"
elif platform.system() == 'Linux':
url = "https://www.whiteboxgeo.com/AgricultureToolset/AgricultureToolset_linux.zip"
unzipped_dir_name = "AgricultureToolset"
elif "dem" in ext_name.lower():
if platform.system() == 'Windows':
url = "https://www.whiteboxgeo.com/DemAndSpatialHydrologyToolset/DemAndSpatialHydrologyToolset_win.zip"
elif platform.system() == 'Darwin':
url = "https://www.whiteboxgeo.com/DemAndSpatialHydrologyToolset/DemAndSpatialHydrologyToolset_MacOS_Intel.zip"
elif platform.system() == 'Linux':
url = "https://www.whiteboxgeo.com/DemAndSpatialHydrologyToolset/DemAndSpatialHydrologyToolset_linux.zip"
unzipped_dir_name = "DemAndSpatialHydrologyToolset"
elif "lidar" in ext_name.lower():
if platform.system() == 'Windows':
url = "https://www.whiteboxgeo.com/LidarAndRemoteSensingToolset/LidarAndRemoteSensingToolset_win.zip"
elif platform.system() == 'Darwin':
url = "https://www.whiteboxgeo.com/LidarAndRemoteSensingToolset/LidarAndRemoteSensingToolset_MacOS_Intel.zip"
elif platform.system() == 'Linux':
url = "https://www.whiteboxgeo.com/LidarAndRemoteSensingToolset/LidarAndRemoteSensingToolset_linux.zip"
unzipped_dir_name = "LidarAndRemoteSensingToolset"
else: # default to the general toolset
if "gte" not in ext_name.lower():
print(f"Warning: Unrecognized extension ext_name {ext_name}. Installing the GTE instead...")
if platform.system() == 'Darwin':
url = "https://www.whiteboxgeo.com/GTE_Darwin/GeneralToolsetExtension_MacOS_Intel.zip"
elif platform.system() == 'Linux':
url = "https://www.whiteboxgeo.com/GTE_Linux/GeneralToolsetExtension_linux.zip"
# Download the extension binary
print("Downloading extension plugins...")
compressed_plugins_file = urllib.request.urlopen(url)
# Save it to a zip then decompress it and move the files to the plugins folder.
print("Installing extension plugins...")
with open('./compressed_plugins.zip','wb') as output:
output.write(compressed_plugins_file.read())
if not os.path.exists('./plugins'):
os.makedirs('./plugins')
with zipfile.ZipFile('./compressed_plugins.zip', 'r') as zip_ref:
zip_ref.extractall('./')
for entry in os.scandir(f'./{unzipped_dir_name}'):
new_path = entry.path.replace(f'{unzipped_dir_name}', 'plugins')
os.replace(entry.path, new_path)
if ".json" not in new_path and platform.system() != "Windows":
os.system("chmod 755 " + new_path) # grant executable permission
# Remove the unzipped directory, which isn't needed anymore.
if os.path.exists(f'./{unzipped_dir_name}'):
shutil.rmtree(f'./{unzipped_dir_name}')
# Get the updated Python API, so that they can use any new extension tools that
# have been released since the last open-core release from Python.
print("Updating WBT Python API...")
url = "https://raw.githubusercontent.com/jblindsay/whitebox-tools/master/whitebox_tools.py"
with urllib.request.urlopen(url) as f:
api_text = f.read().decode('utf-8')
with open('./whitebox_tools.py', 'w') as output:
output.write(api_text)
if "agri" in ext_name.lower():
print("The Whitebox Agriculture Toolset Extension has been installed!")
elif "dem" in ext_name.lower():
print("The Whitebox DEM and Spatial Hydrology Toolset Extension has been installed!")
elif "lidar" in ext_name.lower():
print("The Whitebox DEM and LiDAR and Remote Sensing Toolset Extension has been installed!")
else:
print("The Whitebox General Toolset Extension (GTE) has been installed!")
print(
'''
You will need to activate a license before using this extension. If you do
not currently have a valid activation key, you may purchase one by visiting
https://www.whiteboxgeo.com/extension-pricing/''')
# Does the user want to register an activation key for this extension?
reply = input("\nWould you like to activate a license key for the extension now? (Y/n) ")
if "y" in reply.lower():
self.activate_license()
else:
print(
'''
Okay, that's it for now.
''')
except Exception as e:
print("Unexpected error:", e)
print("Please contact [email protected] if you continue to experience issues.")
raise
def activate_license(self):
try:
if platform.system() == 'Windows':
os.system("plugins\\register_license.exe")
else:
os.system("./plugins/register_license")
except:
print("Unexpected error:", sys.exc_info()[0])
print("Please contact [email protected] if you continue to experience issues.")
raise
########################################################################
# 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 csv 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 fix_dangling_arcs(self, i, output, dist="", callback=None):
"""This tool fixes undershot and overshot arcs, two common topological errors, in an input vector lines file.
Keyword arguments:
i -- Name of the input lines vector file.
output -- Name of the output lines vector file.
dist -- Snap distance, in xy units (metres).
callback -- Custom function for handling tool text outputs.
"""
args = []
args.append("--input='{}'".format(i))
args.append("--output='{}'".format(output))
args.append("--dist={}".format(dist))
return self.run_tool('fix_dangling_arcs', args, callback) # returns 1 if error
def join_tables(self, input1, pkey, input2, fkey, import_field=None, 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))
if import_field is not None: 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):
"""Modifies nodata values in a raster.
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", cell_size=None, 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').
cell_size -- Optionally specified cell size of output raster. Not used when base raster is specified.
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))
if cell_size is not None: args.append("--cell_size='{}'".format(cell_size))
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.