forked from wilmerjimenez/SoilDataDevelopmentToolbox
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSDA_Mapping.py
7618 lines (5823 loc) · 320 KB
/
SDA_Mapping.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
# SDA_Mapping.py
#
# Creates Soil Data Viewer-type maps using Soil Data Access and the sdv* attribute tables
# Uses mdstatrship* tables and sdvattribute table to populate menu
#
# 2016-06-22
#
# THINGS TO DO:
#
# Implement Tie-Breaker parameter
# Incorporate "Least Limiting", "Most Limiting" and "Maximum or Minimum" aggregation methods
#
# 2015-10-07 Still some issues related to arcpy.mapping.symbology and layer files. Added
# workaround for join-symbology bug.
#
# 2015-10-12 Removed WTA as an aggregation method for interps. Conflicting information regarding this.
#
# 2015-10-30 Need to check for conflicting tables in the ArcMap that might interfer with queries. arcpy.mapping.ListTableViews
#
# 2015-12-14 Added record count for mdstatrshpdet table because some of the geodatabases created by
# the SSURGO QA scripts do not populate the md* tables.
#
#
# 1. Aggregation method "Weighted Average" can now be used for non-class soil interpretations.
#
#
# 2. "Minimum or Maximum" and its use is now restricted to numeric attributes or attributes
# with a corresponding domain that is logically ordered.
#
# 3. Aggregation method "Absence/Presence" was replaced with a more generalized version
# thereof, which is referred to as "Percent Present". Up to now, aggregation method
# "Absence/Presence" was supported for one and only one attribute, component.hydricrating.
# Percent Present is a powerful new aggregation method that opens up a lot of new possibilities,
# e.g. "bedrock within two feel of the surface".
#
# 4. The merged aggregation engine now supports two different kinds of horizon aggregation,
# "weighted average" and "weighted sum". For the vast majority of horizon level attributes,
# "weighted average" is used. At the current time, the only case where "weighted sum" is used is
# for Available Water Capacity, where the water holding capacity needs to be summed rather than
# averaged.
# 5. The aggregation process now always returns two values, rather than one, the original
# aggregated result AND the percent of the map unit that shares that rating. For example, for
# the drainage class/dominant condition example below, the rating would be "Moderately well
# drained" and the corresponding map unit percent would be 60:
#
# 6. A horizon or layer where the attribute being aggregated is null will now never contribute
# to the final aggregated result. There # was a case for the second version of the aggregation
# engine where this was not true.
#
# 7. Column sdvattribute.fetchallcompsflag is no longer needed. The new aggregation engine was
# updated to know that it needs to # include all components whenever no component percent cutoff
# is specified and the aggregation method is "Least Limiting" or "Most # Limiting" or "Minimum or Maximum".
#
# 8. For aggregation methods "Least Limiting" and "Most Limiting", the rating will be set to "Unknown"
# if any component has a null # rating, and no component has a fully conclusive rating (0 or 1), depending
# on the type of rule (limitation or suitability) and the # corresponding aggregation method.
#
# 2015-12-17 Depth to Water Table: [Minimum or Maximum / Lower] is not swapping out NULL values for 201.
# The other aggregation methods appear to be working properly. So the minimum is returning mostly NULL
# values for the map layer when it should return 201's.
# 2015-12-17 For Most Limiting, I'm getting some questionable results. For example 'Somewhat limited'
# may get changed to 'Not rated'
# Looking at option to map fuzzy rating for all interps. This would require redirection to the
# Aggregate2_NCCPI amd CreateNumericLayer functions. Have this working, but needs more testing.
#
# 2015-12-23 Need to look more closely at my Tiebreak implementation for Interps. 'Dwellings with
# Basements (DCD, Higher) appears to be switched. Look at Delware 'PsA' mapunit with Pepperbox-Rosedale components
# at 45% each.
#
# 2016-03-23 Fixed bad bug, skipping last mapunit in NCCPI and one other function
#
# 2016-04-19 bNulls parameter. Need to look at inclusion/exclusion of NULL rating values for Text or Choice.
# WSS seems to include NULL values for ratings such as Hydrologic Group and Flooding
#
# Interpretation columns
# interphr is the High fuzzy value, interphrc is the High rating class
# interplr is the Low fuzzy value, interplrc is the Low rating class
# Very Limited = 1.0; Somewhat limited = 0.22
# Branched off gSSURGO_Mapping2.py on 6-13-2016 to add function for JSON symbology. May need to remerge the two
# because I've probably fixed some old stuff in this version of the script. Not sure if the reverse is true.
#
## ===================================================================================
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 attFld 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.AddError(" \n" + 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 BadTable(tbl):
# Make sure the table has data
#
# If has contains one or more records, return False (not a bad table)
# If the table is empty, return True (bad table)
try:
if not arcpy.Exists(tbl):
return True
recCnt = int(arcpy.GetCount_management(tbl).getOutput(0))
if recCnt > 0:
return False
else:
return True
except:
errorMsg()
return True
## ===================================================================================
def SortData(muVals):
# Sort a list of tuples containing comppct_r and rating value or index and return a single tuple.
try:
if tieBreaker == dSDV["tiebreakhighlabel"]:
# return higher value
muVal = sorted(sorted(muVals, key = lambda x : x[1], reverse=True), key = lambda x : x[0], reverse=True)[0]
elif tieBreaker == dSDV["tiebreaklowlabel"]:
muVal = sorted(sorted(muVals, key = lambda x : x[1], reverse=False), key = lambda x : x[0], reverse=True)[0]
else:
muVal = (None, None)
return muVal
except:
errorMsg()
return (None, None)
## ===================================================================================
def ColorRamp(count, items, upperColor, lowerColor):
# For Progressive color ramps, there are no colors defined for each legend item.
# Create a dictionary of colors based upon the upper and lower colors. Key value is
# 'part' which is the number of colors used to define the color ramp.
# count is always equal to three and part is always zero-based
try:
PrintMsg(" \nCreating color ramp based upon " + str(count) + " item ramp", 1)
dColors = dict()
dRGB = dict()
# RGB colors:
# 255, 0, 0 = red
# 255, 255, 0 = yellow
# 0, 255, 0 = green
# 0, 255, 255 = cyan
# 0, 0, 255 = blue
# pH example: Creating color ramp based upon 4 colors red -> yellow -> cyan -> blue
#
# red -> yellow (255, 0, 0) -> (255, 255, 0)
#
# yellow -> cyan (255, 255, 0) -> (0, 255, 255)
#
# cyan -> blue (0, 255, 255) -> (0, 0, 255)
dRGB[(255,0,0)] = "red"
dRGB[(255,255,0)] = "yellow"
dRGB[(0,255,0)] ="green"
dRGB[(0,255,255)] = "cyan"
dRGB[(0,0,255)] = "blue"
#PrintMsg(" \nlowerColor: " + str(lowerColor), 1)
#PrintMsg(" \nupperColor: " + str(upperColor), 1)
PrintMsg(dRGB[upperColor[0]] + "->" + dRGB[lowerColor[0]], 1)
PrintMsg(dRGB[upperColor[1]] + "->" + dRGB[lowerColor[1]], 1)
PrintMsg(dRGB[upperColor[2]] + "->" + dRGB[lowerColor[2]], 1)
PrintMsg(" \n" + str(upperColor[0]) + "->" + str(lowerColor[0]), 1)
PrintMsg(str(upperColor[1]) + "->" + str(lowerColor[1]), 1)
PrintMsg(str(upperColor[2]) + "->" + str(lowerColor[2]), 1)
# create lists of colors for each legend item
redList = list()
greenList = list()
blueList = list()
interVal = int(items / (count - 1))
#for i in range(count - 1):
if 1 == 2: # skip this for now
# My understanding is that 3 points define the color ramp. Beginning color, middle color and ending color
# Handle each pair of points (0-1, 1-2) and append the color lists for each to make the complete set
#for i in range(count):
# for each color (r=0, g=1, b= 2)
if lowerColor[i][0] != upperColor[i][0]:
tmpList = range(lowerColor[i][0], upperColor[i][0], int((upperColor[i][0] - lowerColor[i][0]) / interVal) )
else:
tmpList = [lowerColor[i][0]] * interVal
redList.extend(tmpList)
if lowerColor[i][1] != upperColor[i][1]:
tmpList = range(lowerColor[i][1], upperColor[i][1], int((upperColor[i][1] - lowerColor[i][1]) / interVal) )
PrintMsg(" \ntmpList: " + str(lowerColor[i][1]) + "; " + str(upperColor[i][1]) , 1)
else:
tmpList = [lowerColor[i][1]] * interVal
greenList.extend(tmpList)
if lowerColor[i][2] != upperColor[i][2]:
tmpList = range(lowerColor[i][2], upperColor[i][2], int((upperColor[i][2] - lowerColor[i][2]) / interVal) )
else:
tmpList = [lowerColor[i][2]] * interVal
blueList.extend(tmpList)
#PrintMsg(" \nRedList " + str(i) + ": " + str(redList))
#PrintMsg(" \nGreenList " + str(i) + ": " + str(greenList))
#PrintMsg(" \nBlueList " + str(i) + ": " + str(blueList))
#for i in range(len(redList)):
# PrintMsg("\t" + str(i) + " (" + str(redList[1]) + ", " + str(greenList[i]) + ", " + str(blueList[i]) + ")", 1)
return dColors
except:
errorMsg()
return dColors
## ===================================================================================
def GetMapLegend(dAtts):
# Get map legend values and order from maplegendxml column in sdvattribute table
# Return dLegend dictionary containing contents of XML.
try:
#bVerbose = False # This function seems to work well, but prints a lot of messages.
if bFuzzy:
# 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(" \n" + xmlString + " \n ", 1)
# Convert XML to tree format
tree = ET.fromstring(xmlString)
# Iterate through XML tree, finding required elements...
i = 0
dLegend = dict()
dLabels = dict()
dColors = dict()
#dLegendElements = 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
#rec.attrib["label"] = label
dLabels[order] = rec.attrib
except:
upperVal = int(rec.attrib["upper_value"])
lowerVal = int(rec.attrib["lower_value"])
#label = rec.attrib["label"]
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
#rec.attrib["label"] = label
dLabels[order] = rec.attrib
except:
upperVal = float(rec.attrib["upper_value"])
lowerVal = float(rec.attrib["lower_value"])
#label = rec.attrib["label"]
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"] + " Legend Key: " + dLegend["maplegendkey"] + ", Type: " + dLegend["type"] + ", Name: " + dLegend["name"] , 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 dLegend["name"] == "Progressive":
# dColors = ColorRamp(dLegend["count"], len(dLabels), dLegend["LowerColor"], dLegend["UpperColor"])
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 CreateNumericLayer(sdvLyrFile, dLegend, outputValues, classBV, classBL):
#
# POLYGON layer
#
# Create dummy polygon featureclass that can be used to set up
# GRADUATED_COLORS symbology for the final map layer.
#
# Need to expand this to able to use defined class breaks and remove unused
# breaks, labels.
#
# I saw a confusing error message related to env.scratchGDB that was corrupted.
# The error message was ERROR 000354: The name contains invalid characters.
# SDVATTRIBUTE Table notes:
#
# dSDV["maplegendkey"] tells us which symbology type to use
# dSDV["maplegendclasses"] tells us if there are a fixed number of classes (5)
# dSDV["maplegendxml"] gives us detailed information about the legend such as class values, legend text
#
# *maplegendkey 1: fixed numeric class ranges with zero floor. Used only for Hydric Percent Present.
#
# maplegendkey 2: defined list of ordered values and legend text. Used for Corrosion of Steel, Farmland Class, TFactor.
#
# *maplegendkey 3: classified numeric values. Physical and chemical properties.
#
# maplegendkey 4: unique string values. Unknown values such as mapunit name.
#
# maplegendkey 5: defined list of string values. Used for Interp ratings.
#
# *maplegendkey 6: defined class breaks for a fixed number of classes and a color ramp. Used for pH, Slope, Depth to.., etc
#
# *maplegendkey 7: fixed list of index values and legend text. Used for Irrigated Capability Class, WEI, KFactor.
#
# maplegendkey 8: random unique values with domain values and legend text. Used for HSG, Irrigated Capability Subclass, AASHTO.
try:
#arcpy.SetProgressorLabel("Setting up layer for numeric data")
if bVerbose:
PrintMsg(" \nCurrent function : " + sys._getframe().f_code.co_name, 1)
PrintMsg(" \nTop of CreateNumericLayer \n classBV: " + str(classBV) + " \nclassBL: " + str(classBL), 1)
# For pH, the classBV and classBL are already set properly at this point. Need to skip any changes to
# these two variables.
# The temporary output feature class to be created for symbology use.
dummyName = "sdvsymbology"
dummyFC = os.path.join(scratchGDB, dummyName)
# Create the output feature class
#
if arcpy.Exists(dummyFC):
arcpy.Delete_management(dummyFC)
time.sleep(1)
arcpy.CreateFeatureclass_management(os.path.dirname(dummyFC), os.path.basename(dummyFC), "POLYGON")
# Create copy of output field and add to shapefile
outFields = arcpy.Describe(outputTbl).fields
for fld in outFields:
fName = fld.name
fType = fld.type.upper()
fLen = fld.length
arcpy.AddField_management(dummyFC, dSDV["resultcolumnname"].upper(), fType, "", "", fLen)
# Handle numeric ratings
if dSDV["maplegendkey"] in [1, 2, 3, 6]:
#
try:
# Problem with bFuzzy for other interps besides NCCPI
dLabels = dLegend["labels"]
except:
dLabels = dict()
if len(outputValues) == 2:
# Use this one if outputValues are integer with a unique values renderer
#
if outputValues[0] is None:
outputValues[0] = 0
if outputValues[1] is None:
outputValues[1] = 0
if dSDV["effectivelogicaldatatype"].lower() == "float":
minVal = max(float(outputValues[0]), 0)
maxVal = max(float(outputValues[1]), 0)
elif dSDV["effectivelogicaldatatype"].lower() == "integer":
minVal = max(outputValues[0], 0)
maxVal = max(int(outputValues[1]), 0)
else:
# Use this for an unknown range of numeric values including Nulls
minVal = max(min(outputValues), 0)
maxVal = max(max(outputValues), 0)
else:
# More than a single pair of values
if dSDV["effectivelogicaldatatype"].lower() == "float":
minVal = min(outputValues)
maxVal = max(outputValues)
elif dSDV["effectivelogicaldatatype"].lower() == "integer":
# Need to handle Null values
#PrintMsg(" \noutputValues: " + str(outputValues), 1)
if len(outputValues) == 0:
minVal = 0
maxVal = 0
else:
minVal = max(min(outputValues), 0)
maxVal = max(max(outputValues), 0)
else:
# Use this for an unknown range of numeric values
minVal = max(min(outputValues), 0)
maxVal = max(max(outputValues), 0)
if minVal is None:
minVal = 0
if maxVal is None:
maxVal = 0
if bVerbose:
PrintMsg("Min: " + str(minVal) + "; Max: " + str(maxVal), 1)
valRange = maxVal - minVal
if dSDV["maplegendkey"] == 1:
# This legend will use Graduated Colors
#
classBV = list()
classBL = list()
# Need to get first and last values and then resort from high to low
if bVerbose:
PrintMsg(" \nC For MapLegendKey " + str(dSDV["maplegendkey"]) + ", CreateNumericLayer set class breaks to: " + str(classBV), 1)
if len(dLabels) > 0:
#PrintMsg(" \nGot labels....", 1)
if bVerbose:
for key, val in dLabels.items():
PrintMsg("\tdLabels[" + str(key) + "] = " + str(val), 1)
if float(dLabels[1]["upper_value"]) > float(dLabels[len(dLabels)]["upper_value"]):
# Need to swap because legend is high-to-low
classBV.append(float(dLabels[len(dLabels)]["lower_value"]))
#PrintMsg("\tLow value: " + dLabels[len(dLabels)]["lower_value"], 1)
for i in range(len(dLabels), 0, -1):
classBV.append(float(dLabels[i]["upper_value"])) # class break
classBL.append(dLabels[i]["label"]) # label
#PrintMsg("\tLegend Text: " + dLabels[i]["label"], 1)
#PrintMsg("Class: " + str(dLabels[i]["lower_value"]), 1)
else:
# Legend is already low-to-high
for i in range(1, len(dLabels) + 1):
classBV.append(float(dLabels[i]["lower_value"])) # class break
classBL.append(dLabels[i]["label"]) # label
#PrintMsg("Class: " + str(dLabels[i]["lower_value"]), 1)
classBV.append(float(dLabels[len(dLabels)]["upper_value"]))
#PrintMsg("\tLast value: " + dLabels[len(dLabels)]["upper_value"], 1)
# Report class breaks and class break labels
if bVerbose:
PrintMsg(" \nClass Break Values for 1, 3, 6: " + str(classBV), 1)
PrintMsg(" \nClass Break Labels for 1, 3, 6: " + str(classBL), 1)
elif dSDV["maplegendkey"] == 2 and dSDV["attributelogicaldatatype"].lower() == "integer":
if bVerbose:
PrintMsg(" \nA For MapLegendKey " + str(dSDV["maplegendkey"]) + ", CreateNumericLayer set class breaks to: " + str(classBV), 1)
elif dSDV["maplegendkey"] == 3:
# Physical and chemical properties, NCCPI
# 5 numeric classes; red (low val) to blue (high val) using Natural Breaks
#
# Try creating 5 equal interval values within the min-max range and then
# setting only symbology.classNum (and not classBreakValues)
#
# There will be no legend values or legend text for this group
if not dSDV["maplegendclasses"] is None:
if valRange == 0:
# Only a single value in the data, don't create a 5 class legend
classBV = [minVal, minVal]
classBL = [str(minVal)]
else:
if bVerbose:
PrintMsg(" \nCalculating equal interval for " + str(dSDV["maplegendclasses"]) + " classes with a precision of " + str(dSDV["attributeprecision"]), 1)
newVal = minVal
if dSDV["attributeprecision"] is None:
interVal = round((valRange / dSDV["maplegendclasses"]), 2)
classBV = [newVal]
#for i in range(int(dLegend["classes"])):
for i in range(int(dSDV["maplegendclasses"])):
newVal += interVal
classBV.append(int(round(newVal, 0)))
if i == 0:
classBL.append(str(minVal) + " - " + str(newVal))
else:
classBL.append(str(classBV[i]) + " - " + str(newVal))
else:
#PrintMsg(" \nUsing attribute precision (" + str(dSDV["attributeprecision"] ) + ") to create " + str(dSDV["maplegendclasses"]) + " legend classes", 1)
interVal = round((valRange / dSDV["maplegendclasses"]), dSDV["attributeprecision"])
classBV = [round(newVal, dSDV["attributeprecision"])]
for i in range(int(dSDV["maplegendclasses"]) - 1):
newVal += interVal
classBV.append(round(newVal, dSDV["attributeprecision"]))
if i == 0:
classBL.append(str(round(minVal, dSDV["attributeprecision"])) + " - " + str(round(newVal, dSDV["attributeprecision"])))
else:
classBL.append(str(classBV[i]) + " - " + str(round(newVal, dSDV["attributeprecision"])))
# Substitute last value in classBV with maxVal
lastLabel = str(classBV[-1]) + " - " + str(round(maxVal, dSDV["attributeprecision"]))
classBV.append(round(maxVal, dSDV["attributeprecision"]))
classBL.append(lastLabel)
if bVerbose:
PrintMsg(" \nB For MapLegendKey " + str(dSDV["maplegendkey"]) + ", CreateNumericLayer set class breaks to: " + str(classBV), 1)
else:
# No sdvattribute for number of legend classes
pass
elif dSDV["maplegendkey"] == 6:
# fixed numeric class ranges such as pH, slope that have high and low values
#
# I think I can skip 6 because pH is already set
pass
#for i in range(1, len(dLabels) + 1):
# classBV.append(float(dLabels[i]["lower_value"])) # class break
# classBL.append(dLabels[i]["label"]) # label
#PrintMsg("Class: " + str(dLabels[i]["lower_value"]), 1)
#classBV.append(float(dLabels[len(dLabels)]["upper_value"]))
else:
# Need to handle non-numeric legends differently
# Probably should not even call this function?
#
PrintMsg(" \nMapLegendKey is not valid (" + str(dSDV["maplegendkey"]) + ")", 1)
return None
# Open an insert cursor for the new feature class
#
x1 = 0
y1 = 0
x2 = 1
y2 = 1
with arcpy.da.InsertCursor(dummyFC, ["SHAPE@", fName]) as cur:
# Create an array object needed to create features
#
for i in range(len(classBV)):
array = arcpy.Array()
coords = [[x1, y1], [x1, y2], [x2, y2], [x2, y1]]
for coord in coords:
pnt = arcpy.Point(coord[0], coord[1])
array.add(pnt)
array.add(array.getObject(0))
polygon = arcpy.Polygon(array)
rec = [polygon, classBV[i]]
cur.insertRow(rec)
x1 += 1
x2 += 1
if not dSDV["attributeuomabbrev"] is None and len(classBL) > 0:
#PrintMsg(" \nAdding " + dSDV["attributeuomabbrev"] + " to legend " + str(classBL[0]), 1)
classBL[0] = classBL[0] + " (" + dSDV["attributeuomabbrev"] + ")"
if not dSDV["attributeuomabbrev"] is None and len(classBL) == 0:
if bVerbose:
PrintMsg(" \nNo class break labels for " + sdvAtt + " with uom: " + dSDV["attributeuomabbrev"], 1)
# Try creating a featurelayer from dummyFC
dummyLayer = "DummyLayer"
arcpy.MakeFeatureLayer_management(dummyFC, dummyLayer)
#arcpy.mapping.AddLayer(df, tmpSDVLayer)
#arcpy.ApplySymbologyFromLayer_management("DummyLayer", sdvLyrFile)
# Define temporary output layer filename
#layerFileCopy = os.path.join(env.scratchFolder, os.path.basename(sdvLyrFile))
#arcpy.SaveToLayerFile_management("DummyLayer", layerFileCopy, "ABSOLUTE", "10.1")
#arcpy.Delete_management("DummyLayer") # not sure that this does anything
# Now bring up the temporary dummy featureclass and apply symbology to it
dummyDesc = arcpy.Describe(dummyLayer)
#tmpSDVLayer = arcpy.mapping.Layer(layerFileCopy)
tmpSDVLayer = arcpy.mapping.Layer(dummyLayer)
tmpSDVLayer.visible = False
arcpy.mapping.UpdateLayer(df, tmpSDVLayer, arcpy.mapping.Layer(sdvLyrFile), True)
if tmpSDVLayer.symbologyType.lower() == "other":
if tmpSDVLayer.dataSource == dummyFC:
arcpy.ApplySymbologyFromLayer_management(tmpSDVLayer, sdvLyrFile)
if tmpSDVLayer.symbologyType.lower() == "other":
# Failed to properly update symbology on the dummy layer for a second time
raise MyError, "Failed to properly update the datasource using " + dummyFC
# At this point, the layer is based upon the dummy featureclass
if dSDV["maplegendkey"] in [1, 3, 6]:
tmpSDVLayer.symbology.valueField = fName
tmpSDVLayer.symbology.classBreakValues = classBV
tmpSDVLayer.symbology.classBreakLabels = classBL
elif dSDV["maplegendkey"] in [2]:
tmpSDVLayer.symbology.valueField = fName
tmpSDVLayer.symbology.classValues = classBV
tmpSDVLayer.symbology.classLabels = classBL
return tmpSDVLayer # This does not contain the actual data. It is a dummy layer!
except MyError, e:
PrintMsg(str(e), 2)
return None
except:
errorMsg()
return None
## ===================================================================================
def GetNumericLegend(dLegend, outputValues):
#
# For Raster layers only...
# Create final class break values and labels that can be used to create legend
#
# SDVATTRIBUTE Table notes:
#
# dSDV["maplegendkey"] tells us which symbology type to use
# dSDV["maplegendclasses"] tells us if there are a fixed number of classes (5)
# dSDV["maplegendxml"] gives us detailed information about the legend such as class values, legend text
#
# *maplegendkey 1: fixed numeric class ranges with zero floor. Used only for Hydric Percent Present.
#
# maplegendkey 2: defined list of ordered values and legend text. Used for Corrosion of Steel, Farmland Class, TFactor.
#
# *maplegendkey 3: classified numeric values. Physical and chemical properties.
#
# maplegendkey 4: unique string values. Unknown values such as mapunit name.
#
# maplegendkey 5: defined list of string values. Used for Interp ratings.
#
# *maplegendkey 6: defined class breaks for a fixed number of classes and a color ramp. Used for pH, Slope, Depth to.., etc
#
# *maplegendkey 7: fixed list of index values and legend text. Used for Irrigated Capability Class, WEI, KFactor.
#
# maplegendkey 8: random unique values with domain values and legend text. Used for HSG, Irrigated Capability Subclass, AASHTO.
try:
#arcpy.SetProgressorLabel("Setting up layer for numeric data")
#bVerbose = True
if bVerbose:
PrintMsg(" \nCurrent function : " + sys._getframe().f_code.co_name, 1)
precision = max(dSDV["attributeprecision"], 0)
# Handle numeric ratings
if dSDV["maplegendkey"] in [1, 2, 3, 6]:
#
if bVerbose:
PrintMsg(" \noutputValues are " + str(outputValues), 1)
try:
PrintMsg(" \nclassBV: " + str(classBV), 1)
except:
PrintMsg(" \nMissing classBV variable", 1)
pass
#PrintMsg(" \nComing into GetNumericLegend, classBV = " + str(classBV), 1)
if len(outputValues) == 2:
# Use this one if outputValues are integer with a unique values renderer
#
if outputValues[0] is None:
outputValues[0] = 0
if outputValues[1] is None:
outputValues[1] = 0
if dSDV["effectivelogicaldatatype"].lower() == "float":
minVal = max(float(outputValues[0]), 0)
maxVal = max(float(outputValues[1]), 0)
elif dSDV["effectivelogicaldatatype"].lower() == "integer":
minVal = int(max(outputValues[0], 0))
maxVal = int(max(outputValues[1], 0))
else:
# Use this for an unknown range of numeric values including Nulls
minVal = max(min(outputValues), 0)
maxVal = max(max(outputValues), 0)
else:
# More than a single pair of values
#
# Go ahead and set the class break values = outputValues
#PrintMsg(" \nSetting class break values and labels using outputValues: " + str(outputValues), 1)
classBV = list(outputValues)
classBL = list(outputValues)
if dSDV["effectivelogicaldatatype"].lower() == "float":
minVal = min(outputValues)
maxVal = max(outputValues)
elif dSDV["effectivelogicaldatatype"].lower() == "integer":
# Need to handle Null values
#PrintMsg(" \noutputValues: " + str(outputValues), 1)
if len(outputValues) == 0:
minVal = 0
maxVal = 0
else:
minVal = int(max(min(outputValues), 0))
maxVal = int(max(max(outputValues), 0))
else:
# Use this for an unknown range of numeric values
minVal = max(min(outputValues), 0)
maxVal = max(max(outputValues), 0)
if minVal is None:
minVal = 0
if maxVal is None:
maxVal = 0
if bVerbose:
PrintMsg("GetNumericLegend has Min: " + str(minVal) + "; Max: " + str(maxVal), 1)
valRange = maxVal - minVal
if dSDV["maplegendkey"] == 2 and dSDV["attributelogicaldatatype"].lower() == "integer":
if bVerbose:
PrintMsg(" \nA For MapLegendKey " + str(dSDV["maplegendkey"]) + ", CreateNumericLayer set class breaks to: " + str(classBV), 1)
pass
elif dSDV["maplegendkey"] == 3:
# Physical and chemical properties
# 5 numeric classes; red (low val) to blue (high val) using Natural Breaks
#
# Try creating 5 equal interval values within the min-max range and then
# setting only symbology.classNum (and not classBreakValues)
#
# There will be no legend values or legend text for this group
if not dSDV["maplegendclasses"] is None:
if valRange == 0:
# Only a single value in the data, don't create a 5 class legend
classBV = [minVal, minVal]
classBL = [str(minVal)]
else:
if bVerbose:
PrintMsg(" \nCalculating equal interval for " + str(dSDV["maplegendclasses"]) + " classes", 1)
interVal = round((valRange / dSDV["maplegendclasses"]), precision)
newVal = minVal
classBV = [newVal]
classBL = []
if dSDV["attributeprecision"] is None:
for i in range(int(dSDV["maplegendclasses"])):
newVal += interVal
classBV.append(int(round(newVal, 0)))
if i == 0:
classBL.append(str(int(minVal)) + " - " + str(int(newVal)))
else:
classBL.append(str(int(classBV[i])) + " - " + str(int(newVal)))
else:
for i in range(int(dSDV["maplegendclasses"]) - 1):
newVal += interVal
classBV.append(round(newVal, dSDV["attributeprecision"]))
if i == 0:
classBL.append(str(round(minVal, dSDV["attributeprecision"])) + " - " + str(round(newVal, dSDV["attributeprecision"])))
else:
classBL.append(str(classBV[i]) + " - " + str(round(newVal, dSDV["attributeprecision"])))
# Substitute last value in classBV with maxVal
lastLabel = str(classBV[-1]) + " - " + str(maxVal)
classBV.append(maxVal)
classBL.append(lastLabel)
if bVerbose:
PrintMsg(" \nB For MapLegendKey " + str(dSDV["maplegendkey"]) + ", CreateNumericLayer set class breaks to: " + str(classBV), 1)
elif dSDV["maplegendkey"] == 1:
# This legend will use Graduated Colors
#
classBV = list()
classBL = list()
# Need to get first and last values and then resort from high to low
if bVerbose:
if bVerbose:
PrintMsg(" \nC For MapLegendKey " + str(dSDV["maplegendkey"]) + ", CreateNumericLayer set class breaks to: " + str(classBV), 1)