-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathgSSURGO_ValuTable.py
3273 lines (2521 loc) · 137 KB
/
gSSURGO_ValuTable.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_ValuTable.py
#
# Steve Peaslee, National Soil Survey Center
# 2014-09-27
# Adapted from HorizonData_Mapping
# Calculates root zone depth, root zone available water supply and a set of
# available water supply values at various defined depth ranges.
#
# The root zone available water supply is calculated down to the root zone for
# each component and then a weighted average is calculated for the map unit.
#
# The rest of the AWS columns are calculated for all components at a variety of depths.
# Output is to a geodatabase table (Valu1)
#
# To do list for FY2016....
# In order for this script to meet the 2015 standard for the Valu1 table it needs to:
# skip components where compkind is null
# stop horizon calculations for all data where there is a discrepancy in horizon depths
# null map unit AWS, SOC and PWSL values where sum of all components > 100
# null Rootzone Depth, Rootzone AWS and NCCPI* where sum of major components > 100
# perform independent validation of SOC results
# compare metadata dates to make sure they are properly coded and inserted
# look at array processing for calculations based upon depth ranges
#
# changed the OM to carbon conversion from * 0.58 to / 1.724 after running FY2017 value table
## ===================================================================================
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, "")
locale.getlocale()
if bCommas:
theNumber = locale.format("%.*f", (places, num), True)
else:
theNumber = locale.format("%.*f", (places, num), False)
return theNumber
except:
PrintMsg("Unhandled exception in Number_Format function (" + str(num) + ")", 2)
return False
## ===================================================================================
def GetLastDate(inputDB):
# Get the most recent date 'YYYYMMDD' from SACATALOG.SAVEREST and use it to populate metadata
#
try:
tbl = os.path.join(inputDB, "SACATALOG")
today = ""
sqlClause = [None, "ORDER BY SAVEREST DESC"]
with arcpy.da.SearchCursor(tbl, ['SAVEREST'], sql_clause=sqlClause) as cur:
for rec in cur:
#lastDate = rec[0].split(" ")[0].replace("-", "")
lastDate = rec[0].strftime('%Y%m%d')
break
return lastDate
except MyError, e:
# Example: raise MyError("this is an error message")
PrintMsg(str(e) + " \n", 2)
return ""
except:
errorMsg()
return ""
## ===================================================================================
def CreateQueryTables(inputDB, outputDB, maxD):
#
try:
env.workspace = inputDB
queryMU = "MU"
queryCO = "CO"
queryHZ = "HZ"
queryCR = "CR"
queryCT = "CT"
queryTemp = "Tmp" # empty table uses as template
# Create an empty table using the original queryHZ as a template
# MAPUNIT TABLE
#
PrintMsg(" \n\tReading MAPUNIT table...", 0)
whereClause = ""
fldMu = [["mukey", "mukey"], ["musym", "musym"], ["muname", "muname"]]
fldMu2 = list()
dMu = dict()
sqlClause = (None, "ORDER BY mukey")
for fld in fldMu:
fldMu2.append(fld[0])
muList = list()
muTbl = os.path.join(inputDB, "mapunit")
with arcpy.da.SearchCursor(muTbl, fldMu2, sql_clause=sqlClause) as mcur:
for mrec in mcur:
rec = list(mrec)
mukey = rec[0]
#mukey = int(rec[0])
rec.pop(0)
dMu[mukey] = rec
muList.append(mukey)
muList.sort()
del muTbl
# COMPONENT TABLE
#
PrintMsg(" \n\tReading COMPONENT table...", 0)
fldCo = [["mukey", "mukey"], ["cokey", "cokey"], ["comppct_r", "comppct_r"], ["majcompflag", "majcompflag"], \
["compname", "compname"], ["compkind", "compkind"], ["taxorder", "taxorder"], ["taxsubgrp", "taxsubgrp"], \
["localphase", "localphase"], ["otherph", "otherph"], ["hydricrating", "hydricrating"], ["drainagecl", "drainagecl"]]
fldCo2 = list()
dCo = dict()
whereClause = "comppct_r is not NULL"
sqlClause = (None, "ORDER BY cokey, comppct_r DESC")
coTbl = os.path.join(inputDB, "component")
for fld in fldCo:
fldCo2.append(fld[0])
with arcpy.da.SearchCursor(coTbl, fldCo2, where_clause=whereClause, sql_clause=sqlClause) as ccur:
for crec in ccur:
rec = list(crec)
mukey = rec.pop(0) # get rid of mukey from component record
try:
# Add next component record to list
dCo[mukey].append(rec)
except:
# initialize list of records
dCo[mukey] = [rec]
del coTbl
# HORIZON TABLE
#
PrintMsg(" \n\tReading HORIZON table...", 0)
fldHz = [["cokey", "cokey"], ["chkey", "chkey"], ["hzname", "hzname"], ["desgnmaster", "desgnmaster"], \
["hzdept_r", "hzdept_r"], ["hzdepb_r", "hzdepb_r"], ["sandtotal_r", "sandtotal_r"], \
["silttotal_r", "silttotal_r"], ["claytotal_r", "claytotal_r"], ["om_r", "om_r"], \
["dbthirdbar_r", "dbthirdbar_r"], ["ec_r", "ec_r"], ["ph1to1h2o_r", "ph1to1h2o_r"], \
["awc_r", "awc_r"]]
fldHz2 = list()
dHz = dict()
whereClause = "hzdept_r is not NULL and hzdepb_r is not NULL"
sqlClause = (None, "ORDER BY chkey, hzdept_r ASC")
for fld in fldHz:
fldHz2.append(fld[0])
hzTbl = os.path.join(inputDB, "chorizon")
with arcpy.da.SearchCursor(hzTbl, fldHz2, where_clause=whereClause, sql_clause=sqlClause) as hcur:
for hrec in hcur:
rec = list(hrec)
cokey = rec.pop(0)
try:
# Add next horizon record to list
dHz[cokey].append(rec)
except:
# initialize list of horizon records
dHz[cokey] = [rec]
del hzTbl
# HORIZON TEXTURE
#
#PrintMsg(" \n\tMaking query table (CT) for texture information", 0)
inputTbls = list()
tbls = ["chtexturegrp", "chtexture"]
for tbl in tbls:
inputTbls.append(os.path.join(inputDB, tbl))
txList1 = [["chtexturegrp.chkey", "chkey"], ["chtexturegrp.texture", "texture"], ["chtexture.lieutex", "lieutex"]]
whereClause = "chtexturegrp.chtgkey = chtexture.chtgkey and chtexturegrp.rvindicator = 'Yes'"
arcpy.MakeQueryTable_management(inputTbls, queryCT, "USE_KEY_FIELDS", "#", txList1, whereClause)
# Try to overcome memory error by copying this query table to disk
textureTbl = os.path.join(env.scratchGDB, "HzTexture")
arcpy.TableToTable_conversion(queryCT, os.path.dirname(textureTbl), os.path.basename(textureTbl))
arcpy.Delete_management(queryCT)
del queryCT
#raise MyError, "EARLY OUT"
# Read texture query into dictionary
#txList2 = ["chtexturegrp.chkey", "chtexturegrp.texture", "chtexture.lieutex"]
txList2 = ["chkey", "texture", "lieutex"]
dTexture = dict()
ctCnt = int(arcpy.GetCount_management(textureTbl).getOutput(0))
arcpy.SetProgressor ("step", "Getting horizon texture information for QueryTable_HZ...", 0, ctCnt, 1)
# Have been running out of memory here if other applications are running. 5.66GB
lieuList = ['Slightly decomposed plant material', 'Moderately decomposed plant material', \
'Highly decomposed plant material', 'Undecomposed plant material', 'Muck', 'Mucky peat', \
'Peat', 'Coprogenous earth']
txList = ["CE", "COP-MAT", "HPM", "MPM", "MPT", "MUCK", "PDOM", "PEAT", "SPM", "UDOM"]
#cnt = 0
with arcpy.da.SearchCursor(textureTbl, txList2) as cur:
for rec in cur:
if (rec[1] in txList or rec[2] in lieuList):
#cnt +=1
#arcpy.SetProgressorLabel(str(cnt))
dTexture[rec[0]] = [rec[1], rec[2]]
arcpy.SetProgressorPosition()
arcpy.Delete_management(textureTbl)
del textureTbl
# COMPONENT RESTRICTIONS which will be saved to a gdb table
#
if arcpy.Exists(os.path.join(outputDB, "QueryTable_CR")):
arcpy.Delete_management(os.path.join(outputDB, "QueryTable_CR"))
crTbl = os.path.join(inputDB, "corestrictions")
#PrintMsg(" \n\tReading component restriction data...", 0)
fldCr = [["cokey", "cokey"], \
["reskind", "reskind"],\
["reshard", "reshard"],\
["resdept_r", "resdept_r"]]
whereClause = "OBJECTID = 1"
arcpy.MakeQueryTable_management(crTbl, queryCR, "USE_KEY_FIELDS", "#", fldCr, whereClause)
arcpy.CreateTable_management(outputDB, "QueryTable_CR", queryCR)
arcpy.Delete_management(queryCR)
del queryCR
fldCr2 = list()
dCr = dict()
sqlClause = (None, "ORDER BY cokey, resdept_r ASC")
for fld in fldCr:
fldCr2.append(fld[0])
whereClause = "resdept_r is not NULL and resdept_r < " + str(maxD)
outputCR = os.path.join(outputDB, "QueryTable_CR")
crList = list() # list of components with a restriction
crCnt = int(arcpy.GetCount_management(crTbl).getOutput(0))
arcpy.SetProgressor ("step", "Saving component restriction information...", 0, crCnt, 1)
with arcpy.da.SearchCursor(crTbl, fldCr2, where_clause=whereClause, sql_clause=sqlClause) as crcur:
for crrec in crcur:
rec = list(crrec)
cokey = rec[0]
arcpy.SetProgressorPosition()
if not cokey in crList:
# Only save the highest level restriction above 150cm
crList.append(cokey)
dCr[cokey] = rec
#PrintMsg(" \n\tCreating QueryTable_HZ in " + outputDB, 0)
fldCo.pop(0)
fldCo2.pop(0)
fldHz.pop(0)
fldHz2.pop(0)
# Create list of fields for query table
fldAll = list()
# Create list of fields for output cursor
fldAll2 = list()
for fld in fldMu:
fldAll.append(["mapunit." + fld[0], fld[1]])
fldAll2.append(fld[1])
for fld in fldCo:
fldAll.append(["component." + fld[0], fld[1]])
fldAll2.append(fld[1])
for fld in fldHz:
fldAll.append(["chorizon." + fld[0], fld[1]])
fldAll2.append(fld[1])
# Texture fields:
fldAll2.append("texture")
fldAll2.append("lieutex")
# Select component-horizon data for ALL components that have horizon data. Lack of horizon data
# will cause some components to be missing from the PWSL.
#
# Later on in the actual calculations for RZAWS, only the major-earthy components will be used. But
# all components are in this table!
whereClause = "mapunit.mukey = component.mukey and \
component.cokey = chorizon.cokey and mapunit.objectid = 1"
outputTable = os.path.join(outputDB, "QueryTable_HZ")
PrintMsg(" \nCreating table " + outputTable, 0)
if arcpy.Exists(os.path.join(outputDB, "QueryTable_HZ")):
arcpy.Delete_management(os.path.join(outputDB, "QueryTable_HZ"))
arcpy.MakeQueryTable_management(['mapunit', 'component', 'chorizon'], queryTemp, "USE_KEY_FIELDS", "#", fldAll, whereClause)
arcpy.CreateTable_management(outputDB, "QueryTable_HZ", queryTemp)
arcpy.AddField_management(outputTable, "texture", "TEXT", "", "", "30", "texture")
arcpy.AddField_management(outputTable, "lieutex", "TEXT", "", "", "254", "lieutex")
arcpy.Delete_management(queryTemp)
del queryTemp
# Process dictionaries and use themtextureTbl to write out the new QueryTable_HZ table
#
# Open output table
#if arcpy.Exist(theMuTable):
# arcpy.Delete_management(theMuTable)
outFld2 = arcpy.Describe(outputTable).fields
outFlds = list()
for fld in outFld2:
outFlds.append(fld.name)
outFlds.pop(0)
# Create empty lists to replace missing data
missingCo = ["", None, None, None, None, None, None, None, None, None, None]
missingHz = ["", None, None, None, None, None, None, None, None, None, None, None, None]
missingTx = [None, None]
# Save information on mapunits or components with bad or missing data
#badMu = list() # list of mapunits with no components
muNoCo = list()
dNoCo = dict()
coNoHz = list() # list of components with no horizons
dNoHz = dict() # component data for those components in coNoHz
arcpy.SetProgressor ("step", "Writing data to " + outputTable + "...", 0, len(muList), 1)
with arcpy.da.InsertCursor(outputTable, fldAll2) as ocur:
for mukey in muList:
mrec = dMu[mukey]
arcpy.SetProgressorPosition()
try:
coVals = dCo[mukey] # got component records for this mapunit
# Sort lists by comppct_r
coList = sorted(coVals, key = lambda x: int(x[1]))
for corec in coList:
cokey = corec[0]
try:
hzVals = dHz[cokey] # horizon records for this component
# Sort record by hzdept_r
hzList = sorted(hzVals, key = lambda x: int(x[3]))
for hzrec in hzList:
chkey = hzrec[0]
try:
# Get horizon texture
txrec = dTexture[chkey]
except:
txrec = missingTx
# Combine all records and write to table
newrec = [mukey]
newrec.extend(mrec)
newrec.extend(corec)
newrec.extend(hzrec)
newrec.extend(txrec)
ocur.insertRow(newrec)
except KeyError:
# No horizon records for this component
comppct = corec[1]
compname = corec[3]
compkind = corec[4]
mjrcomp = corec[2]
#PrintMsg("Major compflag = " + str(corec), 1)
hzrec = missingHz
txrec = missingTx
newrec = [mukey]
newrec.extend(mrec)
newrec.extend(corec)
newrec.extend(hzrec)
newrec.extend(txrec)
ocur.insertRow(newrec)
if not (compname in ["NOTCOM", "NOTPUB"] or compkind == 'Miscellaneous area'):
badComp = [mukey, str(cokey), compname, compkind, mjrcomp, str(comppct)]
coNoHz.append(str(cokey)) # add cokey to list of components with no horizon data
dNoHz[cokey] = badComp # add component information to dictionary
#PrintMsg(" \nMissing horizon data: " + str(corec), 1)
except:
PrintMsg(" \nhzVals error for " + str(mukey) + ":" + str(cokey) + ": " + str(txrec), 2)
PrintMsg(" \n" + str(fldAll2), 1)
errorMsg()
except:
# No component records for this map unit
corec = missingCo
hzrec = missingHz
txrec = missingTx
newrec = [mukey]
newrec.extend(mrec)
newrec.extend(corec)
newrec.extend(hzrec)
newrec.extend(txrec)
ocur.insertRow(newrec)
if not mrec[0] in ['NOTCOM', 'NOTPUB']:
# skip map units that should never have component data
#
muNoCo.append(str(mukey))
dNoCo[str(mukey)] = [mrec[0], mrec[1]] # Save map unit name for the report
#PrintMsg(" \n\n** No component data for " + str(mrec[1]), 2)
del dMu, dCo
# Run through QueryTbl_HZ table, checking for inconsistencies in horizon depths
# Create a dictionary containing a list of top and bottom of each horizon in each component
# dictionary key = cokey
# list contains tuples of hzdept_r, hzdepb_r, hzname, mukey, compname, localphase
dHZ = dict()
# Exclude horizon data with null hzdep with whereclause
wc = "hzdept_r is not null and hzdepb_r is not null"
arcpy.ResetProgressor()
arcpy.SetProgressorLabel("Looking for inconsistencies in horizon depths...")
#PrintMsg(" \nWriting component restrictions to " + outputCR, 0)
arcpy.SetProgressor ("step", "Writing component restriction data to " + outputCR + "...", 0, len(dCr), 1)
with arcpy.da.InsertCursor(outputCR, fldCr2) as ocur:
for cokey, crrec in dCr.items():
ocur.insertRow(crrec)
env.workspace = outputDB
del dCr
return True
except MyError, e:
# Example: raise MyError("this is an error message")
PrintMsg(str(e) + " \n", 2)
return False
except:
errorMsg()
return False
## ===================================================================================
def CreateOutputTableMu(theMuTable, depthList, dPct):
# Create the Valu1 table (theMuTable). Probably should rename this variable.
#
try:
# Create the output tables and add required fields
try:
# Try to handle existing output table if user has added it to ArcMap from a previous run
if arcpy.Exists(theMuTable):
arcpy.Delete_management(theMuTable)
except:
raise MyError, "Previous output table (" + theMuTable + ") is in use and cannot be removed"
return False
#PrintMsg(" \nCreating new output table (" + os.path.basename(theMuTable) + ") for mapunit level data", 0)
outputDB = os.path.dirname(theMuTable)
tmpTable = os.path.join("IN_MEMORY", os.path.basename(theMuTable))
#arcpy.CreateTable_management(outputDB, os.path.basename(theMuTable))
arcpy.CreateTable_management("IN_MEMORY", os.path.basename(theMuTable))
# Add fields for AWS
for rng in depthList:
# Create the AWS fields in a loop
#
td = rng[0]
bd = rng[1]
awsField = "aws" + str(td) + "_" + str(bd)
arcpy.AddField_management(tmpTable, awsField, "FLOAT", "", "", "", awsField) # Integer is more appropriate
for rng in depthList:
# Create the AWS fields in a loop
#
td = rng[0]
bd = rng[1]
awsField = "tk" + str(td) + "_" + str(bd) + "a"
arcpy.AddField_management(tmpTable, awsField, "FLOAT", "", "", "", awsField)
arcpy.AddField_management(tmpTable, "musumcpcta", "SHORT", "", "", "")
# Add Fields for SOC
for rng in depthList:
# Create the SOC fields in a loop
#
td = rng[0]
bd = rng[1]
socField = "soc" + str(td) + "_" + str(bd)
arcpy.AddField_management(tmpTable, socField, "FLOAT", "", "", "", socField) # Integer is more appropriate
for rng in depthList:
# Create the SOC thickness fields in a loop
#
td = rng[0]
bd = rng[1]
socField = "tk" + str(td) + "_" + str(bd) + "s"
arcpy.AddField_management(tmpTable, socField, "FLOAT", "", "", "", socField)
arcpy.AddField_management(tmpTable, "musumcpcts", "SHORT", "", "", "")
if mainRuleName == "NCCPI - National Commodity Crop Productivity Index (Ver 2.0)":
# Add fields for NCCPI version 2
#
arcpy.AddField_management(tmpTable, "nccpi2cs", "FLOAT", "", "", "")
arcpy.AddField_management(tmpTable, "nccpi2sg", "FLOAT", "", "", "")
arcpy.AddField_management(tmpTable, "nccpi2co", "FLOAT", "", "", "")
arcpy.AddField_management(tmpTable, "nccpi2all", "FLOAT", "", "", "")
elif mainRuleName == "NCCPI - National Commodity Crop Productivity Index (Ver 3.0)":
# Add fields for NCCPI version 3
# "mukey", "NCCPI2CORN", "NCCPI2SOY", "NCCPI2COT","NCCPI2SG", "NCCPI2ALL"
arcpy.AddField_management(tmpTable, "nccpi3corn", "FLOAT", "", "", "")
arcpy.AddField_management(tmpTable, "nccpi3soy", "FLOAT", "", "", "")
arcpy.AddField_management(tmpTable, "nccpi3cot", "FLOAT", "", "", "")
arcpy.AddField_management(tmpTable, "nccpi3sg", "FLOAT", "", "", "")
arcpy.AddField_management(tmpTable, "nccpi3all", "FLOAT", "", "", "")
else:
#PrintMsg(" \n\tNeither NCCPI version 2 or 3 not found", 1)
raise MyError, "Problem handling mainrule: " + mainRuleName
# Add fields for root zone depth and root zone available water supply
arcpy.AddField_management(tmpTable, "pctearthmc", "SHORT", "", "", "")
arcpy.AddField_management(tmpTable, "rootznemc", "SHORT", "", "", "")
arcpy.AddField_management(tmpTable, "rootznaws", "SHORT", "", "", "")
# Add field for droughty soils
arcpy.AddField_management(tmpTable, "droughty", "SHORT", "", "", "")
# Add field for potential wetland soils
arcpy.AddField_management(tmpTable, "pwsl1pomu", "SHORT", "", "", "")
# Add field for mapunit-sum of ALL component-comppct_r values
arcpy.AddField_management(tmpTable, "musumcpct", "SHORT", "", "", "")
# Add Mukey field (primary key)
arcpy.AddField_management(tmpTable, "mukey", "TEXT", "", "", "30", "mukey")
# Convert IN_MEMORY table to a permanent table
arcpy.CreateTable_management(outputDB, os.path.basename(theMuTable), tmpTable)
# Add attribute indexes for key fields
arcpy.AddIndex_management(theMuTable, "MUKEY", "Indx_ResMukey", "NON_UNIQUE", "NON_ASCENDING")
arcpy.Delete_management(os.path.join("IN_MEMORY", os.path.basename(theMuTable)))
# Reading from the original mapunit table, populate the output Valu1 table with mukey and musumpct
#PrintMsg(" \n\tPopulating " + theMuTable + " with mukey values", 1)
with arcpy.da.SearchCursor(os.path.join(outputDB, "mapunit"), ["mukey"]) as incur:
outcur = arcpy.da.InsertCursor(theMuTable, ["mukey", "musumcpct"])
for inrec in incur:
mukey = inrec[0]
try:
sumPct = dPct[mukey][0]
except:
sumPct = 0
inrec = [mukey, sumPct]
outcur.insertRow(inrec)
return True
except MyError, e:
# Example: raise MyError("this is an error message")
PrintMsg(str(e) + " \n", 2)
return False
except:
errorMsg()
return False
## ===================================================================================
def CreateOutputTableCo(theCompTable, depthList):
# Create the Co_Valu component level table (theCompTable). Probably should rename that variable.
# The new input field is created using adaptive code from another script.
#
try:
# Create two output tables and add required fields
try:
# Try to handle existing output table if user has added it to ArcMap from a previous run
if arcpy.Exists(theCompTable):
arcpy.Delete_management(theCompTable)
except:
raise MyError, "Previous output table (" + theCompTable + ") is in use and cannot be removed"
return False
#PrintMsg(" \nCreating new output table (" + os.path.basename(theCompTable) + ") for component level data", 0)
outputDB = os.path.dirname(theCompTable)
tmpTable = os.path.join("IN_MEMORY", os.path.basename(theCompTable))
arcpy.CreateTable_management("IN_MEMORY", os.path.basename(theCompTable))
# Add fields appropriate for the component level restrictions
# mukey,cokey, compName, localphase, compPct, comppct, resdept, restriction
arcpy.AddField_management(tmpTable, "COKEY", "TEXT", "", "", "30", "COKEY")
arcpy.AddField_management(tmpTable, "COMPNAME", "TEXT", "", "", "60", "COMPNAME")
arcpy.AddField_management(tmpTable, "LOCALPHASE", "TEXT", "", "", "40", "LOCALPHASE")
arcpy.AddField_management(tmpTable, "COMPPCT_R", "SHORT", "", "", "", "COMPPCT_R")
for rng in depthList:
# Create the AWS fields in a loop
#
td = rng[0]
bd = rng[1]
awsField = "AWS" + str(td) + "_" + str(bd)
arcpy.AddField_management(tmpTable, awsField, "FLOAT", "", "", "", awsField)
for rng in depthList:
# Create the AWS fields in a loop
#
td = rng[0]
bd = rng[1]
awsField = "TK" + str(td) + "_" + str(bd) + "A"
arcpy.AddField_management(tmpTable, awsField, "FLOAT", "", "", "", awsField)
arcpy.AddField_management(tmpTable, "MUSUMCPCTA", "SHORT", "", "", "")
for rng in depthList:
# Create the SOC fields in a loop
#
td = rng[0]
bd = rng[1]
awsField = "SOC" + str(td) + "_" + str(bd)
arcpy.AddField_management(tmpTable, awsField, "FLOAT", "", "", "")
for rng in depthList:
# Create the rest of the SOC thickness fields in a loop
#
td = rng[0]
bd = rng[1]
awsField = "TK" + str(td) + "_" + str(bd) + "S"
arcpy.AddField_management(tmpTable, awsField, "FLOAT", "", "", "")
arcpy.AddField_management(tmpTable, "MUSUMCPCTS", "SHORT", "", "", "")
# Root Zone and root zone available water supply
arcpy.AddField_management(tmpTable, "PCTEARTHMC", "SHORT", "", "", "")
arcpy.AddField_management(tmpTable, "ROOTZNEMC", "SHORT", "", "", "")
arcpy.AddField_management(tmpTable, "ROOTZNAWS", "SHORT", "", "", "")
arcpy.AddField_management(tmpTable, "RESTRICTION", "TEXT", "", "", "254", "RESTRICTION")
# Droughty soils
arcpy.AddField_management(tmpTable, "DROUGHTY", "SHORT", "", "", "")
# Add field for potential wetland soils
arcpy.AddField_management(tmpTable, "PWSL1POMU", "SHORT", "", "", "")
# Add primary key field
arcpy.AddField_management(tmpTable, "MUKEY", "TEXT", "", "", "30", "MUKEY")
# Convert IN_MEMORY table to a permanent table
if arcpy.Exists(os.path.join(outputDB, os.path.basename(theCompTable))):
arcpy.Delete_management(os.path.join(outputDB, os.path.basename(theCompTable)))
arcpy.CreateTable_management(outputDB, os.path.basename(theCompTable), tmpTable)
# add attribute indexes for key fields
arcpy.AddIndex_management(theCompTable, "MUKEY", "Indx_Res2Mukey", "NON_UNIQUE", "NON_ASCENDING")
arcpy.AddIndex_management(theCompTable, "COKEY", "Indx_ResCokey", "UNIQUE", "NON_ASCENDING")
# populate table with mukey values
#PrintMsg(" \n\tPopulating " + theCompTable + " with basic component values", 1)
with arcpy.da.SearchCursor(os.path.join(outputDB, "component"), ["mukey", "cokey", "compname", "localphase", "comppct_r"]) as incur:
outcur = arcpy.da.InsertCursor(theCompTable, ["mukey", "cokey", "compname", "localphase", "comppct_r"])
for inrec in incur:
outcur.insertRow(inrec)
except MyError, e:
# Example: raise MyError("this is an error message")
PrintMsg(str(e) + " \n", 2)
return False
except:
errorMsg()
return False
## ===================================================================================
def CheckTexture(mukey, cokey, desgnmaster, om, texture, lieutex, taxorder, taxsubgrp):
# Is this an organic horizon? Look at desgnmaster and OM first. If those
# don't help, look at chtexturegrp.texture next.
#
# if True: Organic, exclude from root zone calculations unless it is 'buried'
# if False: Mineral, include in root zone calculations
#
# 01-26-2015
#
# According to Bob, if TAXORDER = 'Histosol' and DESGNMASTER = 'O' or 'L' then it should NOT be included in the RZAWS calculations
#
# If desgnmast = 'O' or 'L' and not (TAXORDER = 'Histosol' OR TAXSUBGRP like 'Histic%') then exclude this horizon from all RZAWS calcualtions.
#
# lieutex values: Slightly decomposed plant material, Moderately decomposed plant material,
# Bedrock, Variable, Peat, Material, Unweathered bedrock, Sand and gravel, Mucky peat, Muck,
# Highly decomposed plant material, Weathered bedrock, Cemented, Gravel, Water, Cobbles,
# Stones, Channers, Parachanners, Indurated, Cinders, Duripan, Fragmental material, Paragravel,
# Artifacts, Boulders, Marl, Flagstones, Coprogenous earth, Ashy, Gypsiferous material,
# Petrocalcic, Paracobbles, Diatomaceous earth, Fine gypsum material, Undecomposed organic matter
# According to Bob, any of these 'decomposed plant material', 'Muck, 'Mucky peat, 'Peat', 'Coprogenous earth' LIEUTEX
# values qualify.
#
# This function does not determine whether the horizon might be a buried organic. That is done in CalcRZAWS1.
#
lieuList = ['Slightly decomposed plant material', 'Moderately decomposed plant material', \
'Highly decomposed plant material', 'Undecomposed plant material', 'Muck', 'Mucky peat', \
'Peat', 'Coprogenous earth']
txList = ["CE", "COP-MAT", "HPM", "MPM", "MPT", "MUCK", "PDOM", "PEAT", "SPM", "UDOM"]
try:
if str(taxorder) == 'Histosols' or str(taxsubgrp).lower().find('histic') >= 0:
# Always treat histisols and histic components as having all mineral horizons
#if mukey == tmukey:
# PrintMsg("\tHistisol or histic: " + cokey + ", " + str(taxorder) + ", " + str(taxsubgrp), 1)
return False
elif desgnmaster in ["O", "L"]:
# This is an organic horizon according to CHORIZON.DESGNMASTER OR OM_R
#if mukey == tmukey:
# PrintMsg("\tO: " + cokey + ", " + str(taxorder) + ", " + str(taxsubgrp), 1)
return True
#elif om > 19:
# This is an organic horizon according to CHORIZON.DESGNMASTER OR OM_R
# if mukey == tmukey:
# PrintMsg("\tHigh om_r: " + cokey + ", " + str(taxorder) + ", " + str(taxsubgrp), 1)
# return True
elif str(texture) in txList:
# This is an organic horizon according to CHTEXTUREGRP.TEXTURE
#if mukey == tmukey:
# PrintMsg("\tTexture: " + cokey + ", " + str(taxorder) + ", " + str(taxsubgrp), 1)
return True
elif str(lieutex) in lieuList:
# This is an organic horizon according to CHTEXTURE.LIEUTEX
#if mukey == tmukey:
# PrintMsg("\tLieutex: " + cokey + ", " + str(taxorder) + ", " + str(taxsubgrp), 1)
return True
else:
# Default to mineral horizon if it doesn't match any of the criteria
#if mukey == tmukey:
# PrintMsg("\tDefault mineral: " + cokey + ", " + str(taxorder) + ", " + str(taxsubgrp), 1)
return False
except MyError, e:
# Example: raise MyError("this is an error message")
PrintMsg(str(e) + " \n", 2)
return False
except:
errorMsg()
return False
## ===================================================================================
def CheckBulkDensity(sand, silt, clay, bd, mukey, cokey):
# Bob's check for a dense layer
# If sand, silt or clay are missing then we default to Dense layer = False
# If the sum of sand, silt, clay are less than 100 then we default to Dense layer = False
# If a single sand, silt or clay value is NULL, calculate it
try:
#if mukey == tmukey:
# PrintMsg("\tCheck for Dense: " + str(mukey) + ", " + str(cokey) + ", " + \
# str(sand) + ", " + str(silt) + ", " + str(clay) + ", " + str(bd), 1)
txlist = [sand, silt, clay]
if bd is None:
# This is not a Dense Layer
#if mukey == tmukey:
# PrintMsg("\tMissing bulk density", 1)
return False
if txlist.count(None) == 1:
# Missing a single total_r value, calculate it
if txlist[0] is None:
sand = 100.0 - silt - clay
elif silt is None:
silt = 100.0 - sand - clay
else:
clay = 100.0 - sand - silt
txlist = [sand, silt, clay]
if txlist.count(None) > 0:
# Null values for more than one, return False
#if mukey == tmukey:
# PrintMsg("\tDense layer with too many null texture values", 1)
return False
if round(sum(txlist), 1) <> 100.0:
# Cannot run calculation, default value is False
#if mukey == tmukey:
# PrintMsg("\tTexture values do not sum to 100", 1)
return False
# All values required to run the Dense Layer calculation are available
a = bd - ((( sand * 1.65 ) / 100.0 ) + (( silt * 1.30 ) / 100.0 ) + (( clay * 1.25 ) / 100.0))
b = ( 0.002081 * sand ) + ( 0.003912 * silt ) + ( 0.0024351 * clay )
if a > b:
# This is a Dense Layer
#if mukey == tmukey:
# PrintMsg("\tDense layer: a = " + str(a) + " and b = " + str(b) + " and BD = " + str(bd), 1)
return True
else:
# This is not a Dense Layer
#if mukey == tmukey:
# PrintMsg("\tNot a Dense layer: a = " + str(a) + " and b = " + str(b) + " and BD = " + str(bd), 1)
return False
except MyError, e:
# Example: raise MyError("this is an error message")
PrintMsg(str(e) + " \n", 2)
return False
except:
errorMsg()
return False
## ===================================================================================
def CalcRZDepth(inputDB, outputDB, theCompTable, theMuTable, maxD, dPct, dCR):
#
# Look at soil horizon properties to adjust the root zone depth.
# This is in addition to the standard component restrictions
#
# Read the component restrictions into a dictionary, then read through the
# QueryTable_Hz table, calculating the final component rootzone depth
#
# Components with COMPKIND = 'Miscellaneous area' or NULL are filtered out.
# Components with no horizon data are assigned a root zone depth of zero.
#
# Horizons with NULL hzdept_r or hzdepb_r are filtered out
# Horizons with hzdept_r => hzdepb_r are filtered out
# O horizons or organic horizons from the surface down to the first mineral horizon
# are filtered out.
#
# Horizon data below 150cm or select component restrictions are filtered out.
# A Dense layer calculation is also included as an additional horizon-specific restriction.
try:
dComp = dict() # component level data for all component restrictions
dComp2 = dict() # store all component level data plus default values
coList = list()
#bInput = CreateQueryTables1(inputDB, outputDB)
queryTbl = os.path.join(outputDB, "QueryTable_Hz")
#if bInput == False:
# raise MyError, "Problem querying input database"
#PrintMsg(" \nProcessing input table (" + queryTbl + ")")
# Create dictionaries and lists
dMapunit = dict() # store mapunit weighted restriction depths
# FIELDS LIST FOR INPUT TABLE
# areasymbol, mukey, musym, muname, mukname,
# cokey, compct, compname, compkind, localphase,
# taxorder, taxsubgrp, ec, pH, dbthirdbar, hzname,
# hzdesgn, hzdept, hzdepb, hzthk, sand,
# silt, clay, om, reskind, reshard,
# resdept, resthk, texture, lieutex
# All reskind values: Strongly contrasting textural stratification, Lithic bedrock, Densic material,
# Ortstein, Permafrost, Paralithic bedrock, Cemented horizon, Undefined, Fragipan, Plinthite,
# Abrupt textural change, Natric, Petrocalcic, Duripan, Densic bedrock, Salic,
# Human-manufactured materials, Sulfuric, Placic, Petroferric, Petrogypsic
#
# Using these restrictions:
# Lithic bedrock, Paralithic bedrock, Densic bedrock, Fragipan, Duripan, Sulfuric
# Other restrictions include pH < 3.5 and EC > 16
resTbl = os.path.join(outputDB, "QueryTable_CR")
crFlds = ["cokey","reskind", "reshard", "resdept_r"]
sqlClause = (None, "ORDER BY cokey, resdept_r ASC")
# ********************************************************
#
# Read the QueryTable_HZ and adjust the component restrictions for additional
# issues such as pH, EC, etc.
#
# Save these new restriction values to dComp dictionary
#
# Only process major-earthy components...
whereClause = "component.compkind <> 'Miscellaneous area' and component.compkind is not Null and component.majcompflag = 'Yes'"
sqlClause = (None, "ORDER BY mukey, comppct_r DESC, cokey, hzdept_r ASC")
curFlds = ["mukey", "cokey", "compname", "compkind", "localphase", "comppct_r", "taxorder", "taxsubgrp", "hzname", "desgnmaster", "hzdept_r", "hzdepb_r", "sandtotal_r", "silttotal_r", "claytotal_r", "om_r", "dbthirdbar_r", "ph1to1h2o_r", "ec_r", "awc_r", "texture", "lieutex"]
resList = ['Lithic bedrock','Paralithic bedrock','Densic bedrock', 'Fragipan', 'Duripan', 'Sulfuric']
lastCokey = "xxxx"
lastMukey = 'xxxx'
# Display status of processing input table containing horizon data and component restrictions
inCnt = int(arcpy.GetCount_management(queryTbl).getOutput(0))
if inCnt > 0:
arcpy.SetProgressor ("step", "Processing input table...", 0, inCnt, 1)
else:
raise MyError, "Input table contains no data"
with arcpy.da.SearchCursor(queryTbl, curFlds, where_clause=whereClause, sql_clause=sqlClause) as cur:
# Reading horizon-level data
for rec in cur:
# ********************************************************
#
# Read QueryTable_HZ record
mukey, cokey, compName, compKind, localPhase, compPct, taxorder, taxsubgrp, hzname, desgnmaster, hzDept, hzDepb, sand, silt, clay, om, bd, pH, ec, awc, texture, lieutex = rec
# Initialize component restriction depth to maxD
dComp2[cokey] = [mukey, compName, localPhase, compPct, maxD, ""]
if lastCokey != cokey:
# Accumulate a list of components for future use
lastCokey = cokey
coList.append(cokey)
if hzDept < maxD:
# ********************************************************
# For horizons above the floor level (maxD), look for other restrictive
# layers based on horizon properties such as pH, EC and bulk density.
# Start with the top horizons and work down.