-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathWSEL_Main.py
1204 lines (1087 loc) · 47.3 KB
/
WSEL_Main.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
from __future__ import print_function
import time, sys, os, re, arcinfo, arcpy, cPickle, logging, json
from multiprocessing import Pool
from WSEL_XS_Check import *
from WSEL_Stream_Setup import *
from WSEL_Intersects import *
from WSEL_Intersects_Clean import *
from WSEL_Step_1 import *
from WSEL_Step_2 import *
from WSEL_Step_3 import *
from WSEL_Step_4 import *
from WSEL_Step_5 import *
from arcpy import env
def Script_setup(check, scriptlocation, r):
setup={}
if check==True:
#TODO add support for arcgis toolbox
multiproc = arcpy.GetParameterAsText(1)
proc = arcpy.GetParameterAsText(2)
projectname = arcpy.GetParameterAsText(3)
rootdir = arcpy.GetParameterAsText(4)
sr=arcpy.GetParameterAsText(5)
modelbuilder = True
else:
multiproc = True #For large groups you must use this
proc = 4 #Number of processors you want to run on
modelbuilder = False
flood_boundary = True #If using for polylinezm only flood_boundary is not needed
rid_field="StrmName" #Name of the Route field usually where you find the stream name or reach code
wsel_field = r
station_field ="Section" #Name of the station field in the xs files usually Section or ProfileM
backwater = True #If you want to correct for backwater
if backwater == True:
main_stream = "BloodyCreek" #Stream that all streams in the given study area flow into
else:
main_stream = ''
projectname = "BC" #Change to descriptive project name
rootdir = "C:\\Users\\bmulcahy\\External\\Projects\\WSEL-Python-Tool\\data\\Testing" # directory where initial data can be found
sr="E:\\Lower CottonwoodRiver\\Data\\run1\\CottonwoodRiver\\CottonwoodRiver.prj" #Spatial reference used in script can accept either text or file location to a .prj file
main =os.path.join(scriptlocation,"output\\"+projectname)
scratch = os.path.join(main,wsel_field)
if not os.path.exists(scratch):
os.makedirs(scratch)
configfile = os.path.join(scratch,"config.cfg")
logfile = os.path.join(scratch,"log.txt")
originalgdb = os.path.join(main,"Original.gdb")
streams_original = os.path.join(originalgdb,'streams')
flood_original = os.path.join(originalgdb,'flood')
xs_original = os.path.join(originalgdb,'xs')
finalgdb = os.path.join(main,"Final.gdb")
streams_final = os.path.join(finalgdb,'streams')
flood_final = os.path.join(finalgdb,'flood')
xs_final = os.path.join(finalgdb,'xs')
final = os.path.join(main,"Output")
setup ={'flood_boundary':flood_boundary,'modelbuilder': modelbuilder,
'main_stream':main_stream,'main': main,
'finalgdb': finalgdb,'streams_final': streams_final,
'flood_final':flood_final,'xs_final':xs_final,
'rid_field': rid_field,'wsel_field': wsel_field,
'station_field': station_field,'backwater': backwater,
'sr': sr,'Rootdir':rootdir,
'Projectname': projectname, 'multiproc': multiproc,
'Proc': proc,'scratch': scratch,
'logfile': logfile,'configfile': configfile,
'originalgdb': originalgdb,'streams_original': streams_original,
'flood_original':flood_original,'xs_original':xs_original,
'final':final}
return setup
#print_to_log print to log file in plain text format
def print_to_log(setup, param, data):
logfile = setup['logfile']
with open(logfile, "ab+") as text_file:
print("{} = {}".format(param,data), end='\n',file=text_file)
return
#print_to_config prints out to config file which will be loading before each run cfg file is not readable unless by python
def print_to_config(setup, param, data):
configfile = setup['configfile']
topickle = {param: data}
with open(configfile, "a+b") as text_file:
cPickle.dump(topickle,text_file)
return
#OriginalWorkspace creates the original and final gdb that can be shared among processes and scenarios
def OriginalWorkspace(setup):
print("Creating workspace")
main=setup['main']
scratch = setup['scratch']
final= setup['final']
originalgdb= setup['originalgdb']
xs_original= setup['xs_original']
streams_original= setup['streams_original']
flood_original= setup['flood_original']
finalgdb= setup['finalgdb']
xs_final= setup['xs_final']
streams_final= setup['streams_final']
flood_final= setup['flood_final']
configfile = setup['configfile']
sr = setup['sr']
projectname = setup['Projectname']
if not os.path.exists(final):
os.makedirs(final)
if not os.path.exists(finalgdb):
arcpy.CreateFileGDB_management(main, "Final.gdb")
if not arcpy.Exists(xs_final):
arcpy.CreateFeatureDataset_management(finalgdb, "xs", sr)
if not arcpy.Exists(streams_final):
arcpy.CreateFeatureDataset_management(finalgdb, "streams", sr)
if not arcpy.Exists(flood_final):
arcpy.CreateFeatureDataset_management(finalgdb, "flood", sr)
if not os.path.exists(originalgdb):
arcpy.CreateFileGDB_management(main, "Original.gdb")
if not arcpy.Exists(xs_original):
arcpy.CreateFeatureDataset_management(originalgdb, "xs", sr)
if not arcpy.Exists(streams_original):
arcpy.CreateFeatureDataset_management(originalgdb, "streams", sr)
if not arcpy.Exists(flood_original):
arcpy.CreateFeatureDataset_management(originalgdb, "flood", sr)
env.workspace = originalgdb
env.overwriteOutput = True
env.MResolution = 0.0001
env.MDomain = "0 10000000"
env.outputMFlag = "Enabled"
env.outputZFlag = "Enabled"
print_to_log(setup,"OriginalWorkspace","Complete")
print_to_config(setup,"OriginalWorkspace",True)
return
#Copys all the streams found in the root data folder that match the file directory and naming conventions outlined below
def CopyWorkspace(setup):
print("Copying data into workspace")
xs_original= setup['xs_original']
streams_original= setup['streams_original']
streams_dataset= setup['streams_original']
flood_original= setup['flood_original']
rootdir = setup['Rootdir']
job_config ={'config':[],'stream_names':[]}
flood_boundary = setup['flood_boundary']
incomplete_streams =[]
stream_count = 0
for name in os.listdir(rootdir):
if os.path.isdir(os.path.join(rootdir, name)):
directory = os.path.join(rootdir, name)
stream_loc = os.path.join(directory, name+'.shp')
xs_original_loc = os.path.join(directory, name+'_xsecs_results.shp')
boundary_loc = os.path.join(directory, name+'_flood.shp')
if flood_boundary == True:
if os.path.isfile(stream_loc) and os.path.isfile(xs_original_loc) and os.path.isfile(boundary_loc):
print("Copying "+name+" data into file geodatabase")
stream_count=stream_count+1
job_config['stream_names'].append(name)
arcpy.FeatureToLine_management(xs_original_loc, xs_original+"/"+name+"_xs")
arcpy.FeatureToLine_management(stream_loc,streams_original+"/"+name+"_stream_feature")
arcpy.FeatureToPolygon_management(boundary_loc,flood_original+"/"+name+"_flood_boundary")
else:
incomplete_streams.append(name)
print(name+" does not have all the needed data")
elif os.path.isfile(stream_loc) and os.path.isfile(xs_original_loc):
print("Copying "+name+" data into file geodatabase")
stream_count=stream_count+1
job_config['stream_names'].append(name)
arcpy.FeatureToLine_management(xs_original_loc, xs_original+"/"+name+"_xs")
arcpy.FeatureToLine_management(stream_loc,streams_original+"/"+name+"_stream_feature")
else:
incomplete_streams.append(name)
print(name+" does not have all the needed data")
print(str(stream_count)+" Streams found that can be processed.")
missing=''.join(incomplete_streams)
if incomplete_streams:
print_to_log(setup,"Incomplete Data for Streams(folder names)",missing)
print_to_log(setup,"Number of Streams to be processed",stream_count)
print_to_log(setup,"CopyWorkspace","Complete")
print_to_config(setup,"CopyWorkspace",True)
print_to_config(setup,"StreamCount",stream_count)
print_to_config(setup,"JobConfig_1",job_config)
return (stream_count,job_config)
#Creates workspace for each processor
def ScratchWorkspace(setup, stream_count, job_config, proc):
main = setup['main']
scratch = setup['scratch']
final= setup['final']
originalgdb= setup['originalgdb']
xs_original= setup['xs_original']
streams_original= setup['streams_original']
flood_original= setup['flood_original']
finalgdb= setup['finalgdb']
xs_final= setup['xs_final']
streams_final= setup['streams_final']
flood_final= setup['flood_final']
configfile = setup['configfile']
sr = setup['sr']
projectname = setup['Projectname']
wsel_field = setup['wsel_field']
station_field = setup['station_field']
rid_field = setup['rid_field']
backwater = setup['backwater']
multi = setup['multiproc']
modelbuilder = setup['modelbuilder']
flood_boundary =setup['flood_boundary']
if stream_count < proc:
proc = stream_count
if multi == True:
for p in range(proc):
i = p+1
print("Creating workspace for processor "+str(i))
scratchoriginal = scratch
scratchproc = os.path.join(scratchoriginal,"proc"+str(i))
scratchgdb = os.path.join(scratchproc,"Scratch.gdb")
finalgdb = os.path.join(main,"Final.gdb")
tablefolder = os.path.join(scratchproc,"Tables")
output_workspace = os.path.join(main,"Final.gdb\\")
raster_catalog = os.path.join(finalgdb,projectname)
streams_dataset = os.path.join(scratchgdb,'streams')
streams_intersect_dataset = os.path.join(scratchgdb,'streams_intersect')
xs_intersect_dataset = os.path.join(scratchgdb,'xs_intersect')
vertices_dataset = os.path.join(scratchgdb,'vertices')
routes_dataset = os.path.join(scratchgdb,'routes')
xs_dataset = os.path.join(scratchgdb,'xs')
flood_dataset = os.path.join(scratchgdb,'flood')
streams_zm = os.path.join(scratchgdb,'streams_zm')
tin_folder = os.path.join(scratchproc,"Tins")
if not os.path.exists(scratchproc):
os.makedirs(scratchproc)
if not os.path.exists(tablefolder):
os.makedirs(tablefolder)
if not os.path.exists(tin_folder):
os.makedirs(tin_folder)
if not os.path.exists(scratchgdb):
arcpy.CreateFileGDB_management(scratchproc, "Scratch.gdb")
if not os.path.exists(finalgdb):
arcpy.CreateFileGDB_management(main, "Final.gdb")
if not arcpy.Exists(streams_dataset):
arcpy.CreateFeatureDataset_management(scratchgdb, "streams", sr)
if not arcpy.Exists(streams_intersect_dataset):
arcpy.CreateFeatureDataset_management(scratchgdb, "streams_intersect", sr)
if not arcpy.Exists(xs_intersect_dataset):
arcpy.CreateFeatureDataset_management(scratchgdb, "xs_intersect", sr)
if not arcpy.Exists(vertices_dataset):
arcpy.CreateFeatureDataset_management(scratchgdb, "vertices", sr)
if not arcpy.Exists(routes_dataset):
arcpy.CreateFeatureDataset_management(scratchgdb, "routes", sr)
if not arcpy.Exists(xs_dataset):
arcpy.CreateFeatureDataset_management(scratchgdb, "xs", sr)
if not arcpy.Exists(flood_dataset):
arcpy.CreateFeatureDataset_management(scratchgdb, "flood", sr)
if not arcpy.Exists(streams_zm):
arcpy.CreateFeatureDataset_management(scratchgdb, "streams_zm", sr)
if not arcpy.Exists(raster_catalog):
arcpy.CreateRasterCatalog_management(finalgdb, projectname, arcpy.SpatialReference(sr))
else:
arcpy.DeleteRasterCatalogItems_management(raster_catalog)
job_config['config'].append({'flood_boundary':flood_boundary,'modelbuilder':modelbuilder,'multiproc':multi,
'backwater': backwater,'rid_field': rid_field,
'finalgdb': finalgdb,'streams_final': streams_final,
'flood_final':flood_final,'xs_final':xs_final,
'wsel_field': wsel_field, 'station_field': station_field,
'table_folder':tablefolder,'tin_folder':tin_folder,
'configfile': configfile,'streams_zm':streams_zm,
'scratch': scratchproc,'sr': sr,
'originalgdb': originalgdb, 'scratchgdb':scratchgdb,
'finalgdb':finalgdb,'output_workspace':output_workspace,
'raster_catalog':raster_catalog,'streams_dataset':streams_dataset,
'streams_intersect_dataset':streams_intersect_dataset,'xs_intersect_dataset':xs_intersect_dataset,
'vertices_dataset':vertices_dataset,'routes_dataset':routes_dataset,
'xs_dataset':xs_dataset,'streams_original':streams_original,
'xs_original':xs_original,'flood_original':flood_original,
'flood_dataset':flood_dataset})
else:
scratchgdb = os.path.join(scratch,"Scratch.gdb")
finalgdb = os.path.join(main,"Final.gdb")
tablefolder = os.path.join(scratch,"Tables")
output_workspace = os.path.join(main,"Final.gdb\\")
raster_catalog = os.path.join(finalgdb,projectname)
streams_dataset = os.path.join(scratchgdb,'streams')
streams_intersect_dataset = os.path.join(scratchgdb,'streams_intersect')
xs_intersect_dataset = os.path.join(scratchgdb,'xs_intersect')
vertices_dataset = os.path.join(scratchgdb,'vertices')
routes_dataset = os.path.join(scratchgdb,'routes')
xs_dataset = os.path.join(scratchgdb,'xs')
flood_dataset = os.path.join(scratchgdb,'flood')
streams_zm = os.path.join(scratchgdb,'streams_zm')
tin_folder = os.path.join(scratch,"Tins")
if not os.path.exists(tin_folder):
os.makedirs(tin_folder)
if not os.path.exists(scratchgdb):
arcpy.CreateFileGDB_management(scratch, "Scratch.gdb")
if not os.path.exists(finalgdb):
arcpy.CreateFileGDB_management(main, "Final.gdb")
if not os.path.exists(tablefolder):
os.makedirs(tablefolder)
if not arcpy.Exists(streams_dataset):
arcpy.CreateFeatureDataset_management(scratchgdb, "streams", sr)
if not arcpy.Exists(streams_intersect_dataset):
arcpy.CreateFeatureDataset_management(scratchgdb, "streams_intersect", sr)
if not arcpy.Exists(xs_intersect_dataset):
arcpy.CreateFeatureDataset_management(scratchgdb, "xs_intersect", sr)
if not arcpy.Exists(vertices_dataset):
arcpy.CreateFeatureDataset_management(scratchgdb, "vertices", sr)
if not arcpy.Exists(routes_dataset):
arcpy.CreateFeatureDataset_management(scratchgdb, "routes", sr)
if not arcpy.Exists(xs_dataset):
arcpy.CreateFeatureDataset_management(scratchgdb, "xs", sr)
if not arcpy.Exists(flood_dataset):
arcpy.CreateFeatureDataset_management(scratchgdb, "flood", sr)
if not arcpy.Exists(streams_zm):
arcpy.CreateFeatureDataset_management(scratchgdb, "streams_zm", sr)
if not os.path.exists(raster_catalog):
arcpy.CreateRasterCatalog_management(finalgdb, projectname,arcpy.SpatialReference(sr))
else:
arcpy.DeleteRasterCatalogItems_management(raster_catalog)
job_config['config'].append({'flood_boundary':flood_boundary,
'modelbuilder':modelbuilder,'multiproc':multi,
'backwater': backwater,'rid_field': rid_field,
'finalgdb': finalgdb,'streams_final': streams_final,
'flood_final':flood_final,'xs_final':xs_final,
'wsel_field': wsel_field, 'station_field': station_field,
'table_folder':tablefolder,'tin_folder':tin_folder,
'configfile': configfile,'streams_zm':streams_zm,
'scratch':scratch,'sr':sr,
'originalgdb': originalgdb,'scratchgdb':scratchgdb,
'finalgdb':finalgdb,'output_workspace':output_workspace,
'raster_catalog':raster_catalog,'streams_dataset':streams_dataset,
'streams_intersect_dataset':streams_intersect_dataset,'xs_intersect_dataset':xs_intersect_dataset,
'vertices_dataset':vertices_dataset,'routes_dataset':routes_dataset,
'xs_dataset':xs_dataset,'streams_original':streams_original,
'xs_original':xs_original,'flood_original':flood_original,
'flood_dataset':flood_dataset})
print_to_log(setup,"Proc",proc)
print_to_config(setup,"Proc",proc)
print_to_config(setup,"JobConfig",job_config)
print_to_log(setup,"ScratchWorkspace","Complete")
print_to_config(setup,"ScratchWorkspace",True)
return (proc, job_config)
def WSEL_XSCheck(streamJobs):
config=streamJobs['config']
stream_names = streamJobs['stream_names']
with WSEL_XS_Check(config,stream_names) as wsel_XS_Check:
result=wsel_XS_Check.processStream()
return result
def WSEL_StreamSetup(streamJobs):
config=streamJobs['config']
stream_names = streamJobs['stream_names']
print(stream_names)
with WSEL_Stream_Setup(config,stream_names) as wsel_StreamSetup:
result=wsel_StreamSetup.processStream()
return result
def WSEL_IntersectJob(streamJobs):
config=streamJobs['config']
stream_names = streamJobs['stream_names']
with WSEL_Intersects(config) as wsel_Intersects:
result=wsel_Intersects.processStream()
return result
def WSEL_IntersectsClean(streamJobs):
config=streamJobs['config']
with WSEL_Intersects_Clean(config) as wsel_Intersects_Clean:
result=wsel_Intersects_Clean.processStream()
return result
def WSEL_step1(streamJobs):
config=streamJobs['config']
stream_names = streamJobs['stream_names']
with WSEL_Step_1(config,stream_names) as wsel_Step_1:
result=wsel_Step_1.processStream()
return result
def WSEL_step2(streamJobs):
config=streamJobs['config']
stream_names = streamJobs['stream_names']
with WSEL_Step_2(config, stream_names) as wsel_Step_2:
wsel_Step_2.processStream()
return
def WSEL_step3(streamJobs):
config=streamJobs['config']
stream_names = streamJobs['stream_names']
with WSEL_Step_3(config, stream_names) as wsel_Step_3:
result=wsel_Step_3.processStream()
return result
def WSEL_step4(streamJobs):
config=streamJobs['config']
stream_names = streamJobs['stream_names']
with WSEL_Step_4(config, stream_names) as wsel_Step_4:
wsel_Step_4.processStream()
return
def WSEL_step5(streamJobs):
config=streamJobs['config']
stream_names = streamJobs['stream_names']
with WSEL_Step_5(config, stream_names) as wsel_Step_5:
wsel_Step_5.processStream()
return
def remove_dup(seq):
# Order preserving
return list(_remove_dup(seq))
def _remove_dup(seq):
seen = set()
for x in seq:
if x in seen:
continue
seen.add(x)
yield x
def merge(merge_stream,all_intersects,main_list,name):
new_merge={name:[]}
for stream in main_list:
if all_intersects.has_key(stream):
p=len(new_merge[name])
new_merge[name].append({stream:[]})
for trib in all_intersects[stream]:
if all_intersects.has_key(trib):
new_merge[name][p][stream].append({trib:all_intersects[trib]})
i=len(new_merge[name][p][stream])
merge(new_merge[name][p][stream][i-1],all_intersects,all_intersects[trib],trib)
else:
new_merge[name][p][stream].append(trib)
else:
new_merge[name].append(stream)
merge_stream.update(new_merge)
return merge_stream
def flatten_stream(stream_dict, stream_list):
new_Streamlist=stream_list
if isinstance(stream_dict, dict):
for stream in stream_dict.keys():
new_Streamlist.append(stream)
for values in stream_dict.values():
for i in range(0,len(values)):
if isinstance(values[i], dict):
flatten_stream(values[i],new_Streamlist)
else:
new_Streamlist.append(values[i])
return stream_list
#creates a list of streams orgininating from the main stream
def stream_order(setup,streamJobs):
print("Creating list of streams for processing order")
stream_dict = {}
stream_initdict ={}
intersectList=[]
strmList=[]
main=setup['main_stream']
scratchgdb_loc = streamJobs[0]['config']['scratchgdb']
intersect_table = scratchgdb_loc+'\\streams_intersect_all_1'
strmList_raw=[r for r in arcpy.da.SearchCursor(intersect_table, ['Route_ID','Intersects','strm_length'])]
for r in strmList_raw:
strmList.append([r[0],r[1]])
intersectList.append(r[1])
intersectList.insert(0,main)
intersectList_uniq=remove_dup(intersectList)
for strm in intersectList_uniq:
stream_initdict[strm] =[]
for strm in strmList:
stream_initdict[strm[1]].append(strm[0])
main_strm =stream_initdict.pop(main)
stream_dict=merge({main: main_strm},stream_initdict,main_strm, main)
stream_order = flatten_stream(stream_dict, list([]))
print_to_config(setup,"stream_list",stream_order)
return stream_order
#returns config file for specific stream name
def getConfig(stream,streamJobs,procs):
for i in range(0, procs):
if stream in streamJobs[i]['stream_names']:
return i
#cleans up and moves stream data to final gdb
def finalize_data(setup,streamJobs,proc,multi):
multiproc = multi
xs_final=setup['xs_final']
finalgdb = setup['finalgdb']
streams_final = setup['streams_final']
flood_final = setup['flood_final']
wsel_field=setup['wsel_field']
print("Moving Data")
if multiproc == True:
for p in range(proc):
stream_loc = streamJobs[p]['config']['routes_dataset']
xs_loc = streamJobs[p]['config']['xs_dataset']
bound_loc = streamJobs[p]['config']['flood_dataset']
env.workspace = stream_loc
env.overwriteOutput = True
streams = arcpy.ListFeatureClasses()
for name in streams:
arcpy.CopyFeatures_management(name,streams_final+'\\'+name+'_'+wsel_field)
env.workspace = xs_loc
env.overwriteOutput = True
xs = arcpy.ListFeatureClasses()
for name in xs:
arcpy.CopyFeatures_management(name,xs_final+'\\'+name+'_'+wsel_field)
env.workspace = bound_loc
env.overwriteOutput = True
boundary = arcpy.ListFeatureClasses()
for name in boundary:
arcpy.CopyFeatures_management(name,flood_final+'\\'+name+'_'+wsel_field)
stream_loc = streams_final
env.workspace = stream_loc
env.overwriteOutput = True
streams = arcpy.ListFeatureClasses()
streams_all = arcpy.Merge_management(streams, finalgdb+"\\streams_all"+'_'+wsel_field)
xs_loc = xs_final
env.workspace = xs_loc
env.overwriteOutput = True
xs = arcpy.ListFeatureClasses()
xs_all = arcpy.Merge_management(xs, finalgdb+"\\xs_all"+'_'+wsel_field)
else:
stream_loc = streamJobs[0]['config']['routes_dataset']
xs_loc = streamJobs[0]['config']['xs_dataset']
env.workspace = stream_loc
streams = arcpy.ListFeatureClasses()
for name in streams:
arcpy.CopyFeatures_management(name,streams_final+'\\'+name+'_'+wsel_field)
env.workspace = xs_loc
xs = arcpy.ListFeatureClasses()
for name in xs:
arcpy.CopyFeatures_management(name,xs_final+'\\'+name+'_'+wsel_field)
stream_loc = streams_final
env.workspace = stream_loc
env.overwriteOutput = True
streams = arcpy.ListFeatureClasses()
streams_all = arcpy.Merge_management(streams, finalgdb+"\\streams_all_"+wsel_field)
xs_loc = xs_final
env.workspace = xs_loc
env.overwriteOutput = True
xs = arcpy.ListFeatureClasses()
xs_all = arcpy.Merge_management(xs,finalgdb+"\\xs_all"+'_'+wsel_field)
xs_fields =['Route_ID','XS_Station','WSEL','WSEL_REG','Backwater']
fields = [f.name for f in arcpy.ListFields(xs_all) if not f.required and f.name not in xs_fields ]
arcpy.DeleteField_management(xs_all, fields)
stream_fields =['Route_ID']
fields = [f.name for f in arcpy.ListFields(streams_all) if not f.required and f.name not in stream_fields ]
arcpy.DeleteField_management(streams_all, fields)
print_to_config(setup,"finalize_data",True)
print("Data moved to Final Geodatabase")
return
#Seperates streams by the number of processors and attaches the correct config file to each
def StreamJobs(setup,config,procs):
multi = setup['multiproc']
streamarr=config['stream_names']
if(len(streamarr)<=procs):
p=1
else:
p=int(len(streamarr)/procs)
jobsList=[]
streamSet=[]
t = 0
if multi == True:
for i in streamarr:
if(len(streamSet)+2<=p):
streamSet.append(i)
elif(len(jobsList)<procs):
streamSet.append(i)
configSet={'stream_names':streamSet,'config':config['config'][t]}
t=t+1
jobsList.append(configSet)
streamSet=[]
else:
streamSet.append(i)
j=0
if(len(streamSet)>0): #distribute the remaining streams across the existing jobs
for i in range(0,len(streamSet)):
if(j<len(jobsList)):
jobsList[j]['stream_names'].append(streamSet[i])
j=j+1
else:
j=0
else:
streamSet = streamarr
configSet={'stream_names':streamSet,'config':config['config'][0]}
jobsList.append(configSet)
print_to_config(setup,"StreamJobs",jobsList)
return jobsList
#merges all the streams from each individual workspace and the overall workspace
def MergeStreams(setup,streamJobs, proc, run,multi):
print("Merging Streams")
multiproc = multi
stream_list =[]
if multiproc == True:
for p in range(proc):
if run == 1:
stream_loc = streamJobs[p]['config']['streams_dataset']
else:
stream_loc = streamJobs[p]['config']['routes_dataset']
scratchgdb_loc = streamJobs[p]['config']['scratchgdb']
env.workspace = stream_loc
env.overwriteOutput = True
streams = arcpy.ListFeatureClasses()
if len(streams)>0:
env.workspace = scratchgdb_loc
env.overwriteOutput = True
local_streams = arcpy.Merge_management(streams, "local_streams_all")
stream_list.append(scratchgdb_loc+'\\local_streams_all')
for p in range(proc):
scratchgdb_loc = streamJobs[p]['config']['scratchgdb']
env.workspace = scratchgdb_loc
env.overwriteOutput = True
comb_streams = arcpy.Merge_management(stream_list, "streams_all")
else:
if run == 1:
stream_loc = streamJobs[0]['config']['streams_dataset']
else:
stream_loc = streamJobs[0]['config']['routes_dataset']
scratchgdb_loc = streamJobs[0]['config']['scratchgdb']
env.workspace = stream_loc
env.overwriteOutput = True
streams = arcpy.ListFeatureClasses()
env.workspace = scratchgdb_loc
env.overwriteOutput = True
comb_streams = arcpy.Merge_management(streams, "streams_all")
if run!=2:
print_to_log(setup,"MergeStreams_"+str(run),"Complete")
print_to_config(setup,"MergeStreams_"+str(run),True)
print("Merge Streams completed")
return
#does the same as mergestreams but for intersects file
def MergeIntersects(setup,streamJobs,proc,run,multi):
stream_intersect =[]
multiproc= multi
print("Merging Stream Intersects")
if multiproc == True:
for p in range(proc):
stream_loc =streamJobs[p]['config']['streams_intersect_dataset']
scratchgdb_loc = streamJobs[p]['config']['scratchgdb']
env.workspace = stream_loc
streams = arcpy.ListFeatureClasses()
if len(streams)>0:
env.workspace = scratchgdb_loc
local_streams = arcpy.Merge_management(streams, "local_streams_intersect_all_"+str(run))
stream_intersect.append(scratchgdb_loc+'\\local_streams_intersect_all_'+str(run))
for p in range(proc):
scratchgdb_loc = streamJobs[p]['config']['scratchgdb']
env.workspace = scratchgdb_loc
env.overwriteOutput = True
comb_intersect = arcpy.Merge_management(stream_intersect, scratchgdb_loc+"\\streams_intersect_all_"+str(run))
else:
stream_loc = streamJobs[0]['config']['streams_intersect_dataset']
scratchgdb_loc = streamJobs[0]['config']['scratchgdb']
env.workspace = stream_loc
streams = arcpy.ListFeatureClasses()
comb_intersect = arcpy.Merge_management(streams, scratchgdb_loc+"\\streams_intersect_all_"+str(run))
env.workspace = scratchgdb_loc
if run!=2:
print_to_log(setup,"MergeIntersects_"+str(run),"Complete")
print_to_config(setup,"MergeIntersects_"+str(run),True)
print("Merge Intersects completed")
return
def comb_raster(setup,streamJobs):
final = setup['final']
projectname = setup['Projectname']
wsel_field=setup['wsel_field']
print("Combining rasters")
raster_loc = streamJobs[0]['config']['output_workspace']
raster_cat = streamJobs[0]['config']['raster_catalog']
arcpy.WorkspaceToRasterCatalog_management(raster_loc, raster_cat,"INCLUDE_SUBDIRECTORIES","PROJECT_ONFLY")
arcpy.RasterCatalogToRasterDataset_management(raster_cat,os.path.join(final,projectname+'_'+wsel_field+".tif"),"",
"MAXIMUM", "FIRST","", "", "32_BIT_FLOAT")
print_to_config(setup,"comb_raster",True)
print("All water surface elevations rasters have been created")
return
def XSCheck(setup,proc,streamJobs):
warning ={}
error = 0
multi = streamJobs[0]['config']['multiproc']
if multi == True:
print("Beginning XS Check using multiprocesser module")
if proc <= 1:
for job in streamJobs:
result = WSEL_XSCheck(job)
print(len(result))
if len(result)> 0:
print(result[0])
error = error +1
warning.update(result[0])
else:
pool=Pool(processes=proc)
result = pool.map(WSEL_XSCheck,streamJobs)
pool.close()
pool.join()
for i in result[0]:
if i != None:
error = error +1
warning.update(i)
else:
print("Beginning XS Check without multiprocesser module")
result=WSEL_XSCheck(streamJobs[0])
if result != None:
error = error +1
print(result)
warning.update(result[0])
print("XS have been checked")
if error >0:
warning_string=json.dumps(warning)
print_to_log(setup,"XSWarnings",warning_string)
print_to_log(setup,"XSCheck","Complete")
print_to_config(setup,"XSCheck",True)
return
def StreamSetup(setup,proc,streamJobs):
multi = streamJobs[0]['config']['multiproc']
if multi == True:
print("Beginning Stream Setup using multiprocesser module")
if proc <= 3: #No point in doing multi proc if proc is small
for job in streamJobs:
result = WSEL_StreamSetup(job)
else:
pool=Pool(processes=proc)
result = pool.map(WSEL_StreamSetup,streamJobs)
pool.close()
pool.join()
else:
print("Beginning Stream Setup without multiprocesser module")
WSEL_StreamSetup(streamJobs[0])
print("Stream Setup completed")
print_to_log(setup,"Stream Setup","Complete")
print_to_config(setup,"StreamSetup",True)
return
def IntersectJob(setup,proc,streamJobs):
multi = streamJobs[0]['config']['multiproc']
if multi == True:
print("Beginning Intersects using multiprocesser module")
#for job in streamJobs:
#result = WSEL_StreamSetup(job)
pool=Pool(processes=proc)
result = pool.map(WSEL_IntersectJob,streamJobs)
pool.close()
pool.terminate()
pool.join()
else:
print("Beginning Intersects without multiprocesser module")
WSEL_IntersectJob(streamJobs[0])
print("Stream Intersects completed")
print_to_log(setup,"Intersects","Complete")
print_to_config(setup,"Intersects",True)
return
def IntersectsClean(setup,proc,streamJobs):
multi = streamJobs[0]['config']['multiproc']
if multi == True:
print("Beginning Intersects Clean using multiprocesser module")
#for job in streamJobs:
#result = WSEL_IntersectsClean(job)
pool=Pool(processes=proc)
result = pool.map(WSEL_IntersectsClean,streamJobs)
pool.close()
pool.terminate()
pool.join()
else:
print("Beginning Intersects Clean without multiprocesser module")
WSEL_IntersectsClean(streamJobs[0])
print("Stream Intersects Clean completed")
print_to_log(setup,"IntersectsClean","Complete")
print_to_config(setup,"IntersectsClean",True)
return
def Intersects_delete(setup,streamJobs,proc):
stream_intersect =[]
multi = streamJobs[0]['config']['multiproc']
print("Deleting Initial Stream Intersects")
if multi == True:
for p in range(proc):
stream_loc = streamJobs[p]['config']['streams_intersect_dataset']
scratchgdb_loc = streamJobs[p]['config']['scratchgdb']
env.workspace = stream_loc
streams = arcpy.ListFeatureClasses()
env.workspace = scratchgdb_loc
for fc in streams:
arcpy.Delete_management(fc)
else:
stream_loc = streamJobs[0]['config']['streams_intersect_dataset']
scratchgdb_loc = streamJobs[0]['config']['scratchgdb']
env.workspace = stream_loc
streams = arcpy.ListFeatureClasses()
env.workspace = scratchgdb_loc
for fc in streams:
arcpy.Delete_management(fc)
print_to_log(setup,"IntersectsDelete","Complete")
print_to_config(setup,"IntersectsDelete",True)
print("Initial Intersects deletion completed")
return
def Step1(setup,proc,streamJobs):
multi = streamJobs[0]['config']['multiproc']
if multi == True:
print("Beginning Step 1")
#for job in streamJobs:
#result = WSEL_step1(job)
pool=Pool(processes=proc)
result = pool.map(WSEL_step1,streamJobs)
pool.close()
pool.terminate()
pool.join()
else:
print("Beginning Step 1")
WSEL_step1(streamJobs[0])
print("Step 1 completed")
print("Streams have been configured")
return
def Step2(setup,proc,streamJobs):
multi = streamJobs[0]['config']['multiproc']
if multi == True:
print("Beginning Step 2")
#for job in streamJobs:
#result = WSEL_step2(job)
pool=Pool(processes=proc)
result = pool.map(WSEL_step2,streamJobs)
pool.close()
pool.join()
else:
print("Beginning Step 2")
WSEL_step2(streamJobs[0])
print("Step 2 completed")
return
def Step3(setup,proc,streamJobs):
multi = streamJobs[0]['config']['multiproc']
error = 0
warning ={}
if multi == True:
print("Beginning Step 3")
#for job in streamJobs:
#result = WSEL_step3(job)
#if result != None:
#warning.update(result[0])
pool=Pool(processes=proc)
result = pool.map(WSEL_step3,streamJobs)
pool.close()
pool.join()
if len(result)> 0:
error = error +1
warning.update(result)
else:
print("Beginning Step 3")
result=WSEL_step3(streamJobs[0])
if len(result)>1:
error = error +1
warning.update(result)
if error >0:
warning_string=json.dumps(warning)
print_to_log(setup,"Stream Intersect Warning",warning_string)
print(warning)
print("Step 3 completed")
return
def Step4(setup,proc,streamJobs, multiproc):#still does not like multi processing
multi = multiproc
if multi == True:
print("Beginning Step 4")
for job in streamJobs:
result = WSEL_step4(job)
#pool=Pool(processes=proc)
#result = pool.map(WSEL_step4,streamJobs)
#pool.close()
#pool.terminate()
#pool.join()
else:
print("Beginning Step 4")
WSEL_step4(streamJobs[0])
print("Step 4 completed")
if setup['backwater']!= True:
print_to_log(setup,"Step 4","Complete")
print_to_config(setup,"Step4",True)
return
def Step5(setup,proc,streamJobs,multi):
#For some reason tin creation will not work with multiprocessing
multiproc = setup['multiproc']
if multiproc == True:
print("Processing Streams with Step 5 module")
for job in streamJobs:
result = WSEL_step5(job)
#pool=Pool(processes=proc)
#result = pool.map(WSEL_step5,streamJobs)
#pool.close()
#pool.join()
else:
print("Processing Streams with Step 5 module")
WSEL_step5(streamJobs[0])
print("Step 5 completed")
if setup['backwater']!= True:
print_to_log(setup,"Step 5","Complete")
print_to_config(setup,"Step5",True)
return
def main(config):
setup = config['Setup']
logging.basicConfig(level=logging.DEBUG, filename=setup['logfile'], format='%(asctime)s %(message)s') #Set logging level and location
try:
print_to_log(setup,"Start Time", time.strftime("%c"))
multi = setup['multiproc']
print_to_log(setup,"Multiproc",multi)
processors = setup['Proc']
# The next list of checks are done to insure that certain variables are in the config file.
# A config process should be added in order to start and stop from a certain step if needed.
if 'Proc' not in config:
config['Proc'] = processors
else:
proc = config['Proc']
if 'StreamCount' not in config:
stream_count = 0
else:
stream_count = config['StreamCount']
if 'JobConfig_1' in config:
job_config_1 = config['JobConfig_1']
else:
config['JobConfig_1'] = ''
if 'JobConfig' in config:
job_config = config['JobConfig']
else:
config['JobConfig'] = ''
if 'StreamJobs' in config:
streamJobs = config['StreamJobs']
else:
config['StreamJobs'] = False
if 'OriginalWorkspace' not in config:
config['OriginalWorkspace'] = False
if 'CopyWorkspace' not in config:
config['CopyWorkspace'] = False
if 'ScratchWorkspace' not in config:
config['ScratchWorkspace'] = False
if 'StreamSetup' not in config:
config['StreamSetup'] = False
if 'Intersects' not in config:
config['Intersects'] = False
if 'IntersectsClean' not in config:
config['IntersectsClean'] = False
if 'Step4' not in config:
config['Step4'] = False
if 'Step5' not in config:
config['Step5'] = False
if 'XSCheck' not in config:
config['XSCheck'] = False
if 'MergeStreams_1' not in config:
config['MergeStreams_1'] = False
if 'MergeIntersects_1' not in config:
config['MergeIntersects_1'] = False
if 'IntersectsDelete' not in config:
config['IntersectsDelete'] = False
if 'finalize_data' not in config: