#Imports
import arcpy, os
#Set environments
arcpy.env.workspace = '..\\scratch'
arcpy.env.scratchWorkspace = '..\\scratch'
arcpy.env.overwriteOutput = True
#Read in the pipeline data
gdb_NG = '\\\\ns-leviathan.win.duke.edu\\biogas_GIS\\Rextag_Zone2\\Rextag_Zone2_Natural_Gas.gdb\\Natural_Gas'
fc_NaturalGasPipelines = os.path.join(gdb_NG,'NaturalGasPipelines')
if not arcpy.Exists(fc_NaturalGasPipelines):
print("Error finding pipeline dataset!")
else:
sr = arcpy.Describe(fc_NaturalGasPipelines).spatialReference
srName = sr.name
srCode = sr.GCSCode
arcpy.env.outputCoordinateSystem=sr
print("Natural gas pipeline feature class found.")
print("Spatial reference set to {} (code:{})".format(srName,srCode))
#Set path to address data csv file
farmFile = '..\\data\\raw\\DairyFarms_18July2019.csv'
#Read the data into a feature layer
farmPts = arcpy.management.XYTableToPoint(in_table=farmFile,
out_feature_class='..\\scratch\\farmPts',
x_field='Longitude',
y_field='Latitude',
coordinate_system=arcpy.SpatialReference(4269))
#Compute the distances from each farm feature to the nearest pipeline feature
nearTable = '..\\scratch\\Distances.csv'
nearTbl = arcpy.GenerateNearTable_analysis(in_features=farmPts,
near_features=fc_NaturalGasPipelines,
out_table=nearTable,
method='GEODESIC')
#Read the address file and the near table produced above and join them
dfFarms = pd.read_csv(addressFile)
dfNear = pd.read_csv(nearTable)
dfOut = pd.merge(dfFarms,dfNear,left_index=True,right_index=True)[['Name','NEAR_DIST']]
dfOut.columns = ('Name','Distance_m')
dfOut['Distance_m'] = dfOut['Distance_m'].round().astype('int')
dfOut.to_csv('..\\scratch\\Distances.csv',index=False)
dfOut
#Copy farms to new FC
farmsPts2 = arcpy.CopyFeatures_management(farmPts,"..\\scratch\\farmsPts2.shp")
#Add FID of nearest pipeline
arcpy.Near_analysis(in_features=farmsPts2,near_features=fc_NaturalGasPipelines,method='GEODESIC')
#Join the pipe attributes to the farmsPts2 table
arcpy.JoinField_management(in_data=farmsPts2,
in_field='NEAR_FID',
join_table=fc_NaturalGasPipelines,
join_field='OBJECTID',fields=['Name','Operator','Diameter'])
#Export the table to a csv file
arcpy.TableToTable