-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCountyParcel_Transform.py
3242 lines (2868 loc) · 164 KB
/
CountyParcel_Transform.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
"""
CountyParcel_Transform.py
Created: June 15th,2023
Last Updated: January 26, 2025
Amy Fish, Tahoe Regional Planning Agency
Andy McClary, Tahoe Regional Planning Agency
Mason Bindl, Tahoe Regional Planning Agency
This python script was developed to get data from the five Tahoe Counties.
El Dorado, Carson, Douglas, Placer, and Washoe.
The data is then staged for transformation.
This script uses Python 3.x and was designed to be used with
the default ArcGIS Pro python enivorment ""C:/Program Files/ArcGIS/Pro/bin/Python/envs/arcgispro-py3/python.exe"", with
no need for installing new libraries.
This script runs on the 16th of each month at 1am on Arc10 from scheduled task "CountyParcelTransform"
"""
#----------------------------------------------------------------------
# SETUP
#----------------------------------------------------------------------
# import packages
import os
import sys
import re
import logging
from datetime import datetime
import time
import pandas as pd
import arcpy
from time import strftime
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
# environment settings
arcpy.env.workspace = "//Trpa-fs01/GIS/PARCELUPDATE/Workspace/ParcelStaging.gdb"
arcpy.env.overwriteOutput = True
arcpy.env.outputCoordinateSystem = arcpy.SpatialReference(26910)
# set workspace and sde connections
workspace = "F:/GIS/PARCELUPDATE/Workspace/Staging"
# network path to connection files
filePath = "F:/GIS/PARCELUPDATE/Workspace/"
# database file path
sdeBase = os.path.join(filePath, "Vector.sde/")
sdeCollect = os.path.join(filePath, "Collection.sde")
sdeTabular = os.path.join(filePath, "Tabular.sde/")
# portal signin
## TRPA_ADMIN credentials
# portal_user = "TRPA_PORTAL_ADMIN"
# portal_pwd = str(os.environ.get('Password'))
# portal_url = "https://maps.trpa.org/portal/"
# # sign in
# arcpy.SignInToPortal(portal_url, portal_user, portal_pwd)
# Parcel AOI to select parcels to keep (includes TRPA Boundary and Olympic Valley Watershed)
parcelAOI = "Parcel_AOI"
#sde feature classes to use in attribution stage
sde_Impervious = sdeBase + "\\sde.SDE.Impervious\\sde.SDE.Impervious_2019"
sde_Bailey = sdeBase + "\\sde.SDE.Soils\sde.SDE.land_capability_Bailey_Soils"
sde_RegionalLandUse = os.path.join(sdeBase,"sde.SDE.Planning/sde.SDE.RegionalLandUse")
sde_NRCSSoils1974 = sdeBase + "\\sde.SDE.Soils\\sde.SDE.NRCS_Soils_1974"
sde_NRCSSoils2003 = sdeBase + "\\sde.SDE.Soils\\sde.SDE.NRCS_Soils_2003"
sde_Catchment = sdeBase + "\\sde.SDE.WaterQuality\\sde.SDE.TMDL_Catchment"
sde_HydroArea = sdeBase + "\\sde.SDE.Water\\sde.SDE.Hydro_Areas"
sde_Watershed = sdeBase + "\\sde.SDE.Water\\sde.SDE.Watershed"
sde_FireDistrict = sdeBase + "\\sde.SDE.Jurisdictions\\sde.SDE.FireDistricts"
sde_LocalPlan = sdeBase + "\\sde.SDE.Planning\\sde.SDE.LocalPlan"
sde_SpecialDistrict = sdeBase + "\\sde.SDE.Planning\\sde.SDE.SpecialPlanningDistrict"
sde_CSLT = sdeBase + "\\sde.SDE.Jurisdictions\\sde.SDE.CSLT"
sde_CurrentParcels = sdeBase + "\\sde.SDE.Parcels\\sde.SDE.Parcel_Master"
sde_Zoning = sdeBase + "\\sde.SDE.Planning\\sde.SDE.District"
sde_TownCenter = sdeBase + "\\sde.SDE.Planning\\sde.SDE.TownCenter"
sde_TownCenterBuffer = sdeBase + "\\sde.SDE.Planning\\sde.SDE.TownCenter_Buffer"
sde_Index1987 = sdeBase + "\\sde.SDE.Index\\sde.SDE.AssessorMapIndex_1987"
sde_TRPAboundary = sdeBase + "\\sde.SDE.Jurisdictions\\sde.SDE.TRPA_bdy"
sde_BonusUnitboundary= sdeBase + "\\sde.SDE.Planning\\sde.SDE.Bonus_unit_boundary"
sde_UrbanArea = sdeBase + "\\sde.SDE.Jurisdictions\\sde.SDE.UrbanAreas"
sde_Zip = sdeBase + "\\sde.SDE.Jurisdictions\\sde.SDE.Postal_ZIP"
sde_TAZ = sdeBase + "\\sde.SDE.Transportation\\sde.SDE.Transportation_Analysis_Zone"
sde_Littoral = sdeBase + "\\sde.SDE.Shorezone\\sde.SDE.LittoralParcel"
sde_Tolerance = sdeBase + "\\sde.SDE.Shorezone\\sde.SDE.Tolerance_District"
# sde Collect feature classes to use for attribution
sde_collect_IPES = os.path.join(sdeCollect, 'SDE.Parcel\SDE.Parcel_LTinfo_IPES')
sde_collect_LCV = os.path.join(sdeCollect, 'SDE.Parcel\SDE.Parcel_LTinfo_LCV')
sde_collect_BMP = os.path.join(sdeCollect, 'SDE.Parcel\SDE.Parcel_BMP')
sde_collect_Deed = os.path.join(sdeCollect, 'SDE.Parcel\SDE.Parcel_LTinfo_Deed_Restriction')
sde_collect_VHR = os.path.join(sdeCollect, 'SDE.Parcel\SDE.Parcel_VHR')
# in memory fcs to use in the attribution stage
memory = "memory" + "\\"
ParcelPoint_RegionalLandUse = memory + "ParcelPoint_RegionalLandUse"
ParcelPoint_Soils74 = memory + "ParcelPoint_Soils74"
ParcelPoint_Soils03 = memory + "ParcelPoint_Soils03"
ParcelPoint_Catchment = memory + "ParcelPoint_Catchment"
ParcelPoint_HydroArea = memory + "ParcelPoint_HydroArea"
ParcelPoint_Watershed = memory + "ParcelPoint_Watershed"
ParcelPoint_FireDistrict = memory + "ParcelPoint_FireDistrict"
ParcelPoint_LocalPlan = memory + "ParcelPoint_LocalPlan"
ParcelPoint_TownCenter = memory + "ParcelPoint_TownCenter"
ParcelPoint_TownCenterBuffer= memory + "ParcelPoint_TownCenterBuffer"
ParcelPoint_Zoning = memory + "ParcelPoint_Zoning"
ParcelPoint_SpecialDistrict = memory + "ParcelPoint_SpecialDistrict"
ParcelPoint_Index1987 = memory + "ParcelPoint_Index1987"
ParcelPoint_PstlTown = memory + "ParcelPoint_PstlTown"
ParcelPoint_PstlZip = memory + "ParcelPoint_PstlZip"
ParcelPoint_CSLT = memory + "ParcelPoint_CSLT"
ParcelPoint_TAZ = memory + "ParcelPoint_TAZ"
ParcelPoint_Design = memory + "ParcelPoint_Design"
ParcelPoint_Littoral = memory + "ParcelPoint_Littoral"
ParcelPoint_Tolerance = memory + "ParcelPoint_Tolerance"
# Set up fields to add to FGDB.
baseFields = [
# apn ppno
['APN_TRPA', 'TEXT', 'APN', 50],
['PPNO_TRPA', 'DOUBLE','PPNO'],
['JURISDICTION_TRPA', 'TEXT', 'Jurisdiction', 4],
['COUNTY_TRPA', 'TEXT', 'County', 2],
# parcel address
['HSE_NUMBR_TRPA', 'TEXT', 'House Number', 25],
['UNIT_NUMBR_TRPA', 'TEXT', 'Unit Number', 50],
['STR_DIR_TRPA', 'TEXT','Street Direction', 5],
['STR_NAME_TRPA', 'TEXT', 'Street Name', 100],
['STR_SUFFIX_TRPA', 'TEXT', 'Street Suffix', 6],
['APO_ADDRESS_TRPA', 'TEXT', 'Full Address', 100],
['PSTL_TOWN_TRPA', 'TEXT', 'Postal Town', 25],
['PSTL_STATE_TRPA', 'TEXT', 'Postal State', 2],
['PSTL_ZIP5_TRPA', 'TEXT', 'Postal Zip Code', 5],
# owner info
['OWN_FIRST_TRPA', 'TEXT', 'Owner First Name', 255],
['OWN_LAST_TRPA', 'TEXT', 'Owner Last Name', 255],
['OWN_FULL_TRPA', 'TEXT', 'Owner Name', 255],
# swap this in soon
# ['OWNER_NAME_TRPA', 'TEXT', 'Owner Name', 255],
['MAIL_ADD1_TRPA', 'TEXT', 'Mailing Address', 100],
['MAIL_CITY_TRPA', 'TEXT', 'Mailing City', 50],
#['MAIL_STATE_TRPA', 'TEXT', 'Mailing State', 25],
['MAIL_STATE_TRPA', 'TEXT', 'Mailing State', 2],
['MAIL_ZIP5_TRPA', 'TEXT', 'Mailing Zip Code', 5],
# value fields
['AS_LANDVALUE_TRPA', 'LONG','Assessed Land Value'],
['AS_IMPROVALUE_TRPA', 'LONG','Assessed Improved Value'],
['AS_SUM_TRPA', 'LONG', 'Assessed Sum Value'],
['TAX_LANDVALUE_TRPA', 'LONG','Tax Land Value'],
['TAX_IMPROVALUE_TRPA', 'LONG','Tax Improved Value'],
['TAX_SUM_TRPA', 'LONG','Tax Sum'],
['TAX_YEAR_TRPA', 'TEXT','Tax Year', 5],
# jurisdiction land use fields
['COUNTY_LANDUSE_CODE_TRPA', 'TEXT', 'County Landuse Code', 50],
['COUNTY_LANDUSE_TRPA', 'TEXT', 'County Landuse', 250],
# Fields for building info
["YEAR_BUILT_TRPA", "SHORT", 'Year Built', 5],
['UNITS_TRPA', 'DOUBLE', 'Units', 5],
["BEDROOMS_TRPA", "DOUBLE",'Bedrooms'],
['BATHROOMS_TRPA', 'DOUBLE', 'Bathrooms'],
['BUILDING_SQFT_TRPA', 'DOUBLE', 'Building Size'],
# fields to add?
["VHR_TRPA", "TEXT", "Vacation Home Rental", 3],
["HOA_TRPA", "TEXT", "Home Owners Association", 3]
]
trpaFields = [
# land use
['OWNERSHIP_TYPE_TRPA', 'TEXT', 'Ownership Type', 50],
['EXISTING_LANDUSE_TRPA', 'TEXT', 'Existing Landuse', 50],
['REGIONAL_LANDUSE_TRPA', 'TEXT', 'Regional Landuse', 50],
# Fields for soil, watershed, etc...
['ESTIMATED_COVERAGE_ALLOWED_TRPA', 'DOUBLE', "Estimate of Coverage Allowed (Bailey, sq.ft.)"],
#['ESTIMATED_PRCNT_COV_ALLOWED_TRPA', 'DOUBLE', "Estimated Percent Coverage Allowed (Bailey, sq.ft.)"],
['ESTIMATED_PRCNT_COV_ALLOWED_TRPA', 'SHORT', "Estimated Percent Coverage Allowed (Bailey, sq.ft.)"],
['IMPERVIOUS_SURFACE_SQFT_TRPA', 'DOUBLE', "Impervious Surface (Remote Sensing, sq.ft.)"],
['SOIL_1974_TRPA', 'TEXT','NRCS Soils 1974', 5],
["SOIL_2003_TRPA", "TEXT", "NRCS Soils 2003", 5],
["CATCHMENT_TRPA", "TEXT", "Catchment", 150],
["HRA_NAME_TRPA", "TEXT", "Hydrologic Resource Area", 30],
["WATERSHED_NUMBER_TRPA", "SHORT", "Watershed Number"],
["WATERSHED_NAME_TRPA", "TEXT", "Watershed Name", 30],
["PRIORITY_WATERSHED_TRPA", "TEXT", "Priority Watershed", 2],
["FIREPD_TRPA", "TEXT", "Fire Protection District", 25],
# Fields for Planning purposes
["PLAN_ID_TRPA", "TEXT", 'Plan ID',8],
["PLAN_NAME_TRPA", "TEXT", 'Plan Name', 40],
["PLAN_TYPE_TRPA", "TEXT", 'Plan Type', 40],
["ZONING_ID_TRPA", "TEXT", 'Zoning ID', 50],
["ZONING_DESCRIPTION_TRPA", "TEXT", 'Zoning Description',500],
["TOWN_CENTER_TRPA", "TEXT",'Town Center', 50],
["LOCATION_TO_TOWNCENTER_TRPA", "TEXT", 'Location Relative to Town Center', 50],
["TOLERANCE_ID_TRPA", "TEXT", 'Tolerance ID', 50],
["TAZ_TRPA", "DOUBLE",'Transportation Analysis Zone'],
["INDEX_1987_TRPA", "TEXT", "1987 Parcel Map Index",10],
["IPES_TRPA", "LONG", "IPES Score"],
["WITHIN_TRPA_BNDY_TRPA", "SHORT","Within TRPA Boundary?"],
["WITHIN_BONUSUNIT_BNDY_TRPA", "SHORT", "Within Bonus Unit Boundary"],
["LOCAL_PLAN_HYPERLINK_TRPA", "TEXT", "Local Plan Hyperlink", 255],
["DESIGN_GUIDELINES_HYPERLINK_TRPA", "TEXT", "Design Guidelines", 255],
["LTINFO_HYPERLINK_TRPA", "TEXT", "LTinfo Parcel Details", 255],
["INDEX_1987_HYPERLINK_TRPA", "TEXT", "Index 1987 Hyperlink", 255],
["STATUS_TRPA",'TEXT',"Status",1],
# Fields for Parcel Size
["PARCEL_ACRES_TRPA", "DOUBLE", "Acres"],
["PARCEL_SQFT_TRPA", "DOUBLE", "Square Feet"]
]
#----------------------------------------------------------------------
# LOGGING
#----------------------------------------------------------------------
# Configure the logging
log_file_path = os.path.join(workspace, "ParcelTransformation.log") # Specify the path to your local directory
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
filename=log_file_path, # Set the log file path
filemode='w')
# Create a logger
logger = logging.getLogger(__name__)
# start a timer for the entire script run
FIRSTstartTimer = datetime.datetime.now()
# Log different types of messages
logger.info("Script Started: " + str(FIRSTstartTimer) + "\n")
# Setup Counties to run
counties_to_run = ['El Dorado', 'Placer', 'Douglas', 'Washoe', 'Carson City']
##--------------------------------------------------------------------------------------------------------#
## SETUP SEND EMAIL WITH LOG FILE ##
##--------------------------------------------------------------------------------------------------------#
# path to text file
fileToSend = log_file_path
# email parameters
subject = "Parcel Transformation Log File"
sender_email = "infosys@trpa.org"
# password = ''
receiver_email = "afish@trpa.gov"
#----------------------------------------------------------------------
# FUNCTIONS
#----------------------------------------------------------------------
### Functions ###
# time a function function
## use as decorator @timer
def timer(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
print(f"Function {func.__name__} took {end_time - start_time} seconds to execute.")
return result
return wrapper
def get_text_fields(feature_class):
field_list = []
fields = arcpy.ListFields(feature_class)
for field in fields:
if field.type == 'String':
field_list.append(field.name)
return field_list
# set none to '' for all cells
@timer
def replace_null_values_with_blank(fc):
field_list = get_text_fields(fc)
with arcpy.da.UpdateCursor(fc, field_list) as cursor:
for row in cursor:
for i in range(len(row)):
if row[i] is None:
row[i] = ""
cursor.updateRow(row)
@timer
def UpdateFieldFromDictionary(featureclass, field, update_dictionary):
record_count = 0
with arcpy.da.UpdateCursor(featureclass, field) as cursor:
for row in cursor:
key_field_value = row[0]
if key_field_value in update_dictionary:
row[0] = update_dictionary[key_field_value]
cursor.updateRow(row)
record_count+=record_count
logger.info(f"{record_count} rows were updated")
#record_count = 0
# combine duplicate records, creating multipart and dissolved polygons
@timer
def CombineAPNs(fc, fld_dissolve):
try:
from time import strftime
print("Started combining APNs: " + strftime("%Y-%m-%d %H:%M:%S"))
# get unique values from field
value_list = [r[0] for r in arcpy.da.SearchCursor(fc, (fld_dissolve))]
unique_vals = list(set(value_list))
if len(value_list) !=len(unique_vals):
seen = set()
dup_vals = set()
for x in value_list:
if x in seen:
dup_vals.add(x)
else:
seen.add(x)
print(dup_vals)
dup_vals.remove('')
for unique_val in dup_vals:
geoms = [r[0] for r in arcpy.da.SearchCursor(fc, ('SHAPE@', fld_dissolve)) if r[1] == unique_val]
#Probably don't need this as there will always be more than one geometry
if len(geoms) > 1:
print(unique_val)
diss_geom = DissolveGeoms(geoms)
# update the first feature with new geometry and delete the others
where = "{} = '{}'".format(fld_dissolve, unique_val)
cnt = 0
with arcpy.da.UpdateCursor(fc, ('SHAPE@'), where) as curs:
for row in curs:
cnt += 1
if cnt == 1:
row[0] = diss_geom
curs.updateRow(row)
else:
curs.deleteRow()
else:
print("No duplicates!")
print ("Finished combining APNs: " + strftime("%Y-%m-%d %H:%M:%S"))
except Exception as e:
exc_type, exc_obj, tb = sys.exc_info()
f = tb.tb_frame
lineno = tb.tb_lineno
print(str(lineno) + ": " + e.args[0])
logger.error(e)
# union all geometry inputs into one dissolved geometry
@timer
def DissolveGeoms(geoms):
cnt = 0
for geom in geoms:
cnt += 1
if cnt == 1:
diss_geom = geom
else:
diss_geom = diss_geom.union(geom)
return diss_geom
# moves attribute values from one feature class to the other using an aspatial join
@timer
def fieldJoinCalc(updateFC, updateFieldsList, sourceFC, sourceFieldsList):
from time import strftime
logger.info("Started data transfer: " + strftime("%Y-%m-%d %H:%M:%S"))
# Use list comprehension to build a dictionary from arcpy SearchCursor
valueDict = {r[0]:(r[1:]) for r in arcpy.da.SearchCursor(sourceFC, sourceFieldsList)}
with arcpy.da.UpdateCursor(updateFC, updateFieldsList) as updateRows:
for updateRow in updateRows:
# store the Join value of the row being updated in a keyValue variable
keyValue = updateRow[0]
# verify that the keyValue is in the Dictionary
if keyValue in valueDict:
# transfer the value stored under the keyValue from the dictionary to the updated field.
updateRow[1] = valueDict[keyValue][0]
updateRows.updateRow(updateRow)
del valueDict
logger.info("Finished data transfer: " + strftime("%Y-%m-%d %H:%M:%S"))
# transfer attributes frome one feature class field to another while using multiple fields to create the keys
@timer
def fieldJoinCalc_multikey(updateFC, updateFieldsList_key, updateFieldsList_value, sourceFC, sourceFieldsList_key, sourceFieldsList_value):
from time import strftime
print ("Started data transfer: " + strftime("%Y-%m-%d %H:%M:%S"))
# Use list comprehension to build a dictionary from arcpy SearchCursor
total_count=0
valueDict = {(r[0]+r[1]):(r[2]) for r in arcpy.da.SearchCursor(sourceFC, (sourceFieldsList_key + sourceFieldsList_value)) if r[0] is not None and r[1] is not None}
with arcpy.da.UpdateCursor(updateFC, (updateFieldsList_key+ updateFieldsList_value)) as updateRows:
for updateRow in updateRows:
# store the Join value of the row being updated in a keyValue variable
if updateRow[0] is not None and updateRow[1] is not None:
keyValue = updateRow[0]+updateRow[1]
# verify that the keyValue is in the Dictionary
if keyValue in valueDict:
total_count +=1
if (total_count%1000)==0:
print (f"Updating row {total_count}")
# transfer the value stored under the keyValue from the dictionary to the updated field.
updateRow[2] = valueDict[keyValue]
updateRows.updateRow(updateRow)
del valueDict
#logger.info("Finished data transfer: " + strftime("%Y-%m-%d %H:%M:%S"))
# send email with attachments
def send_mail(body):
msg = MIMEMultipart()
msg['Subject'] = subject
msg['From'] = sender_email
msg['To'] = receiver_email
msgText = MIMEText('%s<br><br>Cheers,<br>GIS Team' % (body), 'html')
msg.attach(msgText)
attachment = MIMEText(open(fileToSend).read())
attachment.add_header("Content-Disposition", "attachment", filename = os.path.basename(fileToSend))
msg.attach(attachment)
try:
with smtplib.SMTP("mail.smtp2go.com", 25) as smtpObj:
smtpObj.ehlo()
smtpObj.starttls()
# smtpObj.login(sender_email, password)
smtpObj.sendmail(sender_email, receiver_email, msg.as_string())
except Exception as e:
logger.error(e)
# Function to check if a county exists in the list of counties to run
def is_county_in_list(county, county_list):
return county in county_list
#-----------------------------------------------------------------------
# START TRANSFORMATION
#-----------------------------------------------------------------------
try:
# start timer for the get data requests
startTimer = datetime.datetime.now()
#-----------------------------------------------------------------------
# CARSON COUNTY TRANSFORMATION
#-----------------------------------------------------------------------
# get staging feature class and name output transformed feature class
county_to_check = 'Carson City'
exists = is_county_in_list(county_to_check, counties_to_run)
print(f"Is {county_to_check} in the list? {exists}")
if exists == 1:
in_features = "Parcel_CC_Extracted"
parcel_out = "Parcel_CC_Transformed"
# in-memory feature class
carsonParcel = r"in_memory/inMemoryFeatureClass"
# copy feature class into in-memory feature class to work on
arcpy.management.CopyFeatures(in_features, carsonParcel)
# Add TRPA base fields
arcpy.management.AddFields(carsonParcel, baseFields)
with arcpy.da.UpdateCursor(carsonParcel, [
'APN_TRPA', 'PPNO_TRPA', 'JURISDICTION_TRPA', 'HSE_NUMBR_TRPA',
'STR_DIR_TRPA', 'STR_NAME_TRPA', 'STR_SUFFIX_TRPA', 'UNIT_NUMBR_TRPA',
'APO_ADDRESS_TRPA', 'PSTL_TOWN_TRPA', 'PSTL_STATE_TRPA', 'PSTL_ZIP5_TRPA',
'OWN_FULL_TRPA', 'MAIL_ADD1_TRPA', 'MAIL_CITY_TRPA', 'MAIL_STATE_TRPA',
'MAIL_ZIP5_TRPA', 'AS_LANDVALUE_TRPA', 'AS_IMPROVALUE_TRPA', 'AS_SUM_TRPA',
'TAX_LANDVALUE_TRPA', 'TAX_IMPROVALUE_TRPA', 'TAX_SUM_TRPA', 'TAX_YEAR_TRPA',
'COUNTY_LANDUSE_CODE_TRPA', 'COUNTY_LANDUSE_TRPA', 'YEAR_BUILT_TRPA',
'UNITS_TRPA', 'BEDROOMS_TRPA', 'BATHROOMS_TRPA', 'BUILDING_SQFT_TRPA',
'VHR_TRPA', 'HOA_TRPA', 'APN', 'APN_NUM', 'Phy_Addr', 'Loc1', 'Dir',
'Street_Name', 'Unit', 'Legal_Owner', 'Mail_Addr', 'Mail2_Addr', 'MCity',
'MZip', 'Land_Value', 'Improv_Val', 'LU', 'Total_DWUnits'
]) as cursor:
for row in cursor:
# Set APN
apn = row[cursor.fields.index('APN')]
row[cursor.fields.index('APN_TRPA')] = (apn[:3] + "-" + apn[3:6] + "-" + apn[6:8]) if apn else ''
# Set PPNO
ppno = row[cursor.fields.index('APN_NUM')]
row[cursor.fields.index('PPNO_TRPA')] = int(ppno) if ppno else ''
# Jurisdiction
row[cursor.fields.index('JURISDICTION_TRPA')] = "CC"
# APO Address
full_address = row[cursor.fields.index('Phy_Addr')]
row[cursor.fields.index('APO_ADDRESS_TRPA')] = full_address if full_address else ''
# House Number
house = row[cursor.fields.index('Loc1')]
row[cursor.fields.index('HSE_NUMBR_TRPA')] = str(house) if house else ''
# Street Direction
street_direction = row[cursor.fields.index('Dir')]
row[cursor.fields.index('STR_DIR_TRPA')] = street_direction if street_direction else ''
# Street Name and Suffix
street_name = row[cursor.fields.index('Street_Name')]
if street_name:
parts = street_name.split(" ")
row[cursor.fields.index('STR_NAME_TRPA')] = parts[0]
row[cursor.fields.index('STR_SUFFIX_TRPA')] = parts[-1]
else:
row[cursor.fields.index('STR_NAME_TRPA')] = ''
row[cursor.fields.index('STR_SUFFIX_TRPA')] = ''
# Unit Number
unit = row[cursor.fields.index('Unit')]
row[cursor.fields.index('UNIT_NUMBR_TRPA')] = unit if unit else ''
# Postal State
row[cursor.fields.index('PSTL_STATE_TRPA')] = 'NV'
# Owner Name
owner = row[cursor.fields.index('Legal_Owner')]
row[cursor.fields.index('OWN_FULL_TRPA')] = owner.strip() if owner else ''
# Mailing Address
address1 = row[cursor.fields.index('Mail_Addr')]
address2 = row[cursor.fields.index('Mail2_Addr')]
row[cursor.fields.index('MAIL_ADD1_TRPA')] = address2.strip() if address2 else address1.strip() if address1 else ''
# Mailing City
mail_city = row[cursor.fields.index('MCity')]
row[cursor.fields.index('MAIL_CITY_TRPA')] = mail_city.split(',', 1)[0].strip() if mail_city else ''
# Mailing State
mail_state = row[cursor.fields.index('MCity')]
row[cursor.fields.index('MAIL_STATE_TRPA')] = mail_state.split(',')[-1].strip()[:2] if mail_state else ''
# Mailing Zip
mail_zip = row[cursor.fields.index('MZip')]
row[cursor.fields.index('MAIL_ZIP5_TRPA')] = mail_zip[:5] if mail_zip and len(mail_zip) >= 5 else ''
# Assessed Land Value
land_value = row[cursor.fields.index('Land_Value')]
row[cursor.fields.index('AS_LANDVALUE_TRPA')] = land_value if land_value else 0
# Assessed Improved Value
improved_value = row[cursor.fields.index('Improv_Val')]
row[cursor.fields.index('AS_IMPROVALUE_TRPA')] = improved_value if improved_value else 0
# Assessed Sum
row[cursor.fields.index('AS_SUM_TRPA')] = (land_value or 0) + (improved_value or 0)
# Tax Values
row[cursor.fields.index('TAX_LANDVALUE_TRPA')] = (land_value / 0.35) if land_value else None
row[cursor.fields.index('TAX_IMPROVALUE_TRPA')] = (improved_value / 0.35) if improved_value else None
row[cursor.fields.index('TAX_SUM_TRPA')] = ((land_value or 0) / 0.35) + ((improved_value or 0) / 0.35)
# Tax Year
row[cursor.fields.index('TAX_YEAR_TRPA')] = datetime.datetime.now().year
# County Land Use Code
county_luc = row[cursor.fields.index('LU')]
row[cursor.fields.index('COUNTY_LANDUSE_CODE_TRPA')] = str(county_luc) if county_luc else ''
# Units
units = row[cursor.fields.index('Total_DWUnits')]
row[cursor.fields.index('UNITS_TRPA')] = units if units else None
# Update the row
cursor.updateRow(row)
del cursor
out_coordinate_system = arcpy.SpatialReference('NAD 1983 UTM Zone 10N')
arcpy.Project_management(carsonParcel, parcel_out, out_coordinate_system)
print('New Carson Parcels transformed')
logger.info('New Carson Parcels transformed')
#-------------------------------------------------------------------------------------
## DOUGLAS TRANSFORM
#-------------------------------------------------------------------------------------
# get staging feature class and name output trnasformed feature class
county_to_check = 'Douglas'
exists = is_county_in_list(county_to_check, counties_to_run)
print(f"Is {county_to_check} in the list? {exists}")
if exists == 1:
in_features = "Parcel_DG_Extracted"
parcel_out = "Parcel_DG_Transformed"
# in-memory feature class
douglasParcel = r"in_memory/inMemoryFeatureClass"
# copy feature class into in-memory feature class to work on
arcpy.management.CopyFeatures(in_features, douglasParcel)
# Add TRPA base fields
arcpy.management.AddFields(douglasParcel, baseFields)
# Define the fields in a list variable
fields = [
## TRPA base schema ##
'APN_TRPA', #0
'PPNO_TRPA', #1
'JURISDICTION_TRPA', #2
# parcel address
'HSE_NUMBR_TRPA', #3
'STR_DIR_TRPA', #4
'STR_NAME_TRPA', #5
'STR_SUFFIX_TRPA', #6
'UNIT_NUMBR_TRPA', #7
'APO_ADDRESS_TRPA', #8
'PSTL_TOWN_TRPA', #9
'PSTL_STATE_TRPA', #10
'PSTL_ZIP5_TRPA', #11
# owner fields
# no own first and last for DG
'OWN_FULL_TRPA', #12
'MAIL_ADD1_TRPA', #13
'MAIL_CITY_TRPA', #14
'MAIL_STATE_TRPA', #15
'MAIL_ZIP5_TRPA', #16
# value fields
'AS_LANDVALUE_TRPA', #17
'AS_IMPROVALUE_TRPA', #18
'AS_SUM_TRPA', #19
'TAX_LANDVALUE_TRPA', #20
'TAX_IMPROVALUE_TRPA', #21
'TAX_SUM_TRPA', #22
'TAX_YEAR_TRPA', #23
# land use fields
'COUNTY_LANDUSE_CODE_TRPA', #24
'COUNTY_LANDUSE_TRPA', #25
# Fields for building info
"YEAR_BUILT_TRPA", #26
'UNITS_TRPA', #27
'BEDROOMS_TRPA', #28
'BATHROOMS_TRPA', #29
'BUILDING_SQFT_TRPA', #30
'VHR_TRPA', #31
'HOA_TRPA', #32
###-------------------------###
# County Fields to get data from
'APN', #33
'PLOC_', #34
'PLOCDR', #35
'PLOCNM', #36
'PLOCTP', #37
'PLOCU_', #38
'PANAME', #39
'PMADD1', #40
'PMADD2', #41
'PMCTST', #42
'PZIP', #43
'YYEAR', #44
'YLDUSE', #45
'YLANDV', #46
'YIMPRV', #47
'YEXMP', #48
'YNETV', #49
'PCONYR', #50
'PBEDS', #51
'PBATHS'] #52
with arcpy.da.UpdateCursor(douglasParcel, fields) as cursor:
# loop through each record and transform the values
for row in cursor:
# APN field
# Get County value
apn = str(row[33])
if not (apn is None or apn == ""):
row[0] =(apn[:4] + "-" + apn[4:6] + "-" + apn[6:9] + "-" + apn[9:12])
else:
row[0] = ""
#PPNO
ppno = row[33]
if not (ppno is None):
row[1] = int(ppno)
else:
row[1] = ''
# Jurisdiction
row[2] = "DG"
# APO Address
house = str(row[34]).strip() if row[34] is not None else ""
street_direction = str(row[35]).strip() if row[35] is not None else ""
street_name = str(row[36]).strip() if row[36] is not None else ""
street_suffix = str(row[37]).strip() if row[37] is not None else ""
unit = str(row[38]).strip() if row[38] is not None else ""
if not (street_name is None or street_name=='' or street_name.isspace()==True):
row[8] = re.sub(" +"," ", (house + " " + street_direction +" " + street_name+" " + street_suffix+" " + unit).strip())
else:
row[8] = ''
# House Number
house = row[34]
if not (house is None):
row[3] = str(house)
else:
row[3] = ''
# Street Direction
street_direction = row[35]
if not (street_direction is None or street_direction=='' or street_direction.isspace()==True):
row[4] = street_direction
else:
row[4] = ''
# Street Name
street_name = row[36]
if not (street_name is None or street_name =='' or street_name.isspace()==True):
row[5] = street_name
else:
row[5] = ''
# Street Suffix
street_suffix = row[37]
if not (street_suffix is None or street_suffix =='' or street_suffix.isspace()==True):
row[6] = street_suffix
else:
row[6] = ''
# Unit Number
unit= row[38]
if not (unit is None or unit=='' or unit.isspace()==True):
row[7] = unit
else:
row[7] = ''
# Postal Town - see Search/Update Cursor below
# Postal State
row[10] = 'NV'
# Postal Zip - See Search/Update Cursor below
row[11] = ''
# Owner Name
owner = row[39]
if not (owner is None or owner == '' or owner.isspace()==True):
row[12] = owner.strip()
else:
row[12] = ""
# Mailing Address
address1 = row[40]
address2 = row[41]
if address1 and address2: # Both values are non-empty and not None
row[13] = f"{address1} {address2}"
elif address1: # Only address1 is valid
row[13] = address1
else: # Neither address1 nor address2 is valid
row[13] = ''
# Mailing City
mail_city = str(row[42]).split(',',1)[0].strip()
if not (mail_city is None or mail_city=='' or mail_city.isspace()==True):
row[14] = mail_city
else:
row[14] = ''
# Mailing State - Added logic to set anything that isn't 2 characters long to ''
mail_state = str(row[42]).rsplit(',')[-1].strip().split(' ',1)[0].strip()
if not (mail_state is None or mail_state=='' or mail_state.isspace()==True or len(mail_state)!=2):
row[15] = mail_state[:2]
else:
row[15] = ''
# Mailing Zipcode
#mail_zip = row[43].strip()
mail_zip = row[43]
if not (mail_zip is None or mail_zip=='' or mail_zip.isspace()==True):
row[16] = mail_zip[:5]
else:
row[16] = ''
# Assessed Land Value
land_value = row[46]
if not(land_value is None):
row[17] = land_value
else:
row[17] = ''
# Assessed Improved Value
improved_value = row[47]
if not (improved_value is None):
row[18] = improved_value
else:
row[18] = None
# Assessed Sum
if not (land_value is None or improved_value is None):
assessed_sum = improved_value + land_value
row[19] = assessed_sum
else:
row[19] = None
# Tax Land Value
taxland_value = row[46]
if not(taxland_value is None):
row[20] = taxland_value/0.35
else:
row[20] = None
# Tax Improved Value
taximproved_value = row[47]
if not (taximproved_value is None):
row[21] = taximproved_value/0.35
else:
row[21] = None
# Tax Sum
if not (land_value is None or improved_value is None):
tax_sum = row[49]
row[22] = tax_sum
else:
row[22] = None
# Tax Year
tax_year = row[44]
if not (tax_year is None):
row[23] = tax_year
else:
row[23] = ''
# County Land Use Code
county_luc = row[45]
if not (county_luc is None):
row[24] = str(county_luc)
else:
row[24] = ''
# Year Built
year_built = row[50]
if not (year_built is None or year_built==''):
row[26] = year_built
else:
row[26] = None
# Bedrooms
bedrooms = row[51]
if not (bedrooms is None or bedrooms==''):
row[28] = bedrooms
else:
row[28] = None
# Bathrooms
baths = row[52]
if not (baths is None or baths==''):
row[29] = baths
else:
row[29] = None
# Update the row.
cursor.updateRow(row)
del cursor
out_coordinate_system = arcpy.SpatialReference('NAD 1983 UTM Zone 10N')
arcpy.Project_management(douglasParcel, parcel_out, out_coordinate_system)
print('New Douglas Parcels transformed')
logger.info('New Douglas Parcels Transformed')
#-------------------------------------------------------------------------------------------
# ELDORADO TRANSFORM
#-------------------------------------------------------------------------------------------
# get staging feature class to transform
county_to_check = 'El Dorado'
exists = is_county_in_list(county_to_check, counties_to_run)
print(f"Is {county_to_check} in the list? {exists}")
if exists == 1:
in_features = "Parcel_EL_Extracted"
parcel_out = "Parcel_EL_Transformed"
# in-memory feature class
eldoradoParcel = r"in_memory/inMemoryFeatureClass"
# copy feature class into in-memory feature class to work on
arcpy.management.CopyFeatures(in_features, eldoradoParcel)
# Add TRPA base fields
arcpy.management.AddFields(eldoradoParcel, baseFields)
# Set up the regex queries for the data.
# cityStateZipRegex = r'(.+?)\s([A-Z]{1,2})\s(.+?)$' - Keep in case new one doesn't work out long term.
cityStateZipRegex = r'(.+?)\s([A-Z]{1,2})\s(?=\d)(.*)'
poBoxRegex = r'([^x]+)\W(P\s*O BOX\W*[0-9]{1,6})'
addressRegex = r'(\d{1,5}\D+.+)'
canadaRegex = r'(.+?)\s([A-Z]{1,2})\s(CANADA)\s(.*)'
brazilRegex = r'(.+?)\s(BRAZIL)\s(.*)'
# Set up list for addresses with a country name in the mail_addr4 column.
countriesList = ['japan','canada', 'australia', 'brazil', 'mexico', 'germany', 'france', 'england', 'united kingdom', 'uk', 'china', 'russia', 'india', 'south africa', 'nigeria', 'egypt', 'italy', 'spain', 'argentina', 'peru', 'chile', 'colombia', 'venezuela', 'ecuador', 'bolivia', 'paraguay', 'uruguay', 'panama', 'costa rica', 'nicaragua', 'honduras', 'el salvador', 'guatemala', 'belize', 'jamaica', 'haiti', 'dominican republic', 'cuba', 'bahamas', 'bermuda', 'puerto rico', 'us virgin islands', 'british virgin islands', 'anguilla', 'saint kitts and nevis', 'antigua and barbuda', 'saint lucia', 'saint vincent and the grenadines', 'grenada', 'barbados', 'trinidad and tobago', 'guyana', 'suriname', 'french guiana', 'martinique', 'guadeloupe', 'saint barthelemy', 'saint martin', 'sint maarten', 'aruba', 'curacao', 'bonaire', 'saba', 'sint eustatius', 'turks and caicos islands', 'cayman islands', 'anguilla', 'montserrat', 'bermuda', 'saint pierre and miquelon', 'greenland', 'iceland', 'faroe islands', 'norway', 'sweden', 'finland', 'denmark', 'estonia', 'latvia', 'lithuania', 'belarus', 'ukraine', 'moldova', 'romania', 'bulgaria', 'serbia', 'croatia', 'bosnia and herzegovina', 'slovenia', 'hungary', 'slovakia', 'czech republic', 'poland', 'austria', 'switzerland', 'liechtenstein', 'luxembourg', 'netherlands', 'belgium', 'ireland', 'portugal', 'spain', 'andorra', 'monaco', 'france', 'italy']
# Transform County data to TRPA Schema
with arcpy.da.UpdateCursor(eldoradoParcel, [
## TRPA base schema ##
'APN_TRPA', #0
'PPNO_TRPA', #1
'JURISDICTION_TRPA', #2
# parcel address
'HSE_NUMBR_TRPA', #3
'STR_DIR_TRPA', #4
'STR_NAME_TRPA', #5
'STR_SUFFIX_TRPA', #6
'UNIT_NUMBR_TRPA', #7
'APO_ADDRESS_TRPA', #8
'PSTL_TOWN_TRPA', #9
'PSTL_STATE_TRPA', #10
'PSTL_ZIP5_TRPA', #11
# owner fields
# no first and last fields
'OWN_FULL_TRPA', #12
'MAIL_ADD1_TRPA', #13
'MAIL_CITY_TRPA', #14
'MAIL_STATE_TRPA', #15
'MAIL_ZIP5_TRPA', #16
# value fields
'AS_LANDVALUE_TRPA', #17
'AS_IMPROVALUE_TRPA', #18
'AS_SUM_TRPA', #19
'TAX_LANDVALUE_TRPA', #20
'TAX_IMPROVALUE_TRPA', #21
'TAX_SUM_TRPA', #22
'TAX_YEAR_TRPA', #23
# land use fields
'COUNTY_LANDUSE_CODE_TRPA', #24
'COUNTY_LANDUSE_TRPA', #25
# Fields for building info
"YEAR_BUILT_TRPA", #26
'UNITS_TRPA', #27
'BEDROOMS_TRPA', #28
'BATHROOMS_TRPA', #29
'BUILDING_SQFT_TRPA', #30
'VHR_TRPA', #31
'HOA_TRPA', #32
###-------------------------###
# County Fields to get data from
'PRCL_ID', #33
'OWNER_NAME', #34
'MAIL_ADDR1', #35
'MAIL_ADDR2', #36
'MAIL_ADDR3', #37
'MAIL_ADDR4', #38
'ADDRSTNBR', #39
'ADDRSTDIR', #40
'ADDRSTNAME', #41
'ADDRSTTYPE', #42
'ADDRUNITNB', #43
'PRCL_ADDR', #44
'USECD_1', #45
'USECDLIT_1', #46
'STRUCT_VAL', #47
'LAND_VAL', #48
'YR_BUILT', #49
'DWELLUNITS', #50
'BEDROOMS', #51
'ADDRSTPRFX' #52
]) as cursor:
# transform each row
for row in cursor:
# Set APN
apn = row[33]
if not (apn is None or apn == "" or apn.isspace() == True or 'UN' in apn):
row[0] = (apn[:3] + "-" + apn[3:6] + "-" + apn[6:9])
else:
row[0] = ''
# Set PPNO
ppno = row[33]
if not (apn is None or apn == "" or apn.isspace() == True or 'UN' in apn or 'NP' in apn):
try:
row[1] = float(ppno)
except ValueError:
row[1] = 0
else:
row[1] = 0
# Set County
row[2] = 'EL'
# APO Address
full_address = row[44]
if not (full_address is None or full_address=='' or full_address.isspace()==True):
row[8] = full_address
else:
row[8] = ''
# House Number
house = row[39]
if not (house is None):
# convert house number to integer type
row[3] = str(int(house))
else:
row[3] = ''
# Street Direction
street_direction = row[40]
if not (street_direction is None or street_direction=='' or street_direction.isspace()==True
or street_direction == 'UNASSIGNED'):
# get the first character
row[4] = street_direction[0]
else:
row[4] = ''
# Street Name
street_name = row[41]
street_prefix = row[52]
if not (street_name is None or street_name =='' or street_name.isspace()==True):
if not (street_prefix is None or street_prefix =='' or street_prefix.isspace()==True
or street_prefix == 'UNASSIGNED'):
row[5]= street_prefix + ' ' + street_name
else:
row[5] = street_name
else:
row[5] = ''
# Street Suffix
street_suffix = row[42]
if not (street_suffix is None or street_suffix =='' or street_suffix.isspace()==True
or street_direction == 'UNASSIGNED'):
row[6] = street_suffix
else:
row[6] = ''