-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgis_workflow.py
1668 lines (1237 loc) · 60.8 KB
/
gis_workflow.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 29 15:14:57 2015
@author: Sam Brooke
"""
import cement
import yaml
import os
from os.path import basename
import arcpy
import datetime
import shutil
import math
import csv
import glob
from arcpy import env
from arcpy.sa import *
from cement.core import foundation, controller
from cement.core.controller import expose
from cement.utils import shell
class GISAppController(controller.CementBaseController):
class Meta:
label = 'base'
description = 'Python CLI application to automate some GIS processing'
arguments = [
( ['-c', '--config'], dict(action='store', dest='config',
help='path to config file') ),
( ['-b', '--batch'], dict(action='store', dest='batch',
help='path to batch directory') ),
( ['-pp', '--pourpoints'], dict(action='store', dest='custom_pp',
help='custom pour points') ),
]
@expose(hide=True, aliases=['run'])
def default(self):
print("Running in default mode")
@expose(help='Use existing batch and skip to watershed processing')
def process_watersheds(self):
print("Skipping to watersheds")
self.app.skip_to_watersheds = 1
@expose(help='Use existing batch and skip to watershed processing')
def calculate_bqart(self):
print("Skipping to discharge calculations")
self.app.skip_to_watersheds = 1
self.app.skip_to_discharge = 1
@expose(help='Use pre-made catchment polygon (CODE & ALIAS columns required)')
def custom_pour_points(self):
print("Using specific watershed polygon")
self.app.custom_pour_points = 1
@expose(help='Prepare watersheds for Fastscape processing')
def fastscape(self):
print("Fastscape processing")
self.app.fastscape_process = 1
self.app.skip_to_discharge = 1
self.app.skip_to_watersheds = 1
class GISApp(foundation.CementApp):
skip_to_watersheds = 0
skip_to_discharge = 0
custom_pour_points = 0
fastscape_process = 0
class Meta:
label = 'GIS_Automator'
base_controller = GISAppController
app = GISApp()
class GISbatch:
'Common base class for GIS batch processing'
def __init__(self, config, batch = False):
self.project_root = config['root']
self.project_name = config['project_name']
self.projection_code = config['projection_code']
self.pour_points_path = config['pour_points_path']
self.lithology_path = config['lithology_path']
self.lithology_values = config['lithology_values']
self.fault_path = config['fault_path']
self.fault_data = ''
self.scratch_path = config['scratch']
self.output_path = config['output']
self.original_dem = config['original_dem']
self.uplift_mm_yr = config['uplift_mm_yr']
self.min_area = config['min_area']
self.fan_toes = config['fan_toes']
# Workflow variables
self.fill_check = config['fill']
self.flow_dir = config['flow_dir']
self.flow_acc = config['flow_acc']
self.str_net = config['str_net']
self.set_null = config['set_null']
self.str_ord = config['str_ord']
self.faults = config['faults']
self.pour_points = config['pour_points']
# Climate variables
self.climates = config['climates']
self.climate_basic = config['climate_basic']
# Fault data
self.fault_meta_data = {}
# Set the environment variables
arcpy.env.scratchWorkspace = self.scratch_path
self.set_environment(batch)
sr = arcpy.SpatialReference(self.projection_code)
arcpy.env.outputCoordinateSystem = sr
# Load in Spatial Analyst Toolbox
arcpy.CheckOutExtension("Spatial")
def set_custom_pp(self, path):
self.pour_points_path = path
def set_environment(self, batch = False):
if batch:
self.batch_path = batch
arcpy.env.workspace = self.batch_path
else:
self.batch_path = self.set_workspace()
arcpy.env.workspace = self.batch_path
def get_time_string(self):
t = datetime.datetime.now()
tstuff = [t.year, t.month, t.day, t.hour, t.minute, t.second]
# Convert integer values to string
tstring_list = map(str, tstuff)
d = '_'.join(tstring_list)
return d
def set_workspace(self):
if app.pargs.batch is None:
dirname = self.get_time_string()
# Assuming it doesn't exist already
output_batch_path = os.path.join(self.output_path, dirname)
os.makedirs(output_batch_path)
# Copy original DEM
shutil.copy2(self.original_dem, output_batch_path)
else:
if os.path.isdir(app.pargs.batch):
output_batch_path = app.pargs.batch
else:
print('Batch directory does not exist')
exit
return output_batch_path
def hydro_workflow(self):
print('Starting Hydrology Workflow...')
print('Fill')
if self.fill_check:
dem = self.fill()
else:
dem = self.original_dem
print('Flow direction')
flow_path = self.flow_direction(dem)
print('Flow accumulation')
flow_acc_path = self.flow_accumulation(flow_path)
print('Steam network')
stream_net_path = self.stream_network(flow_acc_path)
print('Nullify')
null_path = self.nullify(stream_net_path)
print('Stream order')
s_ord_path = self.stream_order(null_path, flow_path)
print('Vectorise streams')
vector_streams = self.vectorise_streams(s_ord_path, flow_path)
# Save file values to YAML file
hydro_paths = {
'working_dem' : dem,
'flow_path' : flow_path,
'flow_acc_path' : flow_acc_path,
'stream_net_path' : stream_net_path,
'null_path' : null_path,
's_ord_path' : s_ord_path,
'vector_streams' : vector_streams,
'fault_data': '',
'fault_data_meta':'',
'uplift_rate':self.uplift_mm_yr
}
with open(os.path.join(self.batch_path,'hydro_paths.yml'), 'w') as outfile:
outfile.write(yaml.dump(hydro_paths, default_flow_style=True) )
return hydro_paths
def fault_workflow(self, faultlines, hydro_paths):
print('Starting Fault workflow')
fault_data_path = os.path.join(self.batch_path, 'fault_data')
if os.path.exists(fault_data_path):
for f in os.listdir(fault_data_path):
os.unlink(os.path.join(fault_data_path,f))
else:
os.makedirs(fault_data_path)
self.fault_path = fault_data_path
print('Extracting fault data')
self.get_fault_data(faultlines)
print('Find intersects of faults and streams')
# Fault intersects
intersects_multipart = self.fault_intersects(faultlines, hydro_paths['vector_streams'], self.faults['cluster_tolerance'])
print('Changing intersects to singlepart dataset')
# Multipart to singlepart
intersects_singlepart = self.intersects_to_singlepart(intersects_multipart)
print('Removing low lying areas')
# Remove areas that are too low
self.highlands = self.remove_lowlands(self.pour_points['minimum_height'])
print('Removing pour point intersects below '+ str(self.pour_points['minimum_height']))
# Extract pour points above minimum height
pour_points = self.ignore_lowest_pp(intersects_singlepart, self.highlands)
print('Create fault routes')
# Create fault routes
fault_routes = self.fault_routes(faultlines)
print('Measure pour points along faults')
# Generate intersect events
intersect_events = self.intersect_events(pour_points, fault_routes, self.faults['search_radius'])
print('Saving fault data')
self.fault_data = self.extract_intersect_positions(intersect_events)
# Updating yaml paths
hydro_paths['fault_data'] = self.fault_data
hydro_paths['fault_meta_data'] = self.fault_meta_data
with open(os.path.join(self.batch_path,'hydro_paths.yml'), 'w') as outfile:
outfile.write(yaml.dump(hydro_paths, default_flow_style=True) )
return pour_points
def watershed_workflow(self, original_pour_points, hydro_paths):
print('Starting Watershed workflow')
print('Creating batch directory')
self.watershed_batch_path, pp_path = self.setup_watershed_batch(original_pour_points)
print('Snap to pour points')
snap_pp_path = self.snap_pour_points(pp_path, hydro_paths['flow_acc_path'])
print('Extract watersheds')
ws_path = self.watersheds(hydro_paths['flow_path'], snap_pp_path)
print('Converting to polygons')
ws_polygons = self.ws_to_poly(ws_path)
watershed_paths = {
'pour_points' : snap_pp_path,
'pour_points_vector': pp_path,
'watersheds' : ws_path,
'ws_polygons' : ws_polygons
}
if self.fan_toes:
print('Measuring fan lengths')
fan_toe_lengths = self.fan_toe_lengths(self.fan_toes, pp_path)
fan_toe_file = os.path.join(self.watershed_batch_path,'fan_toes.csv')
writer = csv.writer(open(fan_toe_file, 'wb'))
for key, value in fan_toe_lengths.iteritems():
writer.writerow([key, value])
watershed_paths.update({'fan_toes': fan_toe_file})
with open(os.path.join(self.watershed_batch_path,'watershed_paths.yml'), 'w') as outfile:
outfile.write(yaml.dump(watershed_paths, default_flow_style=True) )
return ws_path
def bqart_workflow(self, watershed_raster, hydro_paths, watershed_path,
temp_directory, precip_directory, climate_scenario, clear_cache):
precip_run = False
print('Starting BQART workflow')
# Are we ignoring any catchments?
ignore = self.ignore_catchments(watershed_path)
print('Creating climate batch directory')
climate_batch_path = self.climate_batch_directory(watershed_path, climate_scenario)
climate_cache_path = os.path.join(watershed_path, 'climate_cache', climate_scenario)
if climate_scenario.startswith('_basic_'):
# Just go with it
temp_val = temp_directory
precip_val = precip_directory
else:
precip_cache_check = self.check_climate_cache(watershed_path, climate_scenario, 't')
temp_cache_check = self.check_climate_cache(watershed_path, climate_scenario, 'p')
if clear_cache:
p = shell.Prompt("Continue to overwrite previous climate rasters", ['y','n'])
if p.input is 'y':
self.clear_cache(watershed_path, climate_scenario)
precip_cache_check = False
temp_cache_check = False
else:
exit
if precip_cache_check:
print('Precipitation cache found')
precip_clip_resample = temp_cache_check
else:
datatype = 'p'
combined_name = datatype + '_' + climate_scenario + '_all.tif'
clip_name_root = datatype + '_' + climate_scenario + '_clip'
resample_name = datatype + '_' + climate_scenario + '_resample.tif'
print('Clipping precipitation rasters')
precip_clip_dir = self.clip_rasters(precip_directory, climate_cache_path, datatype, clip_name_root, watershed_raster)
print('Averaging precipitation rasters')
precip_averaged = self.average_rasters(precip_clip_dir, climate_cache_path, combined_name, 0)
print('Resampling precipitation rasters')
precip_clip_resample = self.resample_climate_raster(precip_averaged, watershed_raster, climate_cache_path, resample_name)
if temp_cache_check:
print('Temperature cache found')
temp_clip_resample = temp_cache_check
else:
datatype = 't'
combined_name = datatype + '_' + climate_scenario + '_all.tif'
clip_name_root = datatype + '_' + climate_scenario + '_clip'
resample_name = datatype + '_' + climate_scenario + '_resample.tif'
print('Clipping temperature rasters')
temp_clip_dir = self.clip_rasters(temp_directory, climate_cache_path, datatype, clip_name_root, watershed_raster)
print('Averaging temperature rasters')
temp_averaged = self.average_rasters(temp_clip_dir, climate_cache_path, combined_name, 1)
print('Resampling temperature rasters')
temp_clip_resample = self.resample_climate_raster(temp_averaged, watershed_raster, climate_cache_path, resample_name)
print('Climate zone statistics')
tz_dat_path = self.zone_statistics(climate_batch_path, watershed_raster, temp_clip_resample, 'temp_data')
pz_dat_path = self.zone_statistics(climate_batch_path, watershed_raster, precip_clip_resample, 'precip_data')
ez_dat_path = self.zone_statistics(climate_batch_path, watershed_raster, self.original_dem, 'elev_data')
l_values = False
f = open(os.path.join(watershed_path, 'watershed_paths.yml'))
w_paths = yaml.load(f.read())
f.close()
if self.lithology_path:
if os.path.exists(self.lithology_path):
print('Lithology')
l_values = self.process_lithology(w_paths['ws_polygons'], self.lithology_path, climate_batch_path)
else:
print('Could not find lithology path')
print(self.lithology_path)
print('Calculating Qs using BQART')
print climate_scenario
if climate_scenario.startswith('_basic_'):
qs_data = self.do_bqart(False, False, ez_dat_path,
hydro_paths['fault_data'], hydro_paths['fault_data_meta'],
hydro_paths['uplift_rate'], w_paths['ws_polygons'], l_values, temp_val, precip_val)
else:
qs_data = self.do_bqart(pz_dat_path, tz_dat_path, ez_dat_path,
hydro_paths['fault_data'], hydro_paths['fault_data_meta'],
hydro_paths['uplift_rate'], w_paths['ws_polygons'], l_values, False, False)
catchment_ids, catchment_data = self.save_data_to_csv(qs_data, climate_batch_path, ignore, climate_scenario, w_paths)
self.extract_catchments(w_paths['ws_polygons'], catchment_ids, catchment_data, climate_batch_path, climate_scenario, ignore)
# ARC GIS PROCESSES
# Hydro stuff
def fill(self):
fill_z_limit = ""
out_fill = Fill(self.original_dem, fill_z_limit)
out_fill_raster = self.project_name + '_fill.tif'
out_fill_path = os.path.join(self.batch_path, out_fill_raster)
out_fill.save(out_fill_path)
return out_fill_path
def flow_direction(self, dem):
force_flow = self.flow_dir['force_flow']
out_flow_dir = FlowDirection(dem, force_flow)
out_flow_dir_raster = self.project_name + '_f_dir.tif'
out_flow_dir_path = os.path.join(self.batch_path, out_flow_dir_raster)
out_flow_dir.save(out_flow_dir_path)
return out_flow_dir_path
def flow_accumulation(self, flow_path):
flow_weight_raster = self.flow_acc['flow_weight_raster']
flow_data_type = self.flow_acc['flow_data_type']
out_flow_acc = FlowAccumulation(flow_path, flow_weight_raster, flow_data_type)
out_flow_acc_raster = self.project_name + '_f_acc.tif'
out_flow_acc_path = os.path.join(self.batch_path, out_flow_acc_raster)
out_flow_acc.save(out_flow_acc_path)
return out_flow_acc_path
def stream_network(self, flow_acc_path):
con_where_clause = self.str_net['conditional']
false_constant = self.str_net['false_constant']
true_raster = flow_acc_path
out_con = Con(flow_acc_path, true_raster, false_constant, con_where_clause)
out_con_raster = self.project_name + '_net.tif'
stream_net_path = os.path.join(self.batch_path, out_con_raster)
out_con.save(stream_net_path)
return stream_net_path
def nullify(self, stream_net_path):
false_raster = self.set_null['false_raster']
null_where_clause = self.set_null['conditional']
out_null = SetNull(stream_net_path, false_raster, null_where_clause)
out_null_raster = self.project_name + '_net_null.tif'
out_null_path = os.path.join(self.batch_path, out_null_raster)
out_null.save(out_null_path)
return out_null_path
def stream_order(self, null_path, flow_path):
method = self.str_ord['method']
out_s_ord_raster = self.project_name + '_s_order.tif'
out_s_ord_path = os.path.join(self.batch_path, out_s_ord_raster)
out_s_ord = StreamOrder(null_path, flow_path, method)
out_s_ord.save(out_s_ord_path)
return out_s_ord_path
def vectorise_streams(self, s_ord_path, flow_path):
out_sf_name = self.project_name + '_streams.shp'
out_sf_path = os.path.join(self.batch_path, out_sf_name)
StreamToFeature(s_ord_path, flow_path, out_sf_path)
return out_sf_path
# Fault stuff
def get_fault_data(self, faultlines):
fc = arcpy.SearchCursor(faultlines)
for row in fc:
# Get mean temperature
self.fault_meta_data.update({row.getValue('FID'):{
'name':row.getValue('name'),
'slip_min':row.getValue('slip_min'),
'slip_max':row.getValue('slip_max'),
'age_min':row.getValue('age_min'),
'age_max':row.getValue('age_max'),
'sense':row.getValue('sense')}})
def fault_intersects(self, faultlines, streams, cluster_tolerance):
inFeatures = [faultlines, streams]
intersects_name = self.project_name + '_intersects_multipart.shp'
intersects_multipart = os.path.join(self.fault_path, intersects_name)
arcpy.Intersect_analysis(inFeatures, intersects_multipart, "", cluster_tolerance, "point")
return intersects_multipart
def intersects_to_singlepart(self, intersects_multipart):
intersects_name = self.project_name + '_intersects_singlepart.shp'
intersects_singlepart = os.path.join(self.fault_path, intersects_name)
arcpy.MultipartToSinglepart_management(intersects_multipart, intersects_singlepart)
return intersects_singlepart
def remove_lowlands(self, minimum_height):
extract = ExtractByAttributes(self.original_dem, "VALUE > "+str(minimum_height))
dem_no_lowlands = os.path.join(self.fault_path, self.project_name + '_dem_no_lowlands.tif')
extract.save(dem_no_lowlands)
return dem_no_lowlands
def ignore_lowest_pp(self, intersects_singlepart, dem_no_lowlands):
intersect_heights = os.path.join(self.fault_path, self.project_name + '_intersects_all.shp')
ExtractValuesToPoints(intersects_singlepart, dem_no_lowlands, intersect_heights,
"INTERPOLATE", "ALL")
intersect_heights_above = os.path.join(self.fault_path, self.project_name + '_intersects_above.shp')
arcpy.Select_analysis(intersect_heights, intersect_heights_above, '"RASTERVALU" > 0')
return intersect_heights_above
def fault_routes(self, faultlines):
fault_routes = os.path.join(self.fault_path, self.project_name + "_fault_routes.shp")
arcpy.CreateRoutes_lr(faultlines, 'Id', fault_routes, "LENGTH")
return fault_routes
def intersect_events(self, pour_points, fault_routes, search_radius):
intersect_events = os.path.join(self.fault_path, self.project_name + "_intersect_events.dbf")
arcpy.LocateFeaturesAlongRoutes_lr(pour_points, fault_routes, "Id", search_radius, intersect_events, "RID POINT MEAS")
return intersect_events
def extract_intersect_positions(self, intersect_events):
ic_cursor = arcpy.SearchCursor(intersect_events)
fieldnames = [field.name for field in arcpy.ListFields(intersect_events)]
ic_data = []
for row in ic_cursor:
# Get mean temperature
ic_data.append([row.getValue('OID'), row.getValue(fieldnames[4]), row.getValue('MEAS')])
intersect_data = os.path.join(self.fault_path, self.project_name + "_intersect_data.csv")
row_headers = ['id', 'fault', 'distance']
with open(intersect_data, 'wb') as qs_file:
a = csv.writer(qs_file, delimiter=',')
a.writerow(row_headers)
for r in ic_data:
a.writerow([r[0], r[1], r[2]])
# Unlock data
del row
del ic_cursor
return intersect_data
# Watershed stuff
def setup_watershed_batch(self, original_pour_points):
# Each watershed calculations need to be discrete from one another
timestamp = self.get_time_string()
if os.path.isdir(os.path.join(self.batch_path, 'watershed_calcs')) == 0:
os.makedirs(os.path.join(self.batch_path, 'watershed_calcs'))
watershed_batch_path = os.path.join(self.batch_path, 'watershed_calcs', timestamp)
originals_batch_path = os.path.join(watershed_batch_path, 'originals')
os.makedirs(watershed_batch_path)
os.makedirs(originals_batch_path)
# Copy original Pour Points
shutil.copy2(original_pour_points, originals_batch_path)
working_pp_path = os.path.join(watershed_batch_path, basename(original_pour_points))
arcpy.CopyFeatures_management(original_pour_points, working_pp_path)
return watershed_batch_path, working_pp_path
def pour_points_to_raster(self, pour_points):
pp_raster_name = self.project_name +'_pp_raster.tif'
pp_raster_path = os.path.join(self.watershed_batch_path, pp_raster_name)
arcpy.PointToRaster_conversion(pour_points, "FID", pp_raster_path, 'MOST_FREQUENT', '', '10')
return pp_raster_path
def snap_pour_points(self, pour_points, flow_acc):
snap_distance = self.pour_points['snap_distance']
out_pp_name = self.project_name + '_snap_ppoints.tif'
out_pp_path = os.path.join(self.watershed_batch_path, out_pp_name)
pp = SnapPourPoint(pour_points, flow_acc, snap_distance, "FID")
pp.save(out_pp_path)
return out_pp_path
def watersheds(self, flow_path, pp_path):
inPourPointField = "VALUE"
out_ws_name = self.project_name + '_watersheds.tif'
out_ws_path = os.path.join(self.watershed_batch_path, out_ws_name)
outWatershed = Watershed(flow_path, pp_path, inPourPointField)
outWatershed.save(out_ws_path)
return out_ws_path
def fan_toe_lengths(self, fan_toes, pour_points):
pp = {}
ft = {}
toe_lengths = {}
with arcpy.da.SearchCursor(pour_points, ["SHAPE@", "FID"]) as pp_d:
for row in pp_d:
pp_x = row[0].extent.XMin
pp_y = row[0].extent.YMin
pp.update({int(row[1]):[pp_x, pp_y]})
with arcpy.da.SearchCursor(fan_toes, ["SHAPE@", "c_id"]) as ft_d:
for row in ft_d:
ft_x = row[0].extent.XMin
ft_y = row[0].extent.YMin
ft.update({int(row[1]):[ft_x, ft_y]})
for i, p in pp.iteritems():
f = ft[i]
dist = math.sqrt(math.pow((float(f[0])-float(p[0])), float(2))+math.pow((float(f[1])-float(p[1])), float(2)))
toe_lengths.update({i: dist})
return toe_lengths
def ws_to_poly(self, ws_path):
out_poly_name = self.project_name + '_poly_ws.shp'
out_poly_path = os.path.join(self.watershed_batch_path, out_poly_name)
arcpy.RasterToPolygon_conversion(ws_path, out_poly_path, "NO_SIMPLIFY", 'VALUE')
arcpy.AddField_management(out_poly_path, 'AREA', "TEXT")
arcpy.CalculateField_management(out_poly_path, 'AREA', '!SHAPE.AREA@SQUAREMETERS!', "PYTHON_9.3")
# Ignore off cuts
fields = ('FID', 'GRIDCODE', 'AREA')
gcodes = []
to_delete = []
duplicates = {}
fids = []
areas = []
with arcpy.da.SearchCursor(out_poly_path, fields) as sc:
for row in sc:
fids.append(row[0])
gcodes.append(row[1])
areas.append(row[2])
i = 0
for g in gcodes:
if gcodes.count(g) >1:
if g in duplicates:
duplicates[g].append(i)
else:
duplicates[g] = [i]
i = i+1
for k, d in duplicates.iteritems():
a1 = float(areas[d[0]])
a2 = float(areas[d[1]])
if (a1-a2) < 0:
to_delete.append(fids[d[0]])
else:
to_delete.append(fids[d[1]])
with arcpy.da.UpdateCursor(out_poly_path, fields) as uc:
for row in uc:
if row[0] in to_delete:
uc.deleteRow()
del row
del uc
del sc
return out_poly_path
# BQART stuff
def climate_batch_directory(self, watershed_directory, scenario):
timestamp = self.get_time_string()
print('Creating batch files')
climate_batch_path = os.path.join(watershed_directory, 'climate_calcs', str(timestamp)+'_'+scenario)
os.makedirs(climate_batch_path)
climate_cache_batch_path = os.path.join(watershed_directory, 'climate_cache')
climate_cache_scenario_path = os.path.join(climate_cache_batch_path, scenario)
if not os.path.isdir(climate_cache_batch_path):
os.makedirs(climate_cache_batch_path)
if not os.path.isdir(climate_cache_scenario_path):
os.makedirs(climate_cache_scenario_path)
return climate_batch_path
def check_climate_cache(self, watershed_directory, climate_scenario, datatype):
print('Checking for preexisting '+datatype+' rasters')
raster_name = datatype + '_' + climate_scenario + '_resample.tif'
raster_cache_path = os.path.join(watershed_directory, 'climate_cache', climate_scenario, raster_name)
output = False
if os.path.isfile(raster_cache_path):
output = raster_cache_path
return output
def clear_cache(Fself, watershed_directory, climate_scenario):
raster_cache_path = os.path.join(watershed_directory, 'climate_cache', climate_scenario)
for the_file in os.listdir(raster_cache_path):
file_path = os.path.join(raster_cache_path, the_file)
try:
if os.path.isfile(file_path):
os.unlink(file_path)
elif os.path.isdir(file_path):
shutil.rmtree(file_path)
#elif os.path.isdir(file_path): shutil.rmtree(file_path)
except Exception, e:
print e
def average_rasters(self, search_directory, save_directory, name, monthly):
os.chdir(search_directory)
rasters = []
for file in glob.glob("*.tif"):
rasters.append(Raster(os.path.join(search_directory,file)))
raster_sum = sum(rasters)
if monthly: # Temp
n_rasters = len(rasters)
combined_raster = raster_sum / n_rasters
else: # precip
combined_raster = raster_sum
combined_raster_path = os.path.join(save_directory, name)
combined_raster.save(combined_raster_path)
return combined_raster_path
def clip_rasters(self, raster_directory, save_directory, datatype, name, extent):
clip_dir = os.path.join(save_directory, 'raster_clips')
datatype_dir = os.path.join(save_directory, 'raster_clips', datatype)
if not os.path.exists(clip_dir):
os.makedirs(clip_dir)
if not os.path.exists(datatype_dir):
os.makedirs(datatype_dir)
os.chdir(raster_directory)
i = 0
for file in glob.glob("*.tif"):
i = i+1
cn = name + '_'+ str(i) + '.tif'
self.clip_raster(file, datatype_dir, cn, extent)
return datatype_dir
def clip_raster(self, input_raster, save_directory, name, extent):
clip_raster_path = os.path.join(save_directory, name)
arcpy.Clip_management(input_raster, '#', clip_raster_path, extent)
return clip_raster_path
def resample_climate_raster(self, climate_raster, watershed_raster, save_directory, raster_name):
cellsize_x = arcpy.GetRasterProperties_management(watershed_raster, "CELLSIZEX")
cellsize_y = arcpy.GetRasterProperties_management(watershed_raster, "CELLSIZEY")
cellsize = min([cellsize_x, cellsize_y])
climate_raster_resample = os.path.join(save_directory,raster_name)
arcpy.Resample_management(climate_raster, climate_raster_resample, cellsize, "NEAREST")
return climate_raster_resample
def zone_statistics(self, table_directory, watersheds, value_raster, data_name):
table_path = os.path.join(table_directory, data_name)
outdata = ZonalStatisticsAsTable(watersheds, "VALUE", value_raster, table_path, "DATA")
return outdata
def do_bqart(self, pz_data, tz_data, ez_data, fault_data_path, fault_meta_data, uplift_rate, polygons, l_values, temp_val, precip_val):
temps = {}
precips = {}
max_reliefs = {}
min_reliefs = {}
areas = {}
e_cursor = arcpy.SearchCursor(ez_data)
w_cursor = arcpy.SearchCursor(polygons)
if pz_data:
t_cursor = arcpy.SearchCursor(tz_data)
p_cursor = arcpy.SearchCursor(pz_data)
for row in t_cursor:
# Get mean temperature
temps.update({row.getValue('VALUE'): row.getValue('MEAN')})
for row in p_cursor:
# Get mean precipitation
precips.update({row.getValue('VALUE'): row.getValue('MEAN')})
del t_cursor
del p_cursor
for row in e_cursor:
# Get highest, lowest elevation & area of watersheds
max_reliefs.update({row.getValue('VALUE'): row.getValue('MAX')})
min_reliefs.update({row.getValue('VALUE'): row.getValue('MIN')})
for row in w_cursor:
c_id = row.getValue('GRIDCODE')
if c_id in areas:
areas[c_id] = areas[c_id] + float(row.getValue('AREA'))
else:
areas.update({c_id: float(row.getValue('AREA'))})
if temp_val and precip_val:
temps.update({c_id: float(temp_val)})
precips.update({c_id: float(precip_val)})
fault_data_output = {}
print('Adding fault data from')
if fault_data_path:
if os.path.exists(fault_data_path):
fault_data_output = {}
with open(fault_data_path, 'rb') as csvfile:
fault_data = csv.reader(csvfile, delimiter=',')
for row in fault_data:
fault_data_output.update({row[0]: [row[1], row[2]]})
# Unlock data
del row
del e_cursor
del w_cursor
# BQART
qs_rows = []
# Units!!
# Qs (kg/s)
# Qs (m^3/s)
# A (km^2)
# R (km)
# T (C)
# precips are in mm
# temps are in C x 10
# relief is in m
# area is m^2
# Are we ignoring any catchments?
for k in precips.keys():
precip = precips[k] # mm/yr - yearly average
area_m_squared = areas[k] # m^2
relief = max_reliefs[k] - min_reliefs[k] # m
temp = temps[k]/10 # C - yearly average (Worldclim temps need to be divided by 10)
density = 2700 # kg/m^3
omega = 0.0006
if l_values:
I = 1 #
L = l_values[k] # Lithology factor
Te = 0
Eb = 1
B = I * L * (1 - Te) * Eb
else:
B = 1
porosity = 0.3
# Convert precipitation to m/yr
precip_m = precip / float(1000)
# Relief to km
relief_km = relief / float(1000)
# Convert area to km^2
area_km_squared = area_m_squared / float(1000000)
# Discharge m^3/yr
precip_m3_yr = precip_m * float(area_m_squared)
# Disharge m^3/s
Qw_s = precip_m3_yr / float(60*60*24*365)
# Discharge km^3/yr
Qw_km_yr = math.pow(((Qw_s*(60*60*24*365))/1000000000),0.31)
# Area
A = math.pow(area_km_squared, 0.5)
if temp < 2:
# Qs in megatons per year
Qs_MT_yr = 2 * omega * B * Qw_km_yr * A * relief_km
else:
Qs_MT_yr = omega * B * Qw_km_yr * A * relief_km * temp
# Qs m^3/yr
Qs_m3_yr = Qs_MT_yr*((1000000000/density)*(1+porosity))
Qs_m_yr = Qs_m3_yr / float(area_m_squared)
Qs_mm_yr = Qs_m_yr * float(1000)
qs = [k, precip, omega, B,precip_m3_yr, Qw_s, Qw_km_yr, area_km_squared, A, relief_km, temp, Qs_MT_yr, porosity, density, Qs_m3_yr, Qs_m_yr, Qs_mm_yr]
if fault_data_output:
if fault_data_output[str(k)]:
fault_id = fault_data_output[str(k)][0]
# We're using max
max_fault_slip_mm_yr = fault_meta_data[int(fault_id)]['slip_max']
min_fault_slip_mm_yr = fault_meta_data[int(fault_id)]['slip_min']
qs.append(max_fault_slip_mm_yr)
qs.append(min_fault_slip_mm_yr)
# fault slip (m)
# corrected for density
Q_tectonic_max = (area_m_squared * (max_fault_slip_mm_yr/float(1000)))
Q_tectonic_min = (area_m_squared * (min_fault_slip_mm_yr/float(1000)))
# Simple Qs
qs.append(Q_tectonic_min)
qs.append(Q_tectonic_max)
# Fault number
qs.append(fault_id)
# Fault name
qs.append(fault_meta_data[int(fault_id)]['name'])
# Distance
qs.append(fault_data_output[str(k)][1])
else:
Uplift_mm_yr = uplift_rate
Uplift_metres_yr = Uplift_mm_yr / float(1000)
Q_tectonic = area_m_squared * Uplift_metres_yr
qs.append(Uplift_mm_yr)
qs.append(Uplift_mm_yr)
qs.append(Q_tectonic)
qs.append(Q_tectonic)
qs_rows.append(qs)
return qs_rows