-
Notifications
You must be signed in to change notification settings - Fork 2
/
gSSURGO_ExportRasters.py
1746 lines (1348 loc) · 77.8 KB
/
gSSURGO_ExportRasters.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
# gSSURGO_ExportRasters.py
#
# Steve Peaslee, National Soil Survey Center
# 2019-10-07
#
# Purpose: Batch mode conversion of multiple gSSURGO soil maps into raster (TIFF or FGDB raster).
#
# Looking at option to automatically identify a soil map layer with the
# associated sdvattribute.resultcolumnname record in the correct geodatabase.
#
# Examples of qualified fieldnames for ratings:
# SDV_pHwater_DCP_0to5.pHwater_DCP
# SDV_pHwater_DCP_5to15.pHwater_DCP
# SDV_NCCPI_WTA.NCCPI_WTA
# SDV_KfactWS_DCD_0to1.KFACTWS_DCD
# SDV_EcoSiteNm_DCD_NRCS_Rangeland_Site.ECOSITENM_DCD
#
# Will need to incorporate some code from Create Soil Map script. This may be a burden for
# map legends that do not have values or breaks stored in xml.
# dLayerDefinition['drawingInfo']['renderer']
#
#
## ===================================================================================
class MyError(Exception):
pass
## ===================================================================================
def errorMsg():
try:
tb = sys.exc_info()[2]
tbinfo = traceback.format_tb(tb)[0]
theMsg = tbinfo + " \n" + str(sys.exc_type)+ ": " + str(sys.exc_value) + " \n"
PrintMsg(theMsg, 2)
except:
PrintMsg("Unhandled error in errorMsg method", 2)
pass
## ===================================================================================
def PrintMsg(msg, severity=0):
# Adds tool message to the geoprocessor
#
#Split the message on \n first, so that if it's multiple lines, a GPMessage will be added for each line
try:
for string in msg.split('\n'):
#Add a geoprocessing message (in case this is run as a tool)
if severity == 0:
arcpy.AddMessage(string)
elif severity == 1:
arcpy.AddWarning(string)
elif severity == 2:
arcpy.AddMessage(" ")
arcpy.AddError(string)
except:
pass
## ===================================================================================
def Number_Format(num, places=0, bCommas=True):
try:
# Format a number according to locality and given places
locale.setlocale(locale.LC_ALL, "")
if bCommas:
theNumber = locale.format("%.*f", (places, num), True)
else:
theNumber = locale.format("%.*f", (places, num), False)
return theNumber
except:
errorMsg()
return "???"
## ===================================================================================
def get_random_color(pastel_factor=0.5):
# Part of generate_random_color
try:
newColor = [int(255 *(x + pastel_factor)/(1.0 + pastel_factor)) for x in [random.uniform(0,1.0) for i in [1,2,3]]]
return newColor
except:
errorMsg()
return [0,0,0]
## ===================================================================================
def color_distance(c1,c2):
# Part of generate_random_color
return sum([abs(x[0] - x[1]) for x in zip(c1,c2)])
## ===================================================================================
def generate_new_color(existing_colors, pastel_factor=0.5):
# Part of generate_random_color
try:
#PrintMsg(" \nExisting colors: " + str(existing_colors) + "; PF: " + str(pastel_factor), 1)
max_distance = None
best_color = None
for i in range(0,100):
color = get_random_color(pastel_factor)
if not color in existing_colors:
color.append(255) # add transparency level
return color
best_distance = min([color_distance(color,c) for c in existing_colors])
if not max_distance or best_distance > max_distance:
max_distance = best_distance
best_color = color
best_color.append(255)
return best_color
except:
errorMsg()
return None
## ===================================================================================
def rand_rgb_colors(num):
# Generate a random list of rgb values
# 2nd argument in generate_new_colors is the pastel factor. 0 to 1. Higher value -> more pastel.
try:
colors = []
# PrintMsg(" \nGenerating " + str(num - 1) + " new colors", 1)
for i in range(0, num):
newColor = generate_new_color(colors, 0.1)
colors.append(newColor)
# PrintMsg(" \nColors: " + str(colors), 1)
return colors
except:
errorMsg()
return []
## ===================================================================================
def GetMapLegend(dAtts, bFuzzy):
# From gSSURGO_CreateSoilMap script...
#
# Get map legend values and order from maplegendxml column in sdvattribute table
# Return dLegend dictionary containing contents of XML.
# Problem with Farmland Classification. It is defined as a choice, but
try:
#bVerbose = True # This function seems to work well, but prints a lot of messages.
global dLegend
dLegend = dict()
dLabels = dict()
#if bFuzzy and not dAtts["attributename"].startswith("National Commodity Crop Productivity Index"):
# # Skip map legend because the fuzzy values will not match the XML legend.
# return dict()
arcpy.SetProgressorLabel("Getting map legend information")
if bVerbose:
PrintMsg(" \nCurrent function : " + sys._getframe().f_code.co_name, 1)
xmlString = dAtts["maplegendxml"]
#if bVerbose:
# PrintMsg(" \nxmlString: " + xmlString + " \n ", 1)
# Convert XML to tree format
tree = ET.fromstring(xmlString)
# Iterate through XML tree, finding required elements...
i = 0
dColors = dict()
legendList = list()
legendKey = ""
legendType = ""
legendName = ""
# Notes: dictionary items will vary according to legend type
# Looks like order should be dictionary key for at least the labels section
#
for rec in tree.iter():
if rec.tag == "Map_Legend":
dLegend["maplegendkey"] = rec.attrib["maplegendkey"]
if rec.tag == "ColorRampType":
dLegend["type"] = rec.attrib["type"]
dLegend["name"] = rec.attrib["name"]
if rec.attrib["name"] == "Progressive":
dLegend["count"] = int(rec.attrib["count"])
if "name" in dLegend and dLegend["name"] == "Progressive":
if rec.tag == "LowerColor":
# 'part' is zero-based and related to count
part = int(rec.attrib["part"])
red = int(rec.attrib["red"])
green = int(rec.attrib["green"])
blue = int(rec.attrib["blue"])
#PrintMsg("Lower Color part #" + str(part) + ": " + str(red) + ", " + str(green) + ", " + str(blue), 1)
if rec.tag in dLegend:
dLegend[rec.tag][part] = (red, green, blue)
else:
dLegend[rec.tag] = dict()
dLegend[rec.tag][part] = (red, green, blue)
if rec.tag == "UpperColor":
part = int(rec.attrib["part"])
red = int(rec.attrib["red"])
green = int(rec.attrib["green"])
blue = int(rec.attrib["blue"])
#PrintMsg("Upper Color part #" + str(part) + ": " + str(red) + ", " + str(green) + ", " + str(blue), 1)
if rec.tag in dLegend:
dLegend[rec.tag][part] = (red, green, blue)
else:
dLegend[rec.tag] = dict()
dLegend[rec.tag][part] = (red, green, blue)
if rec.tag == "Labels":
order = int(rec.attrib["order"])
if dSDV["attributelogicaldatatype"].lower() == "integer":
# get dictionary values and convert values to integer
try:
val = int(rec.attrib["value"])
label = rec.attrib["label"]
rec.attrib["value"] = val
dLabels[order] = rec.attrib
except:
upperVal = int(rec.attrib["upper_value"])
lowerVal = int(rec.attrib["lower_value"])
rec.attrib["upper_value"] = upperVal
rec.attrib["lower_value"] = lowerVal
dLabels[order] = rec.attrib
elif dSDV["attributelogicaldatatype"].lower() == "float" and not bFuzzy:
# get dictionary values and convert values to float
try:
val = float(rec.attrib["value"])
label = rec.attrib["label"]
rec.attrib["value"] = val
dLabels[order] = rec.attrib
except:
upperVal = float(rec.attrib["upper_value"])
lowerVal = float(rec.attrib["lower_value"])
rec.attrib["upper_value"] = upperVal
rec.attrib["lower_value"] = lowerVal
dLabels[order] = rec.attrib
else:
dLabels[order] = rec.attrib # for each label, save dictionary of values
if rec.tag == "Color":
# Save RGB Colors for each legend item
# get dictionary values and convert values to integer
red = int(rec.attrib["red"])
green = int(rec.attrib["green"])
blue = int(rec.attrib["blue"])
dColors[order] = rec.attrib
if rec.tag == "Legend_Elements":
try:
dLegend["classes"] = rec.attrib["classes"] # save number of classes (also is a dSDV value)
except:
pass
# Add the labels dictionary to the legend dictionary
dLegend["labels"] = dLabels
dLegend["colors"] = dColors
# Test iteration methods on dLegend
#PrintMsg(" \n" + dAtts["attributename"] + " Legend Key: " + dLegend["maplegendkey"] + ", Type: " + dLegend["type"] + ", Name: " + dLegend["name"] , 1)
if bVerbose:
PrintMsg(" \n" + dAtts["attributename"] + "; MapLegendKey: " + dLegend["maplegendkey"] + ",; Type: " + dLegend["type"] , 1)
for order, vals in dLabels.items():
PrintMsg("\tNew " + str(order) + ": ", 1)
for key, val in vals.items():
PrintMsg("\t\t" + key + ": " + str(val), 1)
try:
r = int(dColors[order]["red"])
g = int(dColors[order]["green"])
b = int(dColors[order]["blue"])
rgb = (r,g,b)
#PrintMsg("\t\tRGB: " + str(rgb), 1)
except:
pass
if bVerbose:
PrintMsg(" \ndLegend: " + str(dLegend), 1)
return dLegend
except MyError, e:
# Example: raise MyError, "This is an error message"
PrintMsg(str(e), 2)
return dict()
except:
errorMsg()
return dict()
## ===================================================================================
def UpdateMetadata(theGDB, target, sdvLayer, newDescription, mapSettings, newCredits, outputRes):
#
# Used for ISO 19139 metadata
# Arguments:
# 0 Y:\Peaslee\DB\gSSURGO_KS.gdb
# 1. ...\gSSURGO_Rasters\SoilRas_NirrCpCls_DCD_30Meter.tif
# 2. Nonirrigated Capability Class DCD
# 3. Description from SDV narrative plus settings used
# 4. 10
#
# Process:
# 1. Read gSSURGO_PropertyRaster.xml (template metadata file for soil property rasters)
# 2. Replace 'XX" keywords with updated information
# 3. Write new file xxImport.xml
# 4. Import xxImport.xml to raster
#
try:
PrintMsg("\tUpdating raster metadata for " + os.path.basename(target) + "...")
arcpy.SetProgressor("default", "Updating raster metadata")
#PrintMsg(" \nFunction arguments: " + theGDB + " \n" + target + " \n" + sdvLayer + " \n" + description + " \n" + str(outputRes), 1)
# Set metadata translator file
dInstall = arcpy.GetInstallInfo()
installPath = dInstall["InstallDir"]
prod = r"Metadata/Translator/ARCGIS2FGDC.xml"
mdTranslator = os.path.join(installPath, prod) # This file is not being used
# Define input and output XML files
# mdImport = os.path.join(env.scratchFolder, "xxImport.xml") # the metadata xml that will provide the updated info
if target.endswith(".tif"):
mdExport = target + ".xml" # not sure if I can overwrite the metadata file for a TIFF. For testing purposes, add 'M' to the name.
else:
mdExport = os.path.join(env.scratchFolder, "xxRasterMetadata.xml")
#raise MyError, "Output metadata file not yet determined for FGDB raster"
xmlPath = os.path.dirname(sys.argv[0])
mdTemplate = os.path.join(xmlPath, "gSSURGO_PropertyRaster.xml") # original template metadata in script directory
# PrintMsg(" \nParsing gSSURGO template metadata file: " + mdTemplate, 1)
#PrintMsg(" \nUsing SurveyInfo: " + str(surveyInfo), 1)
# Get replacement value for the search words
#
stDict = StateNames()
st = os.path.basename(theGDB)[8:-4]
# PrintMsg(" \nParsed '" + st + "' as state from " + os.path.basename(theGDB), 1)
if st in stDict:
# Get state name from the geodatabase
mdState = stDict[st]
else:
# Leave state name blank. In the future it would be nice to include a tile name when appropriate
mdState = ""
# Update metadata file for the geodatabase
#
# Query the output SACATALOG table to get list of surveys that were exported to the gSSURGO
#
saTbl = os.path.join(theGDB, "sacatalog")
expList = list()
with arcpy.da.SearchCursor(saTbl, ("AREASYMBOL", "SAVEREST")) as srcCursor:
for rec in srcCursor:
expList.append(rec[0] + " (" + str(rec[1]).split()[0] + ")")
surveyInfo = ", ".join(expList)
#PrintMsg(" \nUsing this string as a substitute for xxSTATExx: '" + mdState + "'", 1)
# Set date strings for metadata, based upon today's date
#
d = datetime.date.today()
today = str(d.isoformat().replace("-",""))
#PrintMsg(" \nToday replacement string: " + today, 1)
# As of July 2020, switch gSSURGO version format to YYYYMM
fy = d.strftime('%Y%m')
#PrintMsg(" \nFY replacement string: " + str(fy), 1)
# Process gSSURGO_MapunitRaster.xml from script directory
# This xml uses namespaces, so that needs to be accounted for in the parser
# 'xxPROPERTYxx', 'xxRESOLUTIONxx', 'xxSTATExx', 'xxSURVEYSxx', 'xxTODAYxx', 'xxFYxx'
dKeys = dict()
dKeys['xxPROPERTYxx'] = sdvLayer
dKeys['xxRESOLUTIONxx'] = str(int(outputRes)) + "m resolution"
dKeys['xxSTATExx'] = st
dKeys['xxSURVEYSxx'] = surveyInfo
dKeys['xxTODAYxx'] = today
dKeys['xxFYxx'] = fy
dKeys['xxDESCxx'] = newDescription
dKeys['xxPROCESSxx'] = mapSettings
dKeys['xxCREDITSxx'] = newCredits
# gco
tree = ET.parse(mdTemplate)
#root = tree.getroot()
txtElements = tree.findall('.//{http://www.isotc211.org/2005/gco}CharacterString')
for elem in txtElements:
if elem.text.find('xx') >= 0:
for key in dKeys.keys():
if elem.text.find(key) >= 0:
elem.text = elem.text.replace(key, dKeys[key])
# PrintMsg("\t\tReplacing '" + key + "' with '" + dKeys[key] + "'", 1)
# create new xml file which will be imported, thereby updating the table's metadata
# PrintMsg(" \nWriting metadata to intermediate XML file (" + mdImport + ")", 1)
tree.write(mdExport, encoding="utf-8", xml_declaration=None, default_namespace=None, method="xml")
if not target.endswith(".tif"):
arcpy.ImportMetadata_conversion(mdExport, "FROM_ISO_19139", target, "DISABLED") # import ISO metadata for FGDB raster
# import updated metadata to the geodatabase table
# Using three different methods with the same XML file works for ArcGIS 10.1
# delete metadata tool logs
logFolder = os.path.dirname(env.scratchFolder)
#logFile = os.path.basename(mdImport).split(".")[0] + "*"
#currentWS = env.workspace
#env.workspace = logFolder
#logList = arcpy.ListFiles(logFile)
#for lg in logList:
# arcpy.Delete_management(lg)
#env.workspace = currentWS
return True
except MyError, e:
# Example: raise MyError, "This is an error message"
PrintMsg(str(e), 2)
return False
except:
errorMsg()
return False
## ===================================================================================
def StateNames():
# Create dictionary object containing list of state abbreviations and their names that
# will be used to name the file geodatabase.
# For some areas such as Puerto Rico, U.S. Virgin Islands, Pacific Islands Area the
# abbrevation is
# NEED TO UPDATE THIS FUNCTION TO USE THE LAOVERLAP TABLE AREANAME. AREASYMBOL IS STATE ABBREV
try:
stDict = dict()
stDict["Alabama"] = "AL"
stDict["Alaska"] = "AK"
stDict["American Samoa"] = "AS"
stDict["Arizona"] = "AZ"
stDict["Arkansas"] = "AR"
stDict["California"] = "CA"
stDict["Colorado"] = "CO"
stDict["Connecticut"] = "CT"
stDict["District of Columbia"] = "DC"
stDict["Delaware"] = "DE"
stDict["Florida"] = "FL"
stDict["Georgia"] = "GA"
stDict["Territory of Guam"] = "GU"
stDict["Guam"] = "GU"
stDict["Hawaii"] = "HI"
stDict["Idaho"] = "ID"
stDict["Illinois"] = "IL"
stDict["Indiana"] = "IN"
stDict["Iowa"] = "IA"
stDict["Kansas"] = "KS"
stDict["Kentucky"] = "KY"
stDict["Louisiana"] = "LA"
stDict["Maine"] = "ME"
stDict["Northern Mariana Islands"] = "MP"
stDict["Marshall Islands"] = "MH"
stDict["Maryland"] = "MD"
stDict["Massachusetts"] = "MA"
stDict["Michigan"] = "MI"
stDict["Federated States of Micronesia"] ="FM"
stDict["Minnesota"] = "MN"
stDict["Mississippi"] = "MS"
stDict["Missouri"] = "MO"
stDict["Montana"] = "MT"
stDict["Nebraska"] = "NE"
stDict["Nevada"] = "NV"
stDict["New Hampshire"] = "NH"
stDict["New Jersey"] = "NJ"
stDict["New Mexico"] = "NM"
stDict["New York"] = "NY"
stDict["North Carolina"] = "NC"
stDict["North Dakota"] = "ND"
stDict["Ohio"] = "OH"
stDict["Oklahoma"] = "OK"
stDict["Oregon"] = "OR"
stDict["Palau"] = "PW"
stDict["Pacific Basin"] = "PB"
stDict["Pennsylvania"] = "PA"
stDict["Puerto Rico and U.S. Virgin Islands"] = "PRUSVI"
stDict["Rhode Island"] = "RI"
stDict["South Carolina"] = "SC"
stDict["South Dakota"] = "SD"
stDict["Tennessee"] = "TN"
stDict["Texas"] = "TX"
stDict["Utah"] = "UT"
stDict["Vermont"] = "VT"
stDict["Virginia"] = "VA"
stDict["Washington"] = "WA"
stDict["West Virginia"] = "WV"
stDict["Wisconsin"] = "WI"
stDict["Wyoming"] = "WY"
return stDict
except:
PrintMsg("\tFailed to create list of state abbreviations (CreateStateList)", 2)
return None
## ===================================================================================
def GetSDVAtts(gdb, resultcolumnname):
# GetSDVAtts(gdb, sdvAtt, aggMethod, tieBreaker, bFuzzy, sRV):
# Create a dictionary containing SDV attributes for the selected attribute fields
#
try:
# Open sdvattribute table and query for [attributename] = sdvAtt
dSDV = dict() # dictionary that will store all sdvattribute data using column name as key
sdvattTable = os.path.join(gdb, "sdvattribute")
flds = [fld.name for fld in arcpy.ListFields(sdvattTable)]
oid = flds.pop(0)
sql1 = "UPPER(resultcolumnname) = '" + resultcolumnname + "'"
#PrintMsg("\tresultcolumnname: " + resultcolumnname, 1)
if bVerbose:
PrintMsg(" \nReading sdvattribute table into dSDV dictionary", 1)
with arcpy.da.SearchCursor(sdvattTable, flds, where_clause=sql1) as cur:
for rec in cur: # just reading first record
i = 0
for val in rec:
dSDV[flds[i].lower()] = val
#PrintMsg(str(i) + ". " + flds[i] + ": " + str(val), 0)
i += 1
# Revise some attributes to accomodate fuzzy number mapping code
#
# Temporary workaround for NCCPI. Switch from rating class to fuzzy number
if dSDV["interpnullsaszeroflag"]:
bZero = True
if dSDV["attributetype"].lower() == "interpretation" and (dSDV["effectivelogicaldatatype"].lower() == "float" or bFuzzy == True):
#PrintMsg(" \nOver-riding attributecolumnname for " + sdvAtt, 1)
dSDV["attributecolumnname"] = "INTERPHR"
# WHAT HAPPENS IF I SKIP THIS NEXT SECTION. DOES IT BREAK EVERYTHING ELSE WHEN THE USER SETS bFuzzy TO True?
# Test is ND035, Salinity Risk%
# Answer: It breaks my map legend.
if dSDV["attributetype"].lower() == "interpretation" and dSDV["attributelogicaldatatype"].lower() == "string" and dSDV["effectivelogicaldatatype"].lower() == "float":
#PrintMsg("\tIdentified " + sdvAtt + " as being an interp with a numeric rating", 1)
pass
else:
#if dSDV["nasisrulename"][0:5] != "NCCPI":
# This comes into play when user selects option to create soil map using interp fuzzy values instead of rating classes.
dSDV["effectivelogicaldatatype"] = 'float'
dSDV["attributelogicaldatatype"] = 'float'
dSDV["maplegendkey"] = 3
dSDV["maplegendclasses"] = 5
dSDV["attributeprecision"] = 2
#else:
# Diagnostic for batch mode NCCPI
#PrintMsg(" \n" + dSDV["attributetype"].lower() + "; " + dSDV["effectivelogicaldatatype"] + "; " + str(bFuzzy), 1)
# Workaround for sql whereclause stored in sdvattribute table. File geodatabase is case sensitive.
if dSDV["sqlwhereclause"] is not None:
sqlParts = dSDV["sqlwhereclause"].split("=")
dSDV["sqlwhereclause"] = 'UPPER("' + sqlParts[0] + '") = ' + sqlParts[1].upper()
if dSDV["attributetype"].lower() == "interpretation" and bFuzzy == False and dSDV["notratedphrase"] is None:
# Add 'Not rated' to choice list
dSDV["notratedphrase"] = "Not rated" # should not have to do this, but this is not always set in Rule Manager
if dSDV["secondaryconcolname"] is not None and dSDV["secondaryconcolname"].lower() == "yldunits":
# then this would be units for legend (component crop yield)
#PrintMsg(" \nSetting units of measure to: " + secCst, 1)
dSDV["attributeuomabbrev"] = secCst
## if dSDV["attributecolumnname"].endswith("_r") and sRV in ["Low", "High"]:
## # This functionality is not available with SDV or WSS. Does not work with interps.
## #
## if sRV == "Low":
## dSDV["attributecolumnname"] = dSDV["attributecolumnname"].replace("_r", "_l")
##
## elif sRV == "High":
## dSDV["attributecolumnname"] = dSDV["attributecolumnname"].replace("_r", "_h")
#PrintMsg(" \nUsing attribute column " + dSDV["attributecolumnname"], 1)
# Working with sdvattribute tiebreak attributes:
# tiebreakruleoptionflag (0=cannot change, 1=can change)
# tiebreaklowlabel - if null, defaults to 'Lower'
# tiebreaklowlabel - if null, defaults to 'Higher'
# tiebreakrule -1=use lower 1=use higher
if dSDV["tiebreaklowlabel"] is None:
dSDV["tiebreaklowlabel"] = "Lower"
if dSDV["tiebreakhighlabel"] is None:
dSDV["tiebreakhighlabel"] = "Higher"
if dSDV["tiebreakrule"] == -1:
tieBreaker = dSDV["tiebreaklowlabel"]
else:
tieBreaker = dSDV["tiebreakhighlabel"]
#dAgg = dict()
if tieBreaker == dSDV["tiebreakhighlabel"]:
#PrintMsg(" \nUpdating dAgg", 1)
dAgg["Minimum or Maximum"] = "Max"
else:
dAgg["Minimum or Maximum"] = "Min"
#PrintMsg(" \nUpdating dAgg", 1)
#if aggMethod == "":
aggMethod = dSDV["algorithmname"]
if dAgg[aggMethod] != "":
dSDV["resultcolumnname"] = dSDV["resultcolumnname"] + "_" + dAgg[aggMethod]
#PrintMsg(" \nSetting resultcolumn name to: '" + dSDV["resultcolumnname"] + "'", 1)
return dSDV
except:
errorMsg()
return dSDV
## ===================================================================================
def CreateGroupLayer(grpLayerName, mxd, df):
try:
# Use template lyr file stored in current script directory to create new Group Layer
# This SDVGroupLayer.lyr file must be part of the install package along with
# any used for symbology. The name property will be changed later.
#
# arcpy.mapping.AddLayerToGroup(df, grpLayer, dInterpLayers[sdvAtt], "BOTTOM")
#
grpLayerFile = os.path.join(os.path.dirname(sys.argv[0]), "SDV_GroupLayer.lyr")
if not arcpy.Exists(grpLayerFile):
raise MyError, "Missing group layer file (" + grpLayerFile + ")"
testLayers = arcpy.mapping.ListLayers(mxd, grpLayerName, df)
if len(testLayers) > 0:
# Using existing group layer
grpLayer = testLayers[0]
else:
# Group layer does not exist, make a new one
grpLayer = arcpy.mapping.Layer(grpLayerFile) # template group layer file
grpLayer.visible = False
grpLayer.name = grpLayerName
grpLayer.description = "Group layer containing raster conversions from gSSURGO vector soil maps"
grpLayer.visible = False
arcpy.mapping.AddLayer(df, grpLayer, "TOP")
#PrintMsg(" \nAdding group layer: " + str(grpLayer.name), 0)
return grpLayer
except MyError, e:
# Example: raise MyError, "This is an error message"
PrintMsg(str(e), 2)
return None
except:
errorMsg()
return None
## ===================================================================================
def CreateRasterLayers(sdvLayers, inputRaster, outputFolder, bPyramids, cellFactor, outputRes, bOverwrite):
# Merge rating tables from for the selected soilmap layers to create a single, mapunit-level table
#
try:
global bVerbose
bVerbose = False
global bFuzzy
bFuzzy = False
if os.path.basename(env.scratchGDB) == "Default.gdb" or os.path.basename(env.scratchWorkspace) == "Default.gdb":
# Problems occur with raster geoprocessing when both the current and scratch geodatabases point to the
# same Default.gdb. Create a new scratch geodatabase for this script to use.
#if os.path.basename(env.scratchGDB) == "Default.gdb":
scrFolder = env.scratchFolder
if arcpy.Exists(os.path.join(os.path.dirname(scrFolder), "scratch.gdb")):
scrGDB = os.path.join(os.path.dirname(scrFolder), "scratch.gdb")
else:
scrGDB = os.path.join(scrFolder, "scratch.gdb")
if not arcpy.Exists(scrGDB):
arcpy.CreateFileGDB_management(scrFolder, "scratch.gdb", "CURRENT")
if arcpy.Exists(scrGDB):
env.scratchWorkspace = scrGDB
else:
raise MyError, "Failed to create " + scrGDB
# Get arcpy mapping objects
mxd = arcpy.mapping.MapDocument("CURRENT")
df = mxd.activeDataFrame
grpLayerName = "RASTER SOIL MAP CONVERSIONS"
grpLayer = CreateGroupLayer(grpLayerName, mxd, df)
if grpLayer is None:
raise MyError, ""
grpLayer = arcpy.mapping.ListLayers(mxd, grpLayerName, df)[0] # ValueError'>: DataFrameObject: Unexpected error
if outputFolder != "":
# if the outputFolder exists, create TIF files instead of file geodatabase rasters
if not arcpy.Exists(outputFolder):
outputFolder = ""
env.overwriteOutput = True # Overwrite existing output tables
env.pyramid = "NONE"
arcpy.env.compression = "LZ77"
env.pyramid = "NONE"
# Dictionary for aggregation method abbreviations
#
global dAgg
dAgg = dict()
dAgg["Dominant Component"] = "DCP"
dAgg["Dominant Condition"] = "DCD"
dAgg["No Aggregation Necessary"] = ""
dAgg["Percent Present"] = "PP"
dAgg["Weighted Average"] = "WTA"
dAgg["Most Limiting"] = "ML"
dAgg["Least Limiting"] = "LL"
dAgg[""] = ""
# Tool validation code is supposed to prevent duplicate output tables
# Get description and credits for each existing map layer
mLayers = arcpy.mapping.ListLayers(mxd, "*", df)
dMetadata = dict() # Save original soil map description so that it can passed on to the raster layer
for mLayer in mLayers:
dMetadata[mLayer.name] = (mLayer.description, mLayer.credits)
del mLayer, mLayers
# Probably should make sure all of these input layers have the same featureclass
#
# first get path where input SDV shapefiles are located (using last one in list)
# hopefully each layer is based upon the same set of polygons
#
# First check each input table to make sure there are no duplicate rating fields
# Begin by getting adding fields from the input shapefile (lastShp). This is necessary
# to avoid duplication such as MUNAME which may often exist in a county shapefile.
chkFields = list() # list of rating fields from SDV soil map layers (basenames). Use this to count dups.
dLayerFields = dict()
maxRecords = 0 # use this to determine which table has the most records and put it first
maxTable = ""
# Get FGDB raster from inputLayer
rDesc = arcpy.Describe(inputRaster)
iRaster = rDesc.meanCellHeight
rSR = rDesc.spatialReference
linearUnit = rSR.linearUnitName
rasterDB = os.path.dirname(rDesc.catalogPath) # should check to make sure each sdvLayer is from the same fgdb
# Iterate through each of the map layers and get the name of rating field from the join table
#
sdvLayers.reverse()
for sdvLayer in sdvLayers:
if sdvLayer.startswith("'") and sdvLayer.endswith("'"):
sdvLayer = sdvLayers[i][1:-1] # this is dropping first and last char in name for RUSLE2 maps..
desc = arcpy.Describe(sdvLayer)
dataType = desc.dataType
if dataType == "FeatureLayer":
gdb = os.path.dirname(desc.featureclass.catalogPath)
elif dataType == "RasterLayer":
gdb = os.path.dirname(desc.catalogPath)
else:
raise MyError, "Soil map datatype (" + dataType + ") not valid"
if not gdb == rasterDB:
raise MyError, "Map layer " + sdvLayer + " does belong to the same geodatabase as the input raster"
allFields = desc.fields
ratingField = allFields[-1] # rating field should be the last one in the table
fName = ratingField.name.encode('ascii') # fully qualified name
bName = ratingField.baseName.encode('ascii') # physical name
resultcolumnname = bName.split("_")[0] # Original SDV resultcolumnname. Use this to get matching sdvattribute record.
clipLen = (-1 * (len(bName))) - 1
sdvTblName = fName[0:clipLen] # rating table joined to map layer
sdvTbl = os.path.join(gdb, sdvTblName)
fldType = ratingField.type
fldLen = ratingField.length
dLayerFields[sdvLayer] = (sdvTblName, fName, bName, fldType, fldLen)
chkFields.append(bName)
# New check to make sure the sdvTbl exists. Possibility that the user has soil maps from multiple databases.
if not arcpy.Exists(sdvTbl):
raise MyError, "Table '" + sdvTblName + "' does not exist in this database: " + gdb
# alternative would be to get attributes from sdvattributetable using the resultcolumnname value
# work on this more later. dSDV = GetSDVAtts(gdb, resultcolumnname)
# Get information used in metadata
i = 0
layerIndx = 0
layerCnt = len(sdvLayers)
# Get user name and today's date for credits
envUser = arcpy.GetSystemEnvironment("USERNAME")
if "." in envUser:
user = envUser.split(".")
userName = " ".join(user).title()
elif " " in envUser:
user = envUser.split(" ")
userName = " ".join(user).title()
else:
userName = envUser
d = datetime.date.today()
toDay = d.isoformat()
newCredits = "Created by " + userName + " on " + toDay + " using script " + os.path.basename(sys.argv[0])
# Process each map layer. This is the beginning of the big loop.
#
for sdvLayer in sdvLayers:
layerIndx += 1
arcpy.SetProgressorLabel("Creating raster layer from '" + sdvLayer + "' (" + str(layerIndx) + " of " + str(layerCnt) + ")")
PrintMsg(" \nCreating raster layer from '" + sdvLayer + "' (" + str(layerIndx) + " of " + str(layerCnt) + ")", 0)
sdvTblName, fName, bName, fldType, fldLen = dLayerFields[sdvLayer]
newDescription = dMetadata[sdvLayer][0]
processSteps = ""
newLayerName = sdvLayer + " (" + str(outputRes) + " " + linearUnit.lower() + " raster)"
symTbl = os.path.join(gdb, "SDV_Symbology")
# Set initialize output resolution to same as input
env.cellSize = iRaster
# Set output file name (FGDB Raster or TIFF)
# Use input geodatabase if no folder is specified
if outputFolder == "":
if sdvTblName[-1].isdigit():
newRaster = os.path.join(gdb, "SoilRas_" + sdvTblName.replace("SDV_", "") + "_" + str(outputRes) + str(linearUnit)) # Temporary placement of this line
else:
if sdvTblName[-1].isdigit():
newRaster = os.path.join(gdb, "SoilRas_" + sdvTblName.replace("SDV_", "") + "cm_" + str(outputRes) + str(linearUnit)) # Temporary placement of this line
else:
newRaster = os.path.join(gdb, "SoilRas_" + sdvTblName.replace("SDV_", "") + "_" + str(outputRes) + str(linearUnit)) # Temporary placement of this line
else:
if outputFolder.endswith(".gdb"):
# FGDB Raster
if sdvTblName[-1].isdigit():
newRaster = os.path.join(outputFolder, "SoilRas_" + sdvTblName.replace("SDV_", "") + "cm_" + str(outputRes) + str(linearUnit)) # Temporary placement of this line
else:
newRaster = os.path.join(outputFolder, "SoilRas_" + sdvTblName.replace("SDV_", "") + "_" + str(outputRes) + str(linearUnit)) # Temporary placement of this line
else:
# TIFF
if sdvTblName[-1].isdigit():
newRaster = os.path.join(outputFolder, "SoilRas_" + sdvTblName.replace("SDV_", "") + "cm_" + str(outputRes) + str(linearUnit) + ".tif") # Temporary placement of this line
else:
newRaster = os.path.join(outputFolder, "SoilRas_" + sdvTblName.replace("SDV_", "") + "_" + str(outputRes) + str(linearUnit) + ".tif") # Temporary placement of this line
# PrintMsg("\tOutput raster will be '" + newRaster + "'", 0)
# Check raster output overwrite option here before proceeding
# Skip raster conversion if output already exists and bOverwrite = False (default)
if (bOverwrite and arcpy.Exists(newRaster)) or not arcpy.Exists(newRaster):
if arcpy.Exists(symTbl):
wc = "layername = '" + sdvLayer +"'"
rendererInfo = ""
with arcpy.da.SearchCursor(symTbl, ['maplegend'], where_clause=wc) as cur:
for rec in cur:
rendererInfo = json.loads(rec[0])
if len(rendererInfo) > 0:
rendererType = rendererInfo['type']
#PrintMsg(" \nrendererType: " + rendererType, 1)
else:
if fldType == "String":
rendererType = "uniqueValue"
else:
rendererType = ""
dLegendInfo = dict()
if rendererType == 'uniqueValue':
# Let's try writing a Lookup table that we can use later
# Failing for non-irr cap class
#
lu = os.path.join(gdb, "Lookup")
if arcpy.Exists(lu):
arcpy.Delete_management(lu)
arcpy.CreateTable_management(os.path.dirname(lu), os.path.basename(lu))
arcpy.AddField_management(lu, "CELLVALUE", "LONG")
arcpy.AddField_management(lu, bName, fldType, "#", "#", fldLen) # join on this column, but add LABEL to class_name
arcpy.AddField_management(lu, "LABEL", "TEXT", "#", "#", fldLen)
if len(rendererInfo) > 0:
# Create Lookup table with color information
# Example K Factor (whole soils)
#
PrintMsg("\tBuilding Lookup table from map layer information", 0)
with arcpy.da.InsertCursor(lu, ["CELLVALUE", bName, "LABEL"]) as cur:
row = 0
remapList = list()
#PrintMsg(" \nuniqueValueInfos: " + str(rendererInfo['uniqueValueInfos']), 1)
for valInfos in rendererInfo['uniqueValueInfos']:
row += 1
cRed, cGreen, cBlue, opacity = valInfos['symbol']['color']
lab = valInfos['label']
val = valInfos['value']
dLegendInfo[row] = (val, lab, (float(cRed) / 255.0), (float(cGreen) / 255.0), (float(cBlue) / 255.0), 1)
remapList.append([row, row])
try:
cur.insertRow([row, val, lab])
except:
# Need to leave NULL values out of Lookup
pass