/
AcsDataManager.cs
1848 lines (1531 loc) · 75.4 KB
/
AcsDataManager.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
/*
Copyright (c) 2012 Azavea, Inc.
This file is part of ACS Alchemist.
ACS Alchemist is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
ACS Alchemist is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with ACS Alchemist. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using log4net;
using Azavea.NijPredictivePolicing.Common;
using System.IO;
using Azavea.NijPredictivePolicing.Common.DB;
using Azavea.NijPredictivePolicing.ACSAlchemistLibrary.FileFormats;
using System.Security.Policy;
using System.Data;
using GisSharpBlog.NetTopologySuite.Geometries;
using GisSharpBlog.NetTopologySuite.IO;
using System.Data.Common;
using System.Text.RegularExpressions;
using Azavea.NijPredictivePolicing.Common.Data;
using GisSharpBlog.NetTopologySuite.Features;
using GeoAPI.Geometries;
using System.Collections;
using GeoAPI.CoordinateSystems.Transformations;
using GeoAPI.CoordinateSystems;
using ProjNet.CoordinateSystems;
namespace Azavea.NijPredictivePolicing.ACSAlchemistLibrary.Transfer
{
/// <summary>
/// This class does most of the heavy lifting of the ACS Alchemist
/// </summary>
public class AcsDataManager : IDisposable
{
private static ILog _log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// Gets selected State FIPS code as a string
/// </summary>
public string StateFIPS { get { return ((int)(this.State)).ToString("00"); } }
/// <summary>
/// Selected State
/// </summary>
public AcsState State = AcsState.None;
public string WorkingPath;
public string ShapePath;
public string CurrentDataPath;
public string DBFilename;
protected string _summaryLevel;
public string SummaryLevel
{
get
{
return _summaryLevel;
}
set
{
_summaryLevel = value;
if (!string.IsNullOrEmpty(value))
{
_summaryLevel = Utilities.GetAs<int>(value, -1).ToString("000");
}
else
{
_summaryLevel = string.Empty;
}
}
}
/// <summary>
/// If set, the manager will look for a file of WKTs that it will use to ensure all exported geometries
/// at least intersect
/// </summary>
public string ExportFilterFilename;
/// <summary>
/// If set, the manager will read in as a CSV, and import the variable values into the provided job table
/// </summary>
public string DesiredVariablesFilename;
/// <summary>
/// If set, the manager will re-use a previous job with the same name, instead of replacing it
/// </summary>
public bool ReusePreviousJobTable = false;
public string OutputProjectionFilename;
public double GridCellWidth = 10000;
public double GridCellHeight = 10000;
/// <summary>
/// If set, the manager will use this envelope while calculating the export grid
/// (minx, miny, maxx, maxy)
/// </summary>
public string GridEnvelopeFilename;
public bool IncludeEmptyGridCells = false;
public string OutputFolder;
public bool PreserveJam;
/// <summary>
/// If true, add column GEOID_STRP to the shapefile output with values the same as GEOID except without the "15000US" prefix
/// </summary>
public bool AddStrippedGEOIDcolumn = false;
/// <summary>
/// If true, this feature will add a number of columns to the end of the export with
/// calculated values about the projected geometries
/// Area, Perimeter, and Centroid
/// It should also truncate requested variables to make sure things fit, but should warn the user.
/// </summary>
public bool AddGeometryAttributesToOutput = true;
/// <summary>
///
/// </summary>
public IDataClient DbClient;
public AcsDataManager()
{
Init();
}
public AcsDataManager(AcsState aState)
{
this.State = aState;
Init();
}
public AcsDataManager(AcsState aState, string workingFolder, string year)
{
this.State = aState;
if (!string.IsNullOrEmpty(year))
{
/**
* IMPORTANT NOTE! RequestedYear MUST BE SET before setting the Application Data Directory!
*/
Settings.RequestedYear = year;
}
if (!string.IsNullOrEmpty(workingFolder))
{
//override where we're storing temporary files
Settings.AppDataDirectory = FileUtilities.SafePathEnsure(workingFolder);
}
_log.InfoFormat("Working directory is {0} ", workingFolder);
Init();
}
/// <summary>
/// Initialize our properties, and ensure our path structure is intact
/// </summary>
public void Init()
{
this.WorkingPath = FileLocator.GetStateWorkingDir(this.State);
FileUtilities.PathEnsure(this.WorkingPath, "database");
this.DBFilename = FileUtilities.PathCombine(this.WorkingPath, "database", Settings.CurrentAcsDirectory + ".sqlite");
this.ShapePath = FileUtilities.PathEnsure(this.WorkingPath, "shapes");
this.CurrentDataPath = FileUtilities.PathEnsure(this.WorkingPath, Settings.CurrentAcsDirectory);
this.DbClient = DataClient.GetDefaultClient(this.DBFilename);
}
public string GetLocalAllGeometriesZipFileName()
{
string remoteFilename = FileLocator.GetStateAllGeometryFileName(this.State);
string localFilename = Settings.RequestedYear + "_" + remoteFilename;
return FileUtilities.PathCombine(this.WorkingPath, localFilename);
}
public string GetLocalBlockGroupZipFileName()
{
string remoteFilename = FileLocator.GetStateBlockGroupFileName(this.State);
string localFilename = Settings.RequestedYear + "_" + remoteFilename;
return FileUtilities.PathCombine(this.WorkingPath, localFilename);
}
public string GetLocalGeographyFileName()
{
return FileLocator.GetAggregateDataGeographyFilename(this.GetAggregateDataPath());
}
public string GetGeographyTablename()
{
string geographies = "geographies";
if ((this.SummaryLevel != "150") && (this.SummaryLevel != "140"))
{
geographies += "_all";
}
return geographies;
}
public string GetLocalColumnMappingsDirectory()
{
return FileUtilities.PathCombine(Settings.AppDataDirectory, Settings.ColumnMappingsFileName);
}
public bool CheckColumnMappingsFile()
{
_log.DebugFormat("Downloading column mappings file ({0})", Settings.ColumnMappingsFileName);
string desiredUrl = Settings.CurrentColumnMappingsFileUrl;
string destFilepath = FileUtilities.PathCombine(Settings.AppDataDirectory,
Settings.ColumnMappingsFileName + Settings.ColumnMappingsFileExtension);
if (!FileDownloader.GetFileByURL(desiredUrl, destFilepath, ref this._cancelled, WorkOffline))
{
_log.ErrorFormat("Downloading sequence files failed: unable to retrieve {0} ", desiredUrl);
return false;
}
if (!FileLocator.ExpandZipFile(destFilepath, GetLocalColumnMappingsDirectory()))
{
_log.ErrorFormat("Downloading sequence files failed: unable to expand file {0}", destFilepath);
return false;
}
_log.Debug("Downloading sequence files... Done!");
return true;
}
public bool CheckCensusAggregatedDataFile()
{
if ((this.SummaryLevel == "150") || (this.SummaryLevel == "140"))
{
//if summary level is tracts / block groups
return CheckBlockGroupFile();
}
else
{
return CheckAllGeometriesFile();
}
}
/// <summary>
/// Gets either the standard data path based on year, or appends an 'all' if we're not doing tracts or block-groups
/// </summary>
/// <returns></returns>
public string GetAggregateDataPath()
{
if ((this.SummaryLevel == "150") || (this.SummaryLevel == "140"))
{
return FileUtilities.PathEnsure(this.WorkingPath, Settings.CurrentAcsDirectory);
}
else
{
return FileUtilities.PathEnsure(this.WorkingPath, Settings.CurrentAcsDirectory + "_all");
}
}
/// <summary>
/// Downloads the census DATA for the given state
/// </summary>
/// <returns></returns>
public bool CheckBlockGroupFile()
{
_log.DebugFormat("Downloading census data for tract and block groups for {0}", this.State);
string desiredUrl = FileLocator.GetStateBlockGroupUrl(this.State);
string destFilepath = GetLocalBlockGroupZipFileName();
if (!FileDownloader.GetFileByURL(desiredUrl, destFilepath, ref this._cancelled, WorkOffline))
{
_log.ErrorFormat("Downloading census data failed: unable to retrieve {0} ", desiredUrl);
return false;
}
//double-check to make sure we're not expanding this ON-TOP of the 'all-geometries' data!!!
//current data path should NOT be acs2010_5yr
if (!FileLocator.ExpandZipFile(destFilepath, this.GetAggregateDataPath()))
{
_log.ErrorFormat("Downloading census data failed: unable to expand file {0}", destFilepath);
return false;
}
_log.Debug("Downloading census data... Done!");
return true;
}
/// <summary>
/// Downloads the census DATA for the given state
/// </summary>
/// <returns></returns>
public bool CheckAllGeometriesFile()
{
_log.DebugFormat("Downloading census data for all geometries for {0}", this.State);
string desiredUrl = FileLocator.GetStateAllGeometryUrl(this.State);
string destFilepath = GetLocalAllGeometriesZipFileName();
if (!FileDownloader.GetFileByURL(desiredUrl, destFilepath, ref this._cancelled, WorkOffline))
{
_log.ErrorFormat("Downloading census data failed: unable to retrieve {0} ", desiredUrl);
return false;
}
//double-check to make sure we're not expanding this ON-TOP of the block-group data!!!
//current data path should NOT be acs2010_5yr
if (!FileLocator.ExpandZipFile(destFilepath, this.GetAggregateDataPath()))
{
_log.ErrorFormat("Downloading census data failed: unable to expand file {0}", destFilepath);
return false;
}
_log.Debug("Downloading census data... Done!");
return true;
}
/// <summary>
/// Downloads the SHAPE FILEs, must be run before initializing the database!
/// Since this will be imported into the database!
/// </summary>
/// <returns></returns>
public bool CheckShapefiles()
{
BoundaryLevels[] shapeFileLevels = new BoundaryLevels[] {
BoundaryLevels.census_blockgroups,
BoundaryLevels.census_tracts,
BoundaryLevels.county_subdivisions,
BoundaryLevels.counties,
/*
BoundaryLevels.census_regions,
BoundaryLevels.census_divisions,
BoundaryLevels.states
BoundaryLevels.zipthree,
BoundaryLevels.zipfive,
*/
};
foreach (BoundaryLevels level in shapeFileLevels)
{
if (level == BoundaryLevels.None)
continue;
string url = ShapefileHelper.GetRemoteShapefileURL(level, this.StateFIPS);
string localPath = Path.Combine(this.WorkingPath, Path.GetFileName(url));
string name = level.ToString();
if (!DownloadAndImportShapefile(url, localPath, name, name))
{
return false;
}
}
return true;
}
/// <summary>
/// Helper function for retrieving a given zip file from a URL,
/// decompressing it, finding a shapefile in it, and importing that into the database
/// </summary>
/// <param name="desiredUrl"></param>
/// <param name="destFilepath"></param>
/// <param name="niceName"></param>
/// <param name="tablename"></param>
/// <returns></returns>
public bool DownloadAndImportShapefile(string desiredUrl, string destFilepath, string niceName, string tablename)
{
_log.DebugFormat("Downloading shapefile of {0} for {1}", niceName, this.State);
if (!FileDownloader.GetFileByURL(desiredUrl, destFilepath, ref this._cancelled, WorkOffline))
{
_log.ErrorFormat("Shapefile download failed: Could not download {0}", niceName);
return false;
}
if (!FileLocator.ExpandZipFile(destFilepath, this.ShapePath))
{
_log.ErrorFormat("Shapefile import failed: Could not decompress {0}", niceName);
return false;
}
_log.DebugFormat("State {0} decompressed successfully", niceName);
var client = DbClient;
using (var conn = client.GetConnection())
{
if (DataClient.HasTable(conn, client, tablename))
{
DbClient.GetCommand(string.Format("DROP TABLE IF EXISTS \"{0}\";", tablename), conn).ExecuteNonQuery();
}
{
_log.DebugFormat("{0} table not found, importing...", tablename);
var filenames = FileUtilities.FindFileNameInZipLike(destFilepath, "*.shp");
if ((filenames == null) || (filenames.Count == 0))
{
_log.ErrorFormat("Compressed file {0} didn't contain a shapefile!", destFilepath);
return false;
}
foreach (string filename in filenames)
{
string fullShapefilename = Path.Combine(this.ShapePath, filename);
ShapefileHelper.MakeCensusProjFile(fullShapefilename);
ShapefileHelper.ImportShapefile(conn, this.DbClient,
fullShapefilename, tablename, 4269);
//TODO: multiple shape files in one zip?
break;
}
}
}
return true;
}
/// <summary>
/// Checks to see if the database exists, and if not, initializes it with the provided inputs
/// </summary>
/// <returns></returns>
public bool CheckDatabase()
{
_log.DebugFormat("Looking for local {0} database", this.State);
if (!File.Exists(this.DBFilename))
{
_log.DebugFormat("Building local {0} database...", this.State);
}
if (!this.InitDatabase())
{
_log.ErrorFormat("Building local {0} database... Failed! There was a problem detected.", this.State);
return false;
}
return (DbClient.TestDatabaseConnection());
}
public bool CreateGeographiesTable(DbConnection conn)
{
//create the table
string createGeographyTableSQL = DataClient.GenerateTableSQLFromFields(this.GetGeographyTablename(), GeographyFileReader.Columns);
DbClient.GetCommand(createGeographyTableSQL, conn).ExecuteNonQuery();
//parse in the file
string geographyFilename = GetLocalGeographyFileName();
GeographyFileReader geoReader = new GeographyFileReader(geographyFilename);
if (geoReader.HasFile)
{
_log.Debug("Importing Geographies File...");
string tableSelect = string.Format("select * from \"{0}\"", this.GetGeographyTablename());
var adapter = DataClient.GetMagicAdapter(conn, DbClient, tableSelect);
var table = DataClient.GetMagicTable(conn, DbClient, tableSelect);
_log.Debug("Reading...");
int primKey = 0;
foreach (List<string> row in geoReader.GetReader())
{
var geoData = row.ToArray();
//add a primary key on there
object[] rowData = new object[table.Columns.Count];
rowData[0] = primKey++;
Array.Copy(geoData, 0, rowData, 1, geoData.Length);
table.Rows.Add(rowData);
}
if ((table != null) && (table.Rows.Count > 0))
{
_log.Debug("Saving... (This can take a while)");
//this.StateFIPS = (table.Rows[0]["STATE"] as string);
adapter.Update(table);
table.AcceptChanges();
}
_log.Debug("Importing Geographies File... Done!");
return true;
}
else
{
_log.Debug("Could not find geographies file, table could not be initialized!");
return false;
}
}
public bool CreateColumnMappingsTable(DbConnection conn)
{
DbClient.GetCommand(string.Format("DROP TABLE IF EXISTS \"{0}\";", DbConstants.TABLE_ColumnMappings), conn).ExecuteNonQuery();
//create table
string createMappingsTableSql = DataClient.GenerateTableSQLFromFields(DbConstants.TABLE_ColumnMappings, SequenceFileReader.Columns);
DbClient.GetCommand(createMappingsTableSql, conn).ExecuteNonQuery();
string tableSelect = string.Format("select * from \"{0}\"", DbConstants.TABLE_ColumnMappings);
var adapter = DataClient.GetMagicAdapter(conn, DbClient, tableSelect);
var table = DataClient.GetMagicTable(conn, DbClient, tableSelect);
string colMapDir = GetLocalColumnMappingsDirectory();
if (Directory.Exists(colMapDir))
{
_log.Debug("Importing Sequence Files...");
int ixid = 0;
foreach (string file in Directory.GetFiles(colMapDir, "Seq*.xls", SearchOption.TopDirectoryOnly))
{
//Extract sequence number from filename
string localFilename = Path.GetFileName(file);
Regex sequenceFormat = new Regex(@"^Seq(\d{1,4})\.xls$");
Match match = sequenceFormat.Match(localFilename);
if (!match.Groups[0].Success)
{
_log.Warn("Malformed filename found in sequence files folder; skipping\n\t" + file);
continue;
}
int seqNo = int.Parse(match.Groups[1].Value);
//Read data from file
var reader = new SequenceFileReader(file).GetReader();
if (reader == null)
{
_log.Error("One of the sequence files is missing; skipping\n\t" + file);
continue;
}
DataSet fileData = reader.AsDataSet(false);
if (fileData.Tables == null || fileData.Tables.Count == 0)
{
_log.ErrorFormat("Sequence File had no readable variables: {0} ", file);
continue;
}
else if (fileData.Tables.Count > 1)
{
_log.WarnFormat("Sequence File had multiple worksheets : {0} ", file);
}
DataTable firstWorksheet = fileData.Tables[0];
if (firstWorksheet.Rows == null || firstWorksheet.Rows.Count < 2)
{
_log.ErrorFormat("Sequence File didn't have enough rows: {0} ", file);
continue;
}
else if (firstWorksheet.Rows.Count > 2)
{
_log.WarnFormat("Sequence File had too many rows: {0} ", file);
}
//Expected values of row: FILEID,FILETYPE,STUSAB,CHARITER,SEQUENCE,LOGRECNO,...
DataRow columnIDRow = firstWorksheet.Rows[0];
DataRow columnNameRow = firstWorksheet.Rows[1];
if (columnIDRow.ItemArray == null || columnIDRow.ItemArray.Length < 7)
{
_log.Error("One of the sequence files had bad data, skipping\n\t" + file);
continue;
}
//Add data to database
for (int i = 6; i < columnIDRow.ItemArray.Length; i++)
{
//This file has _ separating Table Number and offset, everywhere else doesn't
string columnID = columnIDRow[i].ToString().Trim().Replace("_", "");
string columnName = (columnNameRow[i] as string);
// ixid, CENSUS_TABLE_ID, NAME, COLNO, SEQNO
var toAdd = new object[] { ixid++, columnID, columnName, i, seqNo };
table.Rows.Add(toAdd);
}
}
if ((table != null) && (table.Rows.Count > 0))
{
_log.Debug("Saving... (This may take a while)");
adapter.Update(table);
table.AcceptChanges();
}
else
{
_log.Error("Could not read any of the sequence files!");
return false;
}
_log.Debug("Importing Sequence Files... Done!");
return true;
}
else
{
_log.Error("Could not find column mappings directory file, table not initialized!");
return false;
}
}
/// <summary>
/// Call this anyway, should only execute code inside safe blocks
/// </summary>
/// <returns></returns>
protected bool InitDatabase()
{
if (!DbClient.TestDatabaseConnection())
{
_log.Error("InitDatabase failed: Unable to connect to database");
return false;
}
using (var conn = DbClient.GetConnection())
{
_log.Debug("Checking for geographies table...");
if (!DataClient.HasTable(conn, DbClient, this.GetGeographyTablename()))
{
if (!CreateGeographiesTable(conn))
{
//error message is in guard function
return false;
}
}
_log.Debug("Checking for columnMappings table...");
if ((!DataClient.HasTable(conn, DbClient, "columnMappings"))
|| (DataClient.RowCount(conn, DbClient, "columnMappings") == 0))
{
if (!CreateColumnMappingsTable(conn))
{
//error message is in guard function
return false;
}
}
}
return true;
}
/// <summary>
/// Returns all the variable names in the columnMappings table
/// </summary>
/// <returns></returns>
public DataTable GetAllSequenceVariables()
{
using (var conn = DbClient.GetConnection())
{
return DataClient.GetMagicTable(conn, DbClient, "select CENSUS_TABLE_ID, COLNAME from columnMappings");
}
}
public HashSet<string> GetFilteredLRUs(DbConnection conn)
{
_log.Debug("Filtering requested LRUs");
HashSet<string> results = new HashSet<string>();
if (string.IsNullOrEmpty(this.SummaryLevel))
{
//self-heal if summary level wasn't provided
_log.Error("No Summary Level Selected -- defaulting to Block groups \"150\" -- ");
this.SummaryLevel = "150";
}
if (!string.IsNullOrEmpty(this.SummaryLevel))
{
string sql = string.Format("select LOGRECNO from {0} where SUMLEVEL = @sum", this.GetGeographyTablename());
using (var cmd = DbClient.GetCommand(sql, conn))
{
DbClient.AddParameter(cmd, "sum", this.SummaryLevel);
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
string lrn = reader.GetString(0);
results.Add(lrn);
}
}
}
}
return results;
}
/// <summary>
/// Currently rebuilds the requested variables table every time
/// </summary>
/// <param name="conn"></param>
/// <returns></returns>
public DataTable GetRequestedVariables(DbConnection conn)
{
_log.Debug("Processing requested variables... ");
DataTable dt = null;
if (!string.IsNullOrEmpty(DesiredVariablesFilename))
{
DesiredColumnsReader fileReader = new DesiredColumnsReader();
bool importSucceeded = fileReader.ImportDesiredVariables(conn, DbClient,
this.DesiredVariablesFilename, DbConstants.TABLE_DesiredColumns);
if (importSucceeded)
{
string getRequestedCount = string.Format(
@"SELECT * FROM ""{0}"" ;",
DbConstants.TABLE_DesiredColumns);
DataTable desiredVars = DataClient.GetMagicTable(conn, DbClient, getRequestedCount);
int numDesired = desiredVars.Rows.Count;
_log.DebugFormat("Variable file {0} imported successfully", this.DesiredVariablesFilename);
string getRequestedVariablesSQL = string.Format(
@"SELECT columnMappings.CENSUS_TABLE_ID,
columnMappings.COLNO,
columnMappings.SEQNO,
{0}.CUSTOM_COLUMN_NAME AS COLNAME
FROM columnMappings, ""{0}""
WHERE columnMappings.CENSUS_TABLE_ID = {0}.CENSUS_TABLE_ID;",
DbConstants.TABLE_DesiredColumns);
dt = DataClient.GetMagicTable(conn, DbClient, getRequestedVariablesSQL);
if ((dt == null) || (numDesired != dt.Rows.Count))
{
_log.Warn("I couldn't find one or more of the variables you requested.");
HashSet<string> foundVarsSet = new HashSet<string>();
if (dt != null)
{
foreach (DataRow dr in dt.Rows)
{
foundVarsSet.Add(dr["CENSUS_TABLE_ID"] as string);
}
}
foreach (DataRow dr in desiredVars.Rows)
{
var varName = dr["CENSUS_TABLE_ID"] as string;
if (!foundVarsSet.Contains(varName))
{
_log.ErrorFormat("Could not find requested variable \"{0}\"", varName);
}
}
_log.Debug("Processing requested variables... Done -- with errors");
//make tests pass
if (dt.Rows.Count == 0)
return null;
return dt;
}
}
else
{
_log.Warn("Processing requested variables... Failed!");
return null;
}
}
else
{
_log.Debug("No variables file specified");
}
_log.Debug("Processing requested variables... Done!");
return dt;
}
public List<IGeometry> GetFilteringGeometries(string filename, ICoordinateSystem outputCrs)
{
if ((string.IsNullOrEmpty(filename)) || (!File.Exists(filename)))
{
_log.ErrorFormat("GetFilteringGeometries failed, shapefile is empty or does not exist {0} ", filename);
return null;
}
//inputCrs should be valid if LoadShapefile returns true
ICoordinateSystem inputCrs;
if (!ShapefileHelper.LoadShapefile(filename, Path.GetFileNameWithoutExtension(filename), DbClient, out inputCrs))
{
_log.Error("Could not load filtering geometries!");
return null;
}
string tableName = Path.GetFileNameWithoutExtension(filename);
string sqlcmd = string.Format("SELECT AsBinary(Geometry) AS Geometry FROM \"{0}\" ", tableName);
var wholeShapeTable = DataClient.GetMagicTable(DbClient.GetConnection(), DbClient, sqlcmd);
List<IGeometry> results = new List<IGeometry>(wholeShapeTable.Rows.Count);
ICoordinateTransformation reprojector = null;
if (outputCrs != null)
{
reprojector = Utilities.BuildTransformationObject(inputCrs, outputCrs);
}
GisSharpBlog.NetTopologySuite.IO.WKBReader binReader = new WKBReader(
new GeometryFactory());
foreach (DataRow row in wholeShapeTable.Rows)
{
byte[] geomBytes = (byte[])row["Geometry"];
IGeometry geom = binReader.Read(geomBytes);
if (geom == null || geom.Dimension != Dimensions.Surface)
{
continue;
}
if (reprojector != null)
{
geom = Utilities.ReprojectGeometry(geom, reprojector);
}
results.Add(geom);
}
//Cleanup so we don't store lots of crap in database
sqlcmd = string.Format("DROP TABLE \"{0}\" ", tableName);
var droptable = DbClient.GetCommand(sqlcmd);
droptable.ExecuteNonQuery();
if (results.Count == 0)
{
_log.Error("Could not use shapefile to create filter because no two dimensional geometries were found");
return null;
}
return results;
}
/// <summary>
/// Gets the filtered LogicalRecordNumbers, and the requested variables, and builds a table of their crossjoin
/// </summary>
/// <param name="tableName"></param>
/// <returns></returns>
public bool CheckBuildVariableTable(string tableName)
{
try
{
using (var conn = DbClient.GetConnection())
{
if (DataClient.HasTable(conn, DbClient, tableName))
{
if (!ReusePreviousJobTable)
{
DbClient.GetCommand(string.Format("DROP TABLE IF EXISTS \"{0}\";", tableName), conn).ExecuteNonQuery();
}
else
{
_log.DebugFormat("Table {0} was already built", tableName);
return true;
}
}
//gets a list of the LRUs we want
HashSet<string> requestedLRNs = GetFilteredLRUs(conn);
//gets all the variable mapping information we need
DataTable reqVariablesDT = GetRequestedVariables(conn);
if ((reqVariablesDT == null) || (reqVariablesDT.Rows.Count == 0))
{
_log.Info("Zero variables found: I couldn't understand those variables, can you check them and try again?");
//_log.Warn("I didn't understand those variables, can you check them and try again?");
return false;
}
DataTable newTable = new DataTable();
newTable.Columns.Add("LOGRECNO", typeof(string));
Dictionary<string, DataRow> rowsByLRN = new Dictionary<string, DataRow>(requestedLRNs.Count);
foreach (var id in requestedLRNs)
{
var row = newTable.NewRow();
row[0] = id;
newTable.Rows.Add(row);
rowsByLRN[id] = row;
}
bool shouldNotParseErrorValues = PreserveJam;
_log.Debug("Importing Columns");
int varNum = 0;
foreach (DataRow variableRow in reqVariablesDT.Rows)
{
if (this.IsCancelled()) { return false; }
varNum++;
var sequenceNo = Utilities.GetAs<int>(variableRow["SEQNO"] as string, -1);
var seqFile = Directory.GetFiles(this.GetAggregateDataPath(), "e*" + sequenceNo.ToString("0000") + "000.txt"); //0001000
if ((seqFile == null) || (seqFile.Length == 0))
{
_log.DebugFormat("Couldn't find sequence file {0}", sequenceNo);
continue;
}
var errorFile = Directory.GetFiles(this.GetAggregateDataPath(), "m*" + sequenceNo.ToString("0000") + "000.txt"); //0001000
if ((errorFile == null) || (errorFile.Length == 0))
{
_log.DebugFormat("Couldn't find error margin file {0}", sequenceNo);
}
//These next two if statement checks should probably be removed once
//#19869 is resolved
//Until that case is resolved, we can't guarantee rows in reqVariablesDT will be
//unique so they should stay.
//TODO: alternate column naming?
string newColumnName = variableRow["COLNAME"] as string;
if (newTable.Columns.Contains(newColumnName))
{
newColumnName = newColumnName + varNum;
}
newTable.Columns.Add(newColumnName, typeof(double));
//this really ought to be unique.
string newErrorMarginColumnName = "m" + newColumnName;
if (newTable.Columns.Contains(newErrorMarginColumnName))
{
newErrorMarginColumnName = newErrorMarginColumnName + varNum;
}
if (shouldNotParseErrorValues)
{
newTable.Columns.Add(newErrorMarginColumnName, typeof(string));
}
else
{
newTable.Columns.Add(newErrorMarginColumnName, typeof(double));
}
_log.DebugFormat("Importing {0}...", newColumnName);
int columnIDX = Utilities.GetAs<int>(variableRow["COLNO"] as string, -1);
CommaSeparatedValueReader reader = new CommaSeparatedValueReader(seqFile[0], false);
foreach (List<string> values in reader)
{
string lrn = values[5];
if (!requestedLRNs.Contains(lrn))
continue;
if (columnIDX < values.Count)
{
double val = Utilities.GetAs<double>(values[columnIDX], double.NaN);
if (!double.IsNaN(val))
{
rowsByLRN[lrn][newColumnName] = val;
}
}
if (this.IsCancelled()) { break; }
}
reader.Close();
//these error files better have the exact same format!
reader = new CommaSeparatedValueReader(errorFile[0], false);
foreach (List<string> values in reader)
{
string lrn = values[5];