-
Notifications
You must be signed in to change notification settings - Fork 1
/
DBUtils.py.cs
2012 lines (1886 loc) · 90.1 KB
/
DBUtils.py.cs
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
using System.Collections.Generic;
using System;
using System.Data;
using System.Data.Common;
using System.Data.OleDb;
using System.Data.SQLite;
using System.IO;
using System.Linq;
using System.Diagnostics;
using System.Security.Cryptography;
using System.Runtime.CompilerServices;
using System.Windows.Forms;
namespace ArcSWAT3
{
// Functions for interacting with project and reference databases.
public class DBUtils {
public List<string> _allTableNames;
public string _connRefStr;
public string _connStr;
public Dictionary<int, int> _landuseIDCs;
public Dictionary<int, int> _landuseTranslate;
public List<int> _undefinedLanduseIds;
public List<int> _undefinedSoilIds;
public bool useSQLite;
public DbConnection conn;
public DbConnection connRef;
public string dbFile;
public string dbRefFile;
public int defaultLanduse;
public string defaultLanduseCode;
public int defaultSoil;
public string defaultSoilName;
public bool forTNC;
public bool isBatch;
public bool isHAWQS;
public bool isHUC;
public Dictionary<int, string> landuseCodes;
public bool landuseErrorReported;
public Dictionary<int, int> landuseIds;
public Dictionary<int, double> landuseOVN;
public List<string> landuseTableNames;
public List<int> landuseVals;
public string logFile;
public string projDir;
public string projName;
public List<double> slopeLimits;
public Dictionary<int, string> soilNames;
public List<string> soilTableNames;
public Dictionary<int, int> soilTranslate;
public List<int> soilVals;
public DbConnection SSURGOConn;
public string SSURGODbFile;
public Dictionary<int, int> SSURGOSoils;
public int SSURGOUndefined;
public Dictionary<int, int> urbanIds;
public string usersoil;
public bool useSSURGO;
public bool useSTATSGO;
public string waterBodiesFile;
public DBUtils(
string projDir,
string projName,
string dbProjTemplate,
string dbRefTemplate,
bool isHUC,
bool isHAWQS,
bool forTNC,
string logFile,
bool isBatch) {
//# Flag showing if batch run
this.isBatch = isBatch;
//# flag for HUC projects
this.isHUC = isHUC;
//# flag for HAWQS projects
this.isHAWQS = isHAWQS;
//# flag for TNC projects
this.forTNC = forTNC;
//# message logging file for HUC projects
this.logFile = logFile;
// flag to use SQLite databases
this.useSQLite = false; // isHUC || isHAWQS || forTNC
//# project directory
this.projDir = projDir;
//# project name
this.projName = projName;
//# project database
var dbSuffix = Path.GetExtension(dbProjTemplate);
this.dbFile = this.useSQLite ? Utils.join(projDir, projName + ".sqlite") : Utils.join(projDir, projName + dbSuffix);
if (forTNC && !File.Exists(this.dbFile)) {
File.Copy(dbProjTemplate, this.dbFile);
}
if (!(this.useSQLite)) {
this._connStr = Parameters._ACCESSSTRING + this.dbFile;
// copy template project database to project folder if not already there
if (!File.Exists(this.dbFile)) {
File.Copy(dbProjTemplate, this.dbFile);
}
//else {
// this.updateProjDb(Parameters._SWATEDITORVERSION);
//}
}
//# reference database
var dbRefName = this.useSQLite ? "QSWATRef2012.sqlite" : Parameters._DBREF;
this.dbRefFile = Utils.join(projDir, dbRefName);
if (this.useSQLite) {
if (isHUC && !File.Exists(this.dbRefFile)) {
// look one up from project directory for reference database, so allowing it to be shared
this.dbRefFile = Utils.join(projDir + "/..", dbRefName);
} else if (!File.Exists(this.dbRefFile)) {
File.Copy(dbRefTemplate, this.dbRefFile);
}
if (!File.Exists(this.dbRefFile)) {
Utils.error(String.Format("Failed to find reference database {0}", this.dbRefFile), this.isBatch);
return;
}
try {
this.connRef = new SQLiteConnection(String.Format("Data Source={0}", this.dbRefFile));
if (this.connRef is null) {
Utils.error(String.Format("Failed to connect to reference database {0}.", this.dbRefFile), this.isBatch);
}
}
catch (Exception ex) {
Utils.error(String.Format("Failed to connect to reference database {0}: {1}", this.dbRefFile, ex.Message), this.isBatch);
this.connRef = null;
}
} else {
this._connRefStr = Parameters._ACCESSSTRING + this.dbRefFile;
// copy template reference database to project folder if not already there
if (!File.Exists(this.dbRefFile)) {
File.Copy(dbRefTemplate, this.dbRefFile);
}
//# reference database connection
try {
this.connRef = new OleDbConnection(this._connRefStr);
if (this.connRef is null) {
Utils.error(String.Format("Failed to connect to reference database {0}", this.dbRefFile), this.isBatch);
}
//else {
// this.updateRefDb(Parameters._SWATEDITORVERSION, dbRefTemplate);
//}
} catch (Exception ex) {
Utils.error(String.Format("Failed to connect to reference database {0}: {1}", this.dbRefFile, ex.Message), this.isBatch);
this.connRef = null;
}
}
//# WaterBodies (HUC and HAWQS only)
this.waterBodiesFile = isHUC ? Utils.join(projDir + "/..", Parameters._WATERBODIES) : Utils.join(projDir, Parameters._WATERBODIES);
//# Tables in project database containing 'landuse'
this.landuseTableNames = new List<string>();
//# Tables in project database containing 'soil'
this.soilTableNames = new List<string>();
//# all tables names in project database
this._allTableNames = new List<string>();
//# map of landuse category to SWAT landuse code
this.landuseCodes = new Dictionary<int, string>();
//# Landuse categories may not translate 1-1 into SWAT codes.
//
// This map is used to map category ids into equivalent ids.
// Eg if we have [0 +> XXXX, 1 +> YYYY, 2 +> XXXX, 3 +> XXXX] then _landuseTranslate will be
// [2 +> 0, 3 +> 0] showing that 2 and 3 map to 0, and other categories are not changed.
// Only landuse categories 0 and 1 are then used to calculate HRUs, i.e. landuses 0, 2 and 3 will
// contribute to the same HRUs.
// There is an invariant that the domains of landuseCodes and _landuseTranslate are disjoint,
// and that the range of _landuseTranslate is a subset of the domain of landuseCodes.
this._landuseTranslate = new Dictionary<int, int>();
//# Map of landuse category to SWAT crop ids (as found in crop.dat,
// or 0 for urban)
//
// There is an invariant that the domains of landuseCodes and landuseIds are identical.
this.landuseIds = new Dictionary<int, int>();
//# List of undefined landuse categories. Retained so each is only reported once as an error in each run.
this._undefinedLanduseIds = new List<int>();
//# Map of landuse category to IDC value from crop table
// There is an invariant that the domains of landuseCodes and _landuseIDCs are identical.
this._landuseIDCs = new Dictionary<int, int>();
//# map of landuse categories to Mannings n value for overland flow (only used for HUC models)
// same domain as landuseCodes
this.landuseOVN = new Dictionary<int, double>();
//# Map of landuse category to SWAT urban ids (as found in urban.dat)
// There is an invariant that the domain of urbanIds is a subset of
// the domain of landuseIds, corresponding to those whose crop id is 0
this.urbanIds = new Dictionary<int, int>();
//# Sorted list of values occurring in landuse map
this.landuseVals = new List<int>();
//# Default landuse
//# Set to first landuse in lookup table or landuse with 0 landuse id and used to replace landuse nodata when using grid model
this.defaultLanduse = -1;
//# defaultLanduse code
this.defaultLanduseCode = "";
//# flag to prevent multiple landuse errors being reported as errors: subsequent ones in log
this.landuseErrorReported = false;
//# Map of soil id to soil name
this.soilNames = new Dictionary<int, string>();
//# Soil categories may not translate 1-1 into soils.
//
// This map is used to map category ids into equivalent ids.
// Eg if we have [0 +> XXXX, 1 +> YYYY, 2 +> XXXX, 3 +> XXXX] then soilTranslate will be
// [2 +> 0, 3 +> 0] showing that 2 and 3 map to 0, and other categories are not changed.
// Only soil ids 0 and 1 are then used to calculate HRUs, i.e. soils 0, 2 and 3 will
// contribute to the same HRUs.
// There is an invariant that the domains of soilNames and soilTranslate are disjoint,
// and that the range of soilTranslate is a subset of the domain of soilNames.
this.soilTranslate = new Dictionary<int, int>();
//# List of undefined soil identifiers. Retained so each is only reported once as an error in each run.
this._undefinedSoilIds = new List<int>();
//# Sorted list of values occurring in soil map
this.soilVals = new List<int>();
//# Default soil
//# Set to first soil in lookup table or soil with 0 soil id and used to replace soil nodata when using grid model
this.defaultSoil = -1;
//# name of defaultSoil
this.defaultSoilName = "";
//# name of usersoil table: can be changed for TNC projects
this.usersoil = "usersoil";
//# List of limits for slopes.
//
// A list [a,b] means slopes are in ranges [slopeMin,a), [a,b), [b,slopeMax]
// and these ranges would be indexed by slopes 0, 1 and 2.
this.slopeLimits = new List<double>();
//# flag indicating STATSGO soil data is being used
this.useSTATSGO = false;
//# flag indicating SSURGO or STATSGO2 soil data is being used
this.useSSURGO = false;
//# map of SSURGO map values to SSURGO MUID (only used with HUC)
this.SSURGOSoils = new Dictionary<int, int>();
//if (isHUC || isHAWQS) {
// //# SSURGO soil database (only used with HUC and HAWQS)
// if (isHUC) {
// // changed to use copy one up frpm projDir
// this.SSURGODbFile = Utils.join(this.projDir + "/..", Parameters._SSURGODB_HUC);
// } else {
// this.SSURGODbFile = Utils.join(Path.GetDirectoryName(dbRefTemplate), Parameters._SSURGODB_HUC);
// }
// this.SSURGOConn = new SQLiteConnection("Data Source=" + this.SSURGODbFile);
// this.SSURGOConn.Open();
//}
//# nodata value from soil map to replace undefined SSURGO soils (only used with HUC and HAWQS)
this.SSURGOUndefined = -1;
//if (this.isHUC) {
// this.writeSubmapping();
//}
}
// Connect to project database.
public void connect() {
if (!File.Exists(this.dbFile)) {
Utils.error(String.Format("Cannot find project database {0}. Have you opened the project?", this.dbFile), this.isBatch);
}
try
{
if (this.conn is null)
{
if (this.useSQLite) {
this.conn = new SQLiteConnection("Data Source=" + this.dbFile);
} else {
this.conn = new OleDbConnection(this._connStr);
}
if (this.conn is null)
{
Utils.error(String.Format("Failed to connect to project database {0}.", this.dbFile), this.isBatch);
return;
}
}
if (this.conn.State != System.Data.ConnectionState.Open) this.conn.Open();
} catch (Exception ex) {
Utils.error(String.Format("Failed to connect to project database {0}: {1}.", this.dbFile, ex.Message), this.isBatch);
}
}
//===========no longer used================================================================
// def connectRef(self, readonly=False) -> Any:
//
// """Connect to reference database."""
//
// if not File.Exists(self.dbRefFile):
// Utils.error('Cannot find reference database {0}', self.dbRefFile), self.isBatch)
// return None
// try:
// if self.isHUC or self.isHAWQS or self.forTNC:
// conn = sqlite3.connect(self.dbRefFile) # @UndefinedVariable
// conn.row_factory = sqlite3.Row # @UndefinedVariable
// elif readonly:
// conn = pyodbc.connect(self._connRefStr, readonly=True)
// else:
// # use autocommit when writing to tables, hoping to save storing rollback data
// conn = pyodbc.connect(self._connRefStr, autocommit=True)
// if conn:
// return conn
// else:
// Utils.error('Failed to connect to reference database {0}.\n{1}', self.dbRefFile, self.connectionProblem()), self.isBatch)
// except Exception:
// Utils.error('Failed to connect to reference database {0}: {1}.\n{2}', self.dbRefFile, ex.Message,self.connectionProblem()), self.isBatch)
// return None
//===========================================================================
// Connect to database db.
public DbConnection connectDb(string db) {
DbConnection conn;
if (!File.Exists(db)) {
Utils.error(String.Format("Cannot find database {0}", db), this.isBatch);
return null;
}
var refStr = Parameters._ACCESSSTRING + db;
try {
conn = new OleDbConnection(refStr);
if (conn is not null) {
return conn;
} else {
Utils.error(String.Format("Failed to connect to database {0}", db), this.isBatch);
}
} catch (Exception ex) {
Utils.error(String.Format("Failed to connect to database {0}: {1}", db, ex.Message), this.isBatch);
}
return null;
}
// Return true if project database table exists and has data.
public bool hasData(string table) {
try {
this.connect();
string sql = sqlSelect(table, "*", "", "");
var reader = getReader(this.conn, sql);
var result = reader.HasRows;
reader = null;
this.conn.Close();
return result;
} catch (Exception) {
return false;
}
}
// Clear table of data.
public void clearTable(string table) {
try {
execNonQuery("DELETE FROM " + table);
} catch (Exception) {
// since purpose is to make sure any data in table is not accessible
// ignore problems such as table not existing
}
}
public void execNonQuery(string sql) {
this.connect();
int res = 0;
if (this.conn is OleDbConnection)
{
var cmd = new OleDbCommand(sql, (OleDbConnection)conn);
res = cmd.ExecuteNonQuery();
} else {
var cmd = new SQLiteCommand(sql, (SQLiteConnection)conn);
res = cmd.ExecuteNonQuery();
}
}
// Return true if table exists in db
public bool tableExists(string table, string db) {
var conn = this.connectDb(db);
if (conn is null) return false;
bool needToClose = false;
if (conn.State != ConnectionState.Open) {
conn.Open();
needToClose = true;
}
var schema = conn.GetSchema("TABLES");
var myTable = schema.Select(String.Format("TABLE_NAME='{0}'", table));
if (needToClose) {
conn.Close();
}
return myTable.Length > 0;
}
// Create SQL select statement.
public static string sqlSelect(string table, string selection, string order, string where) {
var orderby = order == "" ? "" : " ORDER BY " + order;
var select = "SELECT " + selection + " FROM " + table + orderby;
var result = where == "" ? select : select + " WHERE " + where;
return result;
}
//// SWAT Editor 2012.10_2.18 renamed ElevationBands to ElevationBand.
//public virtual object updateProjDb(string SWATEditorVersion) {
// if (SWATEditorVersion == "2012.10_2.18" || SWATEditorVersion == "2012.10.19") {
// using (var conn = this.connect()) {
// try {
// cursor = conn.cursor();
// hasElevationBand = false;
// hasElevationBands = false;
// foreach (var row in cursor.tables(tableType: "TABLE")) {
// table = row.table_name;
// if (table == "ElevationBand") {
// hasElevationBand = true;
// } else if (table == "ElevationBands") {
// hasElevationBands = true;
// }
// }
// if (hasElevationBands && !hasElevationBand) {
// sql = "SELECT * INTO ElevationBand FROM ElevationBands";
// cursor.execute(sql);
// Utils.loginfo("Created ElevationBand");
// sql = "DROP TABLE ElevationBands";
// cursor.execute(sql);
// Utils.loginfo("Deleted ElevationBands");
// }
// } catch (Exception ex) {
// Utils.error(String.Format("Could not update table in project database {0}: {1}", this.dbFile, ex.Message), this.isBatch);
// return;
// }
// }
// }
//}
//// SWAT Editor 2012.10_2.18 renamed ElevationBandsrng to ElevationBandrng and added tblOutputVars.
//public virtual object updateRefDb(string SWATEditorVersion, string dbRefTemplate) {
// object sql;
// if (SWATEditorVersion == "2012.10_2.18" || SWATEditorVersion == "2012.10.19") {
// try {
// var cursor = this.connRef.cursor();
// var hasElevationBandrng = false;
// var hasElevationBandsrng = false;
// var hasTblOututVars = false;
// foreach (var row in cursor.tables(tableType: "TABLE")) {
// var table = row.table_name;
// if (table == "ElevationBandrng") {
// hasElevationBandrng = true;
// } else if (table == "ElevationBandsrng") {
// hasElevationBandsrng = true;
// } else if (table == "tblOutputVars") {
// hasTblOututVars = true;
// }
// }
// if (!hasElevationBandrng) {
// sql = "SELECT * INTO ElevationBandrng FROM [MS Access;DATABASE=" + dbRefTemplate + "].ElevationBandrng";
// cursor.execute(sql);
// Utils.loginfo("Created ElevationBandrng");
// }
// if (hasElevationBandsrng) {
// sql = "DROP TABLE ElevationBandsrng";
// cursor.execute(sql);
// Utils.loginfo("Deleted ElevationBandsrng");
// }
// if (!hasTblOututVars) {
// sql = "SELECT * INTO tblOutputVars FROM [MS Access;DATABASE=" + dbRefTemplate + "].tblOutputVars";
// cursor.execute(sql);
// Utils.loginfo("Created tblOutputVars");
// }
// } catch (Exception ex) {
// Utils.error(String.Format("Could not update tables in reference database {0}: {1}", this.dbRefFile, ex.Message), this.isBatch);
// return;
// }
// }
//}
// return reader for sql based on tye of connection conn
public static DbDataReader getReader(DbConnection conn, string sql)
{
if (conn.State != System.Data.ConnectionState.Open) conn.Open();
if (conn is SQLiteConnection) {
var cmd = new SQLiteCommand(sql, (SQLiteConnection)conn);
return cmd.ExecuteReader() as SQLiteDataReader;
}
{
var cmd = new OleDbCommand(sql, (OleDbConnection)conn);
return cmd.ExecuteReader() as OleDbDataReader;
}
}
// Collect table names from project database.
public void populateTableNames() {
this.landuseTableNames = new List<string>();
this.soilTableNames = new List<string>();
this._allTableNames = new List<string>();
try
{
this.connect();
if (this.conn is SQLiteConnection) {
string sql = "SELECT name FROM sqlite_master WHERE TYPE='table'";
var cmd = new SQLiteCommand(sql, (SQLiteConnection)this.conn);
var reader = cmd.ExecuteReader();
if (reader.HasRows) {
while (reader.Read()) {
string table = reader.GetString(0);
if (table.Contains("landuse") && !table.Contains("config_landuse")) {
this.landuseTableNames.Add(table);
} else if (table.Contains("soil") && !table.Contains("usersoil") &&
!table.Contains("config_soil")) {
this.soilTableNames.Add(table);
}
this._allTableNames.Add(table);
}
}
} else {
var schema = ((OleDbConnection)this.conn).GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
foreach (var row in schema.Rows.OfType<DataRow>())
{
string table = row.ItemArray[2].ToString();
if (table.Contains("landuse") && !table.Contains("config_landuse"))
{
this.landuseTableNames.Add(table);
}
else if (table.Contains("soil") && !table.Contains("usersoil") &&
!table.Contains("config_soil"))
{
this.soilTableNames.Add(table);
}
this._allTableNames.Add(table);
}
}
} catch (Exception) {
Utils.error(String.Format("Could not read tables in project database {0}", this.dbFile), this.isBatch);
}
}
// Collect landuse codes from landuseTable and create lookup tables.
public bool populateLanduseCodes(string landuseTable) {
var OK = true;
this.landuseCodes.Clear();
var revLanduseCodes = new Dictionary<string, int>();
this._landuseTranslate.Clear();
this.landuseIds.Clear();
this._landuseIDCs.Clear();
this.landuseOVN.Clear();
this.urbanIds.Clear();
this.connect();
string sql = sqlSelect(landuseTable, "LANDUSE_ID, SWAT_CODE", "", "");
DbDataReader reader = getReader(this.conn, sql);
try
{
if (reader.HasRows)
{
while (reader.Read())
{
int nxt = Convert.ToInt32(reader.GetValue(0));
string landuseCode = reader.GetString(1);
if (nxt == 0 || this.defaultLanduse < 0)
{
this.defaultLanduse = nxt;
this.defaultLanduseCode = landuseCode;
}
// check if code already defined
int val = -1;
if (revLanduseCodes.TryGetValue(landuseCode, out val))
{
this.storeLanduseTranslate(nxt, val);
} else
{
// landuseCode was not already defined
if (!this.storeLanduseCode(nxt, landuseCode))
{
OK = false;
}
revLanduseCodes[landuseCode] = nxt;
}
}
Utils.loginfo(String.Format("Default landuse set to {0}", this.defaultLanduseCode));
}
return OK;
}
catch (Exception ex)
{
Utils.error(String.Format("Could not read table {0} in project database {1}: {2}", landuseTable, this.dbFile, ex.Message), this.isBatch);
return false;
}
}
// Make key lid equivalent to key equiv,
// where equiv is a key in landuseCodes.
public void storeLanduseTranslate(int lid, int equiv) {
if (!this._landuseTranslate.ContainsKey(lid)) {
this._landuseTranslate[lid] = equiv;
}
}
// Translate a landuse id to its equivalent lid
// in landuseCodes, if any.
//
public int translateLanduse(int lid) {
ListFuns.insertIntoSortedIntList(lid, this.landuseVals, true);
int val = -1;
if (this._landuseTranslate.TryGetValue(lid, out val))
{ return val; } else { return lid; }
}
// Store landuse codes in lookup tables.
public virtual bool storeLanduseCode(int landuseCat, string landuseCode)
{
if (this.connRef is null)
{
return false;
}
string sql2;
string table;
var landuseIDC = 0;
var landuseOVN = 0.0;
var landuseId = 0;
var urbanId = -1;
var OK = true;
var isUrban = landuseCode.StartsWith("U");
if (isUrban) {
table = "urban";
sql2 = sqlSelect(table, "IUNUM, OV_N", "", String.Format("URBNAME='{0}'", landuseCode));
try {
var reader = getReader(this.connRef, sql2);
if (reader.HasRows)
{
reader.Read();
urbanId = Convert.ToInt32(reader.GetValue(0));
landuseOVN = Convert.ToDouble(reader.GetValue(1));
}
} catch (Exception ex) {
Utils.error(String.Format("Could not read table {0} in reference database {1}: {2}", table, this.dbRefFile, ex.Message), this.isBatch);
return false;
}
}
if (urbanId < 0) {
// not tried or not found in urban
table = "crop";
sql2 = sqlSelect(table, "ICNUM, IDC, OV_N", "", String.Format("CPNM='{0}'", landuseCode));
try {
var reader = getReader(this.connRef, sql2);
if (reader.HasRows)
{
reader.Read();
urbanId = Convert.ToInt32(reader.GetValue(0));
landuseIDC = Convert.ToInt32(reader.GetValue(1));
landuseOVN = reader.GetDouble(2);
}
else
{
if (isUrban)
{
if (this.landuseErrorReported)
{
Utils.loginfo(String.Format("No data for landuse {0} in reference database tables urban or {1}", landuseCode, table));
}
else
{
Utils.error(String.Format("No data for landuse {0} (and perhaps others) in reference database tables urban or {1}", landuseCode, table), this.isBatch);
this.landuseErrorReported = true;
}
}
else if (this.landuseErrorReported)
{
Utils.loginfo(String.Format("No data for landuse {0} in reference database table {1}", landuseCode, table));
}
else
{
Utils.error(String.Format("No data for landuse {0} (and perhaps others) in reference database table {1}", landuseCode, table), this.isBatch);
this.landuseErrorReported = true;
//OK = False
}
}
} catch (Exception ex) {
Utils.error(String.Format("Could not read table {0} in reference database {1}: {2}", table, this.dbRefFile, ex.Message), this.isBatch);
return false;
}
}
this.landuseCodes[landuseCat] = landuseCode;
this.landuseIds[landuseCat] = landuseId;
this._landuseIDCs[landuseCat] = landuseIDC;
this.landuseOVN[landuseCat] = landuseOVN;
if (urbanId >= 0) {
this.urbanIds[landuseCat] = urbanId;
}
return OK;
}
// Return landuse code of landuse category lid.
public virtual string getLanduseCode(int lid) {
var lid1 = this.translateLanduse(lid);
string code = null;
if (this.landuseCodes.TryGetValue(lid1, out code)) return code;
if (this._undefinedLanduseIds.Contains(lid)) {
return this.defaultLanduseCode;
} else {
this._undefinedLanduseIds.Add(lid);
var @string = lid.ToString();
//Utils.error('Unknown landuse value {0}', string), self.isBatch)
Utils.loginfo(String.Format("Unknown landuse value {0}", @string));
return this.defaultLanduseCode;
}
}
// Return landuse category (value in landuse map) for code,
// adding to lookup tables if necessary.
//
public int getLanduseCat(string landuseCode) {
foreach (KeyValuePair<int, string> entry in this.landuseCodes) {
if (entry.Value == landuseCode) {
return entry.Key;
}
}
// we have a new landuse from splitting
// first find a new category: maximum existing ones plus 1
int cat = 0;
foreach (var key in this.landuseCodes.Keys) {
if (key > cat) {
cat = key;
}
}
cat += 1;
this.landuseCodes[cat] = landuseCode;
// now add to landuseIds or urbanIds table
this.storeLanduseCode(cat, landuseCode);
return cat;
}
// HUC and HAWQS only. Return True if landuse counts as agriculture.
public bool isAgriculture(int landuse) {
return 81 < landuse && landuse < 91 || 99 < landuse && landuse < 567;
}
// Store names and groups for soil categories.
public virtual bool populateSoilNames(string soilTable, bool checkSoils) {
this.soilNames.Clear();
this.soilTranslate.Clear();
var revSoilNames = new Dictionary<string, int>();
this.connect();
if (this.conn is null) {
return false;
}
string sql = sqlSelect(soilTable, "SOIL_ID, SNAM", "", "");
var reader = getReader(conn, sql);
if (reader.HasRows) {
try {
while (reader.Read())
{
int nxt = Convert.ToInt32(reader.GetValue(0));
string soilName = reader.GetString(1);
if (nxt == 0 || this.defaultSoil < 0)
{
this.defaultSoil = nxt;
this.defaultSoilName = soilName;
Utils.loginfo(String.Format("Default soil set to {0}", this.defaultSoilName));
}
// check if code already defined
int key = -1;
if (revSoilNames.TryGetValue(soilName, out key))
{
this.storeSoilTranslate(nxt, key);
}
else
{
// soilName not found
this.soilNames[nxt] = soilName;
revSoilNames[soilName] = nxt;
}
}
} catch (Exception ex) {
Utils.error(String.Format("Could not read table {0} in project database {1}: {2}", soilTable, this.dbFile, ex.Message), this.isBatch);
return false;
}
}
// only need to check usersoil table if not STATSGO
// (or SSURGO, but then we would not be here)
return !checkSoils || this.useSTATSGO || this.checkSoilsDefined();
// not currently used
//===========================================================================
// @staticmethod
// def matchesSTATSGO(name):
// pattern = '[A-Z]{2}[0-9]{3}\Z'
// return re.match(pattern, name)
//===========================================================================
}
// Return name for soil id sid, plus flag indicating lookup success.
public string getSoilName(int sid, out bool ok) {
if (this.useSSURGO) {
ok = true;
return sid.ToString();
}
int sid1 = this.translateSoil(sid, out ok);
string name = null;
if (this.soilNames.TryGetValue(sid1, out name))
{
ok = true;
return name;
}
if (this._undefinedSoilIds.Contains(sid)) {
ok = false;
return this.defaultSoilName;
} else {
var @string = sid.ToString();
this._undefinedSoilIds.Add(sid);
Utils.error(String.Format("Unknown soil value {0}", @string), this.isBatch);
ok = false;
return this.defaultSoilName;
}
}
// Check if all soil names in soilNames are in usersoil table in reference database.
public bool checkSoilsDefined() {
var sql = sqlSelect(this.usersoil, "SNAM", "", "SNAM='{0}'");
var errorReported = false;
foreach (var soilName in this.soilNames.Values) {
try {
var sql2 = String.Format(sql, soilName);
var reader = getReader(this.connRef, sql2);
if (!reader.HasRows) {
if (!errorReported) {
Utils.error(String.Format("Soil name {0} (and perhaps others) not defined in {1} table in database {2}.", soilName, this.usersoil, this.dbRefFile), this.isBatch);
errorReported = true;
} else {
Utils.loginfo(String.Format("Soil name {0} not defined.", soilName));
}
}
}
catch (Exception ex)
{
Utils.error(String.Format("Could not read {0} table in database {1}: {2}", this.usersoil, this.dbRefFile, ex.Message), this.isBatch);
return false;
}
}
return true;
}
// no longer used
//===========================================================================
// def setUsersoilTable(self, conn, connRef, usersoilTable, parent):
// """Find a usersoil table.
//
// First candidate is the usersoilTable parameter,
// which (if not empty) if 'usersoil' is in the reference database, else the project database.
// Second candidate is the default 'usersoil' table in the reference database.
// Otherwise try project database tables with 'usersoil' in name, and confirm with user.
// """
// # if usersoilTable exists start with it: it is one obtained from the project file
// if usersoilTable != '':
// if usersoilTable == 'usersoil':
// if self.checkUsersoilTable(usersoilTable, connRef):
// self.usersoilTableName = usersoilTable
// return
// elif self.checkUsersoilTable(usersoilTable, conn):
// self.usersoilTableName = usersoilTable
// return
// # next try default 'usersoil'
// if self.checkUsersoilTable('usersoil', connRef):
// self.usersoilTableName = 'usersoil'
// return
// for table in self._usersoilTableNames:
// if table == 'usersoil':
// continue # old project database
// if self.checkUsersoilTable(table, conn):
// msg = 'Use {0} as usersoil table?', table)
// reply = Utils.question(msg, parent, True)
// if reply == QMessageBox.Yes:
// self.usersoilTableName = table
// return
// Utils.error('No usersoil table found', self.isBatch)
// self.usersoilTableName = ''
//===========================================================================
// Make key sid equivalent to key equiv,
// where equiv is a key in soilNames.
//
public void storeSoilTranslate(int sid, int equiv) {
if (!this.soilTranslate.Keys.Contains(sid)) {
this.soilTranslate[sid] = equiv;
}
}
// Translate a soil id to its equivalent id in soilNames, plus flag indicating lookup success.
public int translateSoil(int sid, out bool ok) {
ListFuns.insertIntoSortedIntList(sid, this.soilVals, true);
if (this.useSSURGO) {
if (this.isHUC || this.isHAWQS) {
return this.translateSSURGOSoil(sid, out ok);
} else {
ok = true;
return sid;
}
}
int sid1;
bool found = this.soilTranslate.TryGetValue(sid, out sid1);
ok = true;
return found ? sid1 : sid;
}
// Use table to convert soil map values to SSURGO muids, plus flag indicating lookup success.
// Replace any soil with sname Water with Parameters._SSURGOWater.
// Report undefined SSURGO soils. Only used with HUC and HAWQS.
public int translateSSURGOSoil(int sid, out bool ok) {
if (this._undefinedSoilIds.Contains(sid)) {
ok = false;
return this.SSURGOUndefined;
}
int muid = -1;
if (this.SSURGOSoils.TryGetValue(sid, out muid))
{
ok = true;
return muid;
}
var sql = sqlSelect("statsgo_ssurgo_lkey", "Source, MUKEY", "", String.Format("LKEY={0}", sid.ToString()));
this.connect();
var reader = getReader(conn, sql);
if (!reader.HasRows) {
Utils.information(String.Format("WARNING: SSURGO soil map value {0} not defined as lkey in statsgo_ssurgo_lkey", sid), this.isBatch, logFile: this.logFile);
this._undefinedSoilIds.Add(sid);
ok = false;
return sid;
}
reader.Read();
// only an information issue, not an error for now
if (reader.GetString(0).ToUpper().Trim() == "STATSGO") {
Utils.information(String.Format("WARNING: SSURGO soil map value {0} is a STATSGO soil according to statsgo_ssurgo_lkey", sid), this.isBatch, logFile: this.logFile);
// self._undefinedSoilIds.append(sid)
// return sid
}
sql = sqlSelect("SSURGO_Soils", "SNAM", "", String.Format("MUID='{0}'", reader.GetString(1)));
reader = getReader(this.SSURGOConn, sql);
if (!reader.HasRows) {
Utils.information(String.Format("WARNING: SSURGO soil lkey value {0} and MUID {1} not defined", sid, reader.GetString(1)), this.isBatch, logFile: this.logFile);
this._undefinedSoilIds.Add(sid);
ok = false;
return this.SSURGOUndefined;
}
reader.Read();
if (reader.GetString(0).ToLower().Trim() == "water") {
this.SSURGOSoils[Convert.ToInt32(sid)] = Parameters._SSURGOWater;
ok = true;
return Parameters._SSURGOWater;
} else {
muid = Convert.ToInt32(reader.GetString(1));
this.SSURGOSoils[Convert.ToInt32(sid)] = muid;
ok = true;
return muid;
}
}
// Make sorted list of all landuses.
public List<string> populateAllLanduses() {
var luses = new List<string>();
var landuseTable = "crop";
var urbanTable = "urban";
var landuseSql = sqlSelect(landuseTable, "CPNM, CROPNAME", "", "");
var urbanSql = sqlSelect(urbanTable, "URBNAME, URBFLNM", "", "");
if (this.connRef is null) {
return luses;
}
var reader = getReader(this.connRef, landuseSql);
try {
while (reader.Read()) {
luses.Add(reader.GetString(0) + " (" + reader.GetString(1) + ")");
}
} catch (Exception ex) {
Utils.error(String.Format("Could not read table {0} in reference database {1}: {2}", landuseTable, this.dbRefFile, ex.Message), this.isBatch);
return luses;
}