Example #1
0
def calculate(pts, line, start=0, search_radius="100 Meters"):
    """Calculate the milepost of each point in pts."""

    # pts = sequence of (id,lat,lon)
    # line = linear feature class with routes (linear referencing)
    rid = "ROUTE"
    props = "ID POINT MP"
    tbl = "in_memory/results"
    srs = arcpy.SpatialReference(4326)  # WGS84
    pt_fc = arcpy.CreateFeatureclass_management("in_memory", "pt_fc", "POINT",
                                                "", "DISABLED", "DISABLED",
                                                srs)
    arcpy.AddField_management(pt_fc, "OBS_ID", "Long")
    with arcpy.da.InsertCursor(pt_fc, ["OBS_ID", "SHAPE@XY"]) as in_cursor:
        for point in pts:
            in_cursor.insertRow([point[0], (point[2], point[1])])
    arcpy.LocateFeaturesAlongRoutes_lr(pt_fc, Config.road_fc, rid,
                                       search_radius, tbl, props)
    with arcpy.da.SearchCursor("in_memory\\results",
                               ["OBS_ID", "MP"]) as out_cursor:
        mileposts = dict(out_cursor)
    if start != 0:
        for mile_id in mileposts:
            mileposts[mile_id] = mileposts[mile_id] + start
    arcpy.Delete_management(tbl)
    arcpy.Delete_management(pt_fc)
    return mileposts
def get_contour():
    # buffer the queried route by 1 foot
    arcpy.Buffer_analysis(ROUTE_FL, BUFFER_FL, buffer_distance_or_field="1 Feet", dissolve_option="NONE")
    # arcpy.CopyFeatures_management(BUFFER_FL, os.path.join(gdb, "buffer"))  # for testing, comment out when not in use
    arcpy.AddMessage("Buffer Complete")

    # clip the contours with the buffer
    arcpy.AddMessage("Clipping Contours....")
    arcpy.Clip_analysis(contour_5ft, BUFFER_FL, CLIPPED_CONTOUR_FL)
    arcpy.CopyFeatures_management(CLIPPED_CONTOUR_FL, os.path.join(gdb, "CONTOUR"))
    arcpy.AddMessage("Contour Clip Complete")

    # intersect Queried Route with Clipped Contour to generate points for loading
    arcpy.AddMessage("Intersecting Contours with Route....")
    arcpy.Intersect_analysis([ROUTE_FL, CLIPPED_CONTOUR_FL], INTERSECT_POINTS_FL_MP, "ALL", 0, "POINT")
    arcpy.AddMessage("Intersect Complete")

    # explode multipart features
    arcpy.AddMessage("Exploding Multipart Features....")
    arcpy.MultipartToSinglepart_management(INTERSECT_POINTS_FL_MP, INTERSECT_POINTS_FL)
    arcpy.AddMessage("Explode Complete")

    # locate the intersected points along the route and give them a measure value
    arcpy.AddMessage("Locating Features Along Route.....")
    arcpy.LocateFeaturesAlongRoutes_lr(INTERSECT_POINTS_FL, route_copy, rid_field, "50 Feet",
                                       out_table, props, "FIRST")
    arcpy.AddMessage("Locate Complete")
Example #3
0
def locateEventTable(gdb,inFC,pts,dem,sDistance,eventProperties,zType,isLines = False):
    desc = arcpy.Describe(pts)

    if not desc.hasZ:
        addMsgAndPrint('      adding Z values')
        arcpy.AddSurfaceInformation_3d (pts, dem, zType, 'LINEAR')

    ## working around bug in LocateFeaturesAlongRoutes
    # add special field for duplicate detection
    dupDetectField = 'xDupDetect'
    arcpy.AddField_management(pts,dupDetectField,'LONG')
    # and calc this field = OBJECTID
    OID = arcpy.Describe(pts).OIDFieldName
    expr = '"!'+OID+'!"'
    arcpy.CalculateField_management(pts,dupDetectField,expr,"PYTHON")
    # locate linePts along route
    addMsgAndPrint('      making event table')
    eventTable = gdb+'/evTb_'+inFC
    testAndDelete(eventTable)
    arcpy.LocateFeaturesAlongRoutes_lr(pts,ZMline,idField,sDistance,eventTable,eventProperties)
    nRows = numberOfRows(eventTable)
    nPts = numberOfRows(pts)
    if nRows > nPts and not isLines:  # if LocateFeaturesAlongRoutes has made duplicates  (A BUG!)
        addMsgAndPrint('      correcting for bug in LocateFeaturesAlongRoutes')
        addMsgAndPrint('        '+str(nRows)+' rows in event table')
        addMsgAndPrint('        removing duplicate entries in event table')
        arcpy.DeleteIdentical_management(eventTable, dupDetectField)  
        addMsgAndPrint('        '+str(numberOfRows(eventTable))+' rows in event table')
    arcpy.DeleteField_management(eventTable,dupDetectField)
    return eventTable
def createEventTable(features, zmLine, rkey, buff, eventTable, rProps):
    #builds event table of points located along a line route
    try:
        arcpy.AddMessage('Locating ' + features + ' on ' + zmLine)
        arcpy.LocateFeaturesAlongRoutes_lr(features, zmLine, rkey, buff, eventTable, rProps, 'FIRST', 'NO_DISTANCE', 'NO_ZERO')
        #return eventTable
    except:
        tb = sys.exc_info()[2]
        tbinfo = traceback.format_tb(tb)[0]
        pymsg = tbinfo + '\n' + str(sys.exc_type)+ ': ' + str(sys.exc_value)
        arcpy.AddError(pymsg)
        raise SystemError
Example #5
0
def addReachDist(given_stream):
    """
    Calculates the ReachDist attribute using StreamID
    :param given_stream:
    :return:
    """
    print "Adding Reach Distance Attribute..."
    fields = [f.name for f in arcpy.ListFields(given_stream)]
    if 'ReachID' not in fields:
        arcpy.AddField_management(given_stream, "ReachID", "LONG")
    with arcpy.da.UpdateCursor(given_stream, ['FID', 'ReachID']) as cursor:
        for row in cursor:
            row[1] = row[0]
            cursor.updateRow(row)

    # get distance along route (LineID) for segment midpoints
    midpoints = arcpy.FeatureVerticesToPoints_management(given_stream, 'in_memory/midpoints', "MID")

    seg_network_dissolve = arcpy.Dissolve_management(given_stream, 'in_memory/seg_network_dissolve', 'StreamID', '',
                                                     'SINGLE_PART', 'UNSPLIT_LINES')

    arcpy.AddField_management(seg_network_dissolve, 'From_', 'DOUBLE')
    arcpy.AddField_management(seg_network_dissolve, 'To_', 'DOUBLE')
    with arcpy.da.UpdateCursor(seg_network_dissolve, ['SHAPE@Length', 'From_', 'To_']) as cursor:
        for row in cursor:
            row[1] = 0.0
            row[2] = row[0]
            cursor.updateRow(row)

    arcpy.CreateRoutes_lr(seg_network_dissolve, 'StreamID', 'in_memory/flowline_route', 'TWO_FIELDS', 'From_', 'To_')
    routeTbl = arcpy.LocateFeaturesAlongRoutes_lr(midpoints, 'in_memory/flowline_route', 'StreamID',
                                                  1.0,
                                                  os.path.join(os.path.dirname(given_stream), 'tbl_Routes.dbf'),
                                                  'RID POINT MEAS')

    distDict = {}
    # add reach id distance values to dictionary
    with arcpy.da.SearchCursor(routeTbl, ['ReachID', 'MEAS']) as cursor:
        for row in cursor:
            distDict[row[0]] = row[1]

    # populate dictionary value to output field by ReachID
    arcpy.AddField_management(given_stream, 'ReachDist', 'DOUBLE')
    with arcpy.da.UpdateCursor(given_stream, ['ReachID', 'ReachDist']) as cursor:
        for row in cursor:
            aKey = row[0]
            row[1] = distDict[aKey]
            cursor.updateRow(row)

    arcpy.Delete_management('in_memory')
Example #6
0
def editMileage():
    '''
    定义一个计算设备设施表里程的函数;
    计算之前确保管段表中起点里程和终点里程已经正确填写;
    
    基本思路:
    首先利用创建路径工具构建库中所有管线的路径
    然后将设备设施的路径通过定位要素工具计算出其里程(或起点里程和终点里程)
    最后将里程值写入每一个要素的对应里程字段中

    三通表计算完的里程需要检验(特别是对于管段编码号较大但里程值为0的或者管段编码值较小但里程值较大的情况需要重点检查),
    '''
    #利用管段起点里程和终点里程字段创建管线的路径
    arcpy.CreateRoutes_lr("T_PN_PIPESEGMENT_GEO","PLCODE","routes", "TWO_FIELDS", "MSTART","MEND")

    #获取管线地理要素集中的所有要素类
    featureClassList=arcpy.ListFeatureClasses("","","PIPEGEO")
    for FC in featureClassList:
        if FC!="T_PN_THREEORFOUR_GEO":
            try:
                #对所有不为空的点状要素进行里程计算
                if arcpy.Describe(FC).shapeType=="Point" and\
                   int(arcpy.GetCount_management(FC).getOutput(0))!=0:
                    
                    #获取输入要素的所有字段名称
                    fieldList=[]
                    fieldNameList=[]
                    fieldList=arcpy.ListFields(FC)  #获取表中字段列表
                    for FL in fieldList: #获取每一个表的所有字段名称
                        fieldNameList.append(FL.name)
                    if "MILEAGE" in fieldNameList:
                        #添加一个字段用于复制要素的OBJECTID
                        arcpy.AddField_management(FC,"OBJECTIDCOPY","TEXT")
                        # 将目标表中的OBJECTID字段计算到设备编号中
                        arcpy.CalculateField_management(FC,"OBJECTIDCOPY","!OBJECTID!","PYTHON")
                        #计算目标要素表的里程数据
                        arcpy.LocateFeaturesAlongRoutes_lr(FC,"routes","PLCODE","0.01 Kilometers","out")
                        #利用属性连接将输出含有里程数据的表与目标要素表连接
                        arcpy.JoinField_management(FC,"OBJECTIDCOPY","out","OBJECTIDCOPY","MEAS")
                        # 将属性连接后的字段计算成要素的管段编码
                        arcpy.CalculateField_management(FC,"MILEAGE","!MEAS!","PYTHON")
                        # 删除连接时多出的临时字段
                        arcpy.DeleteField_management(FC,["MEAS","OBJECTIDCOPY"])
                        # 删除中间文件
                        arcpy.Delete_management("out")     
            except Exception,e:
                print featureClassCodeDictionary[feature],"编辑里程时出错,错误信息:",e.message
                pass
            continue
Example #7
0
	def arcpy_linear_reference_to_table(self, arg_features_to_locate, arg_inmem_output_table_name, radius="200 Meters", locate_on_every_route="ALL", field_name_route="ROAD", output_field_name_route_match="ROAD", output_feature_type="POINT", output_field_name_distance_measure="TRUE_DIST"):
		"""To be called on the route feature
		:param field_name_route: is the field in this dataset that uniquly identifies the routes.
		:param locate_on_every_route: ALL or FIRST."""
		thou_shalt("Locate Features along routes", #TODO: nice print
			lambda: arcpy.LocateFeaturesAlongRoutes_lr(
				in_features=str(arg_features_to_locate),
				in_routes=str(self),
				route_id_field=field_name_route,
				radius_or_tolerance=radius,
				route_locations=locate_on_every_route,
				out_table=str(arg_inmem_output_table_name),
				out_event_properties=' '.join([output_field_name_route_match, output_feature_type, output_field_name_distance_measure])
			)
		)
arcpy.AddField_management("Npoints", "N_MEAS", "DOUBLE")

for rd in rdsList:
    arcpy.AddMessage(i)
    query = "RTE_NBR = {0}".format(rd)
    arcpy.MakeFeatureLayer_management("N_roads",
                                      "Nroadstemp",
                                      where_clause=query)
    arcpy.MakeFeatureLayer_management("N_roads_points",
                                      "Npointstemp",
                                      where_clause=query)
    arcpy.LocateFeaturesAlongRoutes_lr("Npointstemp",
                                       "Nroadstemp",
                                       "RTE_NM",
                                       "0 Feet",
                                       "locNRoads",
                                       "RID_N POINT N_MEAS",
                                       route_locations="ALL",
                                       distance_field="NO_DISTANCE",
                                       in_fields="FIELDS")
    arcpy.Append_management("locNRoads", "Npoints", "NO_TEST")
    i += 1
    arcpy.Delete_management("Nroadstemp")
    arcpy.Delete_management("Npointstemp")
time = str(datetime.datetime.now())
msg = "North features completed at {0}".format(time)
arcpy.AddMessage(msg)

######################################## Begin creating South Bound Roads data
arcpy.CreateFeatureclass_management(
    wrkspce,
Example #9
0
import arcpy
#export working railroad files to shapefiles

# Replace a layer/table view name with a path to a dataset (which can be a layer file) or create the layer/table view within the script
# The following inputs are layers or table views: "ActiveLines2013"
arcpy.CalculateField_management("ActiveLines2013", "LRSKEY",
                                """[RAILROAD] &"_" & [SUBDIVISIO]""", "VB",
                                "#")

# Replace a layer/table view name with a path to a dataset (which can be a layer file) or create the layer/table view within the script
# The following inputs are layers or table views: "ActiveLines2013"
arcpy.CreateRoutes_lr(
    "ActiveLines2013", "LRSKEY",
    "//gisdata/arcgis/GISdata/KDOT/BTP/Projects/RAIL/R1.shp", "ONE_FIELD",
    "LENGTHMILE", "#", "UPPER_RIGHT", "1", "0", "IGNORE", "INDEX")

# Replace a layer/table view name with a path to a dataset (which can be a layer file) or create the layer/table view within the script
# The following inputs are layers or table views: "ActiveStations", "R1"
arcpy.LocateFeaturesAlongRoutes_lr(
    "ActiveStations", "R1", "LRSKEY", "1 Miles",
    "//gisdata/arcgis/gisdata/kdot/btp/projects/rail/stationlraf",
    "LRSKEY POINT MEAS", "FIRST", "DISTANCE", "ZERO", "FIELDS", "M_DIRECTON")

#Make Route event layer

# Replace a layer/table view name with a path to a dataset (which can be a layer file) or create the layer/table view within the script
# The following inputs are layers or table views: "ActiveLines2013", "ActiveStationsSnap"
arcpy.SplitLineAtPoint_management(
    "ActiveLines2013", "ActiveStationsSnap",
    "//gisdata/arcgis/GISdata/KDOT/BTP/Projects/RAIL/SplitLines.shp",
    "50 Feet")
Example #10
0
    where_clause = "Perp" + "=" + str(year)
    try:
        arcpy.env.workspace = outDir
        # create lrs layer
        arcpy.MakeFeatureLayer_management(lrs, "lrs_lyr", where_clause)
        print str(year) + ' lrs layer is created'

        # select the lrs intersect mpo and create a layer
        arcpy.SelectLayerByLocation_management('lrs_lyr', "INTERSECT", mpo)
        print str(year) + ' lrs layer is selected'

        # create lrs subset layer
        arcpy.MakeFeatureLayer_management('lrs_lyr', 'lrs_subset')
        print str(year) + ' lrs subset layer created'

        # locate mpo along lrs subset
        arcpy.LocateFeaturesAlongRoutes_lr(
            mpo, 'lrs_subset', "NLF_ID", '', 'lrs_mpo_' + str(year),
            "NLF_ID LINE CTL_BEGIN_NBR CTL_END_NBR")
        print str(year) + ' lrs_mpo table created'

        arcpy.Delete_management('lrs_subset')
        arcpy.Delete_management('lrs_lyr')
        print 'lrs and subset layer deleted'

    except:
        print(arcpy.GetMessages())

raw_input()
Example #11
0
 # lijn uitlezen en begin en eindpunt selecteren.
 lineGeom = line.getValue(shapefieldname)
 endPoints = lineGeom.firstPoint, lineGeom.lastPoint
 arcpy.AddMessage("\n  Lijnstuk: "+str(line.OBJECTID))
 uitPNT = arcpy.CreateFeatureclass_management("in_memory", "BeginEindPNT", "POINT", "", "", "", inLine)
 ptRows = arcpy.InsertCursor(uitPNT)
 for pt in endPoints:
     ptRow = ptRows.newRow()
     ptRow.shape = pt
     ptRows.insertRow(ptRow)
 # Nu locatie op route zoeken
 tol = "5 Meters"            # Zoekafstand 5 meter
 tbl = "locate_points"
 props = "RID POINT MEASPnt"  # uitvoer kolommen
 # Execute LocateFeaturesAlongRoutes
 Mtabel = arcpy.LocateFeaturesAlongRoutes_lr(uitPNT, inRT, Rkol, tol, tbl, props)
 meas = arcpy.SearchCursor(Mtabel)
 VanTot = []
 for r in meas:
     naam = r.RID
     #traject = naam.split("_")[0]
     dijkpl = naam.split("_")[1]
     afst = r.MEASPnt
     VanTot.append([int(dijkpl),int(afst)])
 del Mtabel
 VanTot = sorted(VanTot)
 #nm1 = str(traj)+"_"+spoor+"_dp"
 nm1 = str(traj)+"_dp"
 # als de afstand tot de dijkpaal > 0 is dan verwerken
 if VanTot[0][1] > 0:
     nm2 = str(VanTot[0][0]).zfill(3)+"+"+str(VanTot[0][1]).zfill(3)
Example #12
0
   #Add DEM Z values to ZinterPts attribute table
   #addZ(zInterPts)
   try:
   	arcpy.AddField_management(zInterPts, 'zDEM', 'DOUBLE')
   except:
   	pass
   
   #and calc in the geometry x
   arcpy.CalculateField_management(zInterPts, 'zDEM', '!SHAPE.FIRSTPOINT.Z!', 'PYTHON_9.3')
 
   #locate intersection points along cross-section
   eventTable = outName + '_interEvents'
   rProps = 'rkey POINT RouteM'
   #createEventTable(zInterPts, zmLine, 'ORIG_FID', '10', eventTable, rProps)
   arcpy.AddMessage('Locating lines in ' + linesLayer + ' on ' + zmLine)
   arcpy.LocateFeaturesAlongRoutes_lr(zInterPts, zmLine, 'ORIG_FID', '10', eventTable, rProps, 'FIRST', 'NO_DISTANCE', 'NO_ZERO')
   arcpy.AddMessage('    ' + eventTable + 'written to ' + scratchDir)
   
   if outShape == 'lines':
   	xInterFeats = outName + '_xsecLines'
   	xsecLines(xInterFeats, zInterPts, eventTable, 'zDEM')
   else:
   	xInterFeats = outName + '_xsecPts'
   	xsecPoints(xInterFeats, zInterPts, eventTable, 'zDEM')
   
   #I think we're done with 'ORIG_FID' here, nuke it
   arcpy.DeleteField_management(xsecLayer, 'ORIG_FID')
   
   #transfer attributes from linesLayer to xInterFeats
   #first, what is the ID field of linesLayer (could be 'OBJECTID' or 'FID')
   descLines = arcpy.Describe(linesLayer)
Example #13
0
def generate_route_border_rule_table(workspace,route,route_id_field,boundary,boundary_id_field,buffer_size,route_border_rule_table,high_angle_threshold,offset):
    arcpy.AddMessage("Generating route border rule source table for {1}...".format(boundary))
    try:
        date = datetime.now()
        date_string = date.strftime("%m/%d/%Y")

        spatial_reference = arcpy.Describe(route).spatialReference
        xy_resolution = "{0} {1}".format(spatial_reference.XYResolution,spatial_reference.linearUnitName)

        ###############################################################################################################
        # get all candidate border routes
        arcpy.AddMessage("Identifying candidate border routes...")

        # generate boundary border
        boundary_border = os.path.join(workspace,"{0}_{1}_border".format(boundary,"boundary"))
        arcpy.FeatureToLine_management(boundary, boundary_border)

        # dissolve polygon boundary based on boundary id
        boundary_border_dissolved = os.path.join(workspace,"{0}_boundary_border_dissolved".format(boundary))
        arcpy.Dissolve_management(boundary_border,boundary_border_dissolved,[boundary_id_field])

        # generate buffer around boundary
        # arcpy.AddMessage("generate buffer around boundary")
        boundary_border_buffer = os.path.join(workspace,"{0}_{1}".format(boundary,"boundary_buffer"))
        arcpy.Buffer_analysis(boundary_border_dissolved, boundary_border_buffer, buffer_size, "FULL", "ROUND")

        # get candidate border route
        # arcpy.AddMessage("get candidate border route")
        candidate_border_route_multipart = "in_memory\\candidate_{0}_border_route_multipart".format(boundary)
        candidate_border_route = os.path.join(workspace,"candidate_{0}_border_route".format(boundary))
        arcpy.Clip_analysis(route, boundary_border_buffer, candidate_border_route_multipart)
        arcpy.MultipartToSinglepart_management(candidate_border_route_multipart, candidate_border_route)
        ################################################################################################################


        ################################################################################################################
        #  filter out candidate border routes that 'intersects' boundary at high angles
        arcpy.AddMessage("Filtering out candidate border routes that 'intersects' boundary at high angles...")

        route_buffer = os.path.join(workspace,"{0}_{1}".format(route,"buffer_flat"))
        if not arcpy.Exists(route_buffer):
            arcpy.Buffer_analysis(route, route_buffer, buffer_size, "FULL", "FLAT")

        # clip boundary segments within route buffer
        boundary_border_within_buffer_multipart = "in_memory\\{0}_boundary_within_{1}_buffer_multipart".format(boundary,route)
        boundary_border_within_buffer = os.path.join(workspace,"{0}_boundary_within_{1}_buffer".format(boundary,route))
        arcpy.Clip_analysis(boundary_border_dissolved, route_buffer, boundary_border_within_buffer_multipart)
        arcpy.MultipartToSinglepart_management(boundary_border_within_buffer_multipart, boundary_border_within_buffer)

        # Add 'SEGMENT_ID_ALL_CANDIDATES' field to candidate route and populate it with 'OBJECTID'
        arcpy.AddField_management(candidate_border_route,"SEGMENT_ID_ALL_CANDIDATES","LONG")
        arcpy.CalculateField_management(candidate_border_route, "SEGMENT_ID_ALL_CANDIDATES", "!OBJECTID!", "PYTHON")

        # Add 'ANGLE_ROUTE' field to candidate route and populate it with the angle to the true north(= 0 degree)
        arcpy.AddField_management(candidate_border_route,"ANGLE_ROUTE","DOUBLE")
        with arcpy.da.UpdateCursor(candidate_border_route,("SHAPE@","ANGLE_ROUTE")) as uCur:
            for row in uCur:
                shape = row[0]
                x_first = shape.firstPoint.X
                y_first = shape.firstPoint.Y
                x_last = shape.lastPoint.X
                y_last = shape.lastPoint.Y

                angle = calculate_angle(x_first,y_first,x_last,y_last)

                if angle >=0:
                    row[1]=angle
                    uCur.updateRow(row)

        # Add 'ANGLE_BOUNDARY' field to boundary segment within route buffer and populate it with the angle to the true north(= 0 degree)
        arcpy.AddField_management(boundary_border_within_buffer,"ANGLE_BOUNDARY","DOUBLE")
        with arcpy.da.UpdateCursor(boundary_border_within_buffer,("SHAPE@","ANGLE_BOUNDARY")) as uCur:
            for row in uCur:
                shape = row[0]
                x_first = shape.firstPoint.X
                y_first = shape.firstPoint.Y
                x_last = shape.lastPoint.X
                y_last = shape.lastPoint.Y

                angle = calculate_angle(x_first,y_first,x_last,y_last)

                if angle:
                    row[1]=angle
                    uCur.updateRow(row)

        del uCur

        # locate boundary segment within buffer along candidate border route.
        # assuming that if the boundary segment can't be located along its corresponding route, these two might have high angles.
        boundary_along_candidate_border_route = os.path.join(workspace,"{0}_boundary_along_candidate_{1}_border_route".format(boundary,boundary))
        arcpy.LocateFeaturesAlongRoutes_lr(boundary_border_within_buffer,candidate_border_route,"SEGMENT_ID_ALL_CANDIDATES",buffer_size,\
                                           boundary_along_candidate_border_route,"{0} {1} {2} {3}".format("RID","LINE","FMEAS","TMEAS"))

        arcpy.JoinField_management(boundary_along_candidate_border_route, "RID", candidate_border_route, "SEGMENT_ID_ALL_CANDIDATES", ["ANGLE_ROUTE"])


        positive_candidate_border_route = []
        with arcpy.da.SearchCursor(boundary_along_candidate_border_route,("RID","ANGLE_ROUTE","ANGLE_BOUNDARY")) as sCur:
            for row in sCur:
                sid = str(row[0])
                angle_route = row[1]
                angle_boundary = row[2]

                if angle_route and angle_boundary:
                    delta_angle = abs(angle_route-angle_boundary)

                    # get real intersecting angle
                    if delta_angle > 90 and delta_angle <= 270:
                        delta_angle = abs(180 - delta_angle)
                    elif delta_angle > 270:
                        delta_angle = 360 - delta_angle
                    else:
                        pass

                    # filter out negative candidate border route
                    if delta_angle <= high_angle_threshold:
                        if sid not in positive_candidate_border_route:
                            positive_candidate_border_route.append(sid)
        del sCur

        candidate_border_route_lyr = "in_memory\\candidate_border_route_lyr"
        arcpy.MakeFeatureLayer_management(candidate_border_route, candidate_border_route_lyr)
        candidate_border_route_positive = os.path.join(workspace,"candidate_{0}_border_route_positive".format(boundary))
        where_clause = "\"{0}\" IN ({1})".format("OBJECTID",",".join(positive_candidate_border_route))
        arcpy.SelectLayerByAttribute_management(candidate_border_route_lyr, "NEW_SELECTION", where_clause)
        arcpy.CopyFeatures_management(candidate_border_route_lyr,candidate_border_route_positive)

        candidate_border_route_negative = os.path.join(workspace,"candidate_{0}_border_route_negative".format(boundary))
        where_clause = "\"{0}\" NOT IN ({1})".format("OBJECTID",",".join(positive_candidate_border_route))
        arcpy.SelectLayerByAttribute_management(candidate_border_route_lyr, "NEW_SELECTION", where_clause)
        arcpy.CopyFeatures_management(candidate_border_route_lyr,candidate_border_route_negative)
        ################################################################################################################


        ################################################################################################################
        # get left, right boundary topology of positive candidate border route
        # handle candidate border route segment with different L/R boundary id by offset
        arcpy.AddMessage("Calculating L/R boundary topology of positive candidate border route...")

        # generate offset around boundary
        boundary_border_offset= os.path.join(workspace,"{0}_{1}".format(boundary,"boundary_offset"))
        arcpy.Buffer_analysis(boundary_border_dissolved, boundary_border_offset, offset, "FULL", "ROUND")

        # get intersections between positive candidate border route and boundary offset
        candidate_border_route_positive_boundary_offset_intersections = os.path.join(workspace,"candidate_{0}_border_route_positive_{1}_offset_intersections".format(boundary,boundary))
        arcpy.Intersect_analysis([candidate_border_route_positive,boundary_border_offset], candidate_border_route_positive_boundary_offset_intersections, "ALL", "", "point")

        # split positive candidate border route by intersections generated above
        candidate_border_route_positive_splitted_by_offset = os.path.join(workspace,"candidate_{0}_border_route_positive_splitted_by_offset".format(boundary))
        arcpy.SplitLineAtPoint_management(candidate_border_route_positive,candidate_border_route_positive_boundary_offset_intersections,\
                                          candidate_border_route_positive_splitted_by_offset,xy_resolution)

        # Add 'SEGMENT_ID_POSITIVE_CANDIDATES' field to splitted positive candidate route and populate it with 'OBJECTID'
        arcpy.AddField_management(candidate_border_route_positive_splitted_by_offset,"SEGMENT_ID_POSITIVE_CANDIDATES","LONG")
        arcpy.CalculateField_management(candidate_border_route_positive_splitted_by_offset, "SEGMENT_ID_POSITIVE_CANDIDATES", "!OBJECTID!", "PYTHON")

        # get positive candidate border route segments that within boundary offset
        candidate_border_route_positive_within_offset = os.path.join(workspace,"candidate_{0}_border_route_positive_within_offset".format(boundary))
        candidate_border_route_positive_splitted_by_offset_lyr = "in_memory\\candidate_{0}_border_route_positive_splitted_by_offset_lyr".format(boundary)
        arcpy.MakeFeatureLayer_management(candidate_border_route_positive_splitted_by_offset, candidate_border_route_positive_splitted_by_offset_lyr)
        arcpy.SelectLayerByLocation_management (candidate_border_route_positive_splitted_by_offset_lyr, "WITHIN", boundary_border_offset)
        arcpy.CopyFeatures_management(candidate_border_route_positive_splitted_by_offset_lyr,candidate_border_route_positive_within_offset)

        # get positive candidate border route segments that out of boundary offset
        candidate_border_route_positive_outof_offset = os.path.join(workspace,"candidate_{0}_border_route_positive_outof_offset".format(boundary))
        arcpy.SelectLayerByAttribute_management(candidate_border_route_positive_splitted_by_offset_lyr, "SWITCH_SELECTION")
        arcpy.CopyFeatures_management(candidate_border_route_positive_splitted_by_offset_lyr,candidate_border_route_positive_outof_offset)

        # generate offset around positive candidate border route within boundary offset
        # arcpy.AddMessage("generate offset around boundary")
        candidate_border_route_positive_within_offset_buffer= os.path.join(workspace,"candidate_{0}_border_route_positive_within_offset_buffer".format(boundary))
        arcpy.Buffer_analysis(candidate_border_route_positive_within_offset, candidate_border_route_positive_within_offset_buffer, offset, "FULL", "FLAT")

        # clip boundary segments within offset distance from positive candidate route that within boundary offset
        boundary_border_within_positive_candidate_border_route_buffer_multipart = "in_memory\\{0}_boundary_within_positive_candidate_border_route_buffer_multipart".format(boundary)
        boundary_border_within_positive_candidate_border_route_buffer = os.path.join(workspace,"{0}_boundary_within_positive_candidate_border_route_buffer".format(boundary))
        arcpy.Clip_analysis(boundary_border_dissolved, candidate_border_route_positive_within_offset_buffer, boundary_border_within_positive_candidate_border_route_buffer_multipart)
        arcpy.MultipartToSinglepart_management(boundary_border_within_positive_candidate_border_route_buffer_multipart, boundary_border_within_positive_candidate_border_route_buffer)

        # get endpoints of boundary border within offset buffer of splitted positive candidate border routes
        boundary_border_within_positive_candidate_border_route_buffer_endpoints = os.path.join(workspace,"{0}_boundary_within_positive_candidate_border_route_buffer_endpoints".format(boundary))
        arcpy.FeatureVerticesToPoints_management(boundary_border_within_positive_candidate_border_route_buffer,\
                                                 boundary_border_within_positive_candidate_border_route_buffer_endpoints,"BOTH_ENDS")
        arcpy.DeleteIdentical_management(boundary_border_within_positive_candidate_border_route_buffer_endpoints, ["Shape"])

        # split boundary border within offset buffer of splitted positive candidate border routes and endpoints location
        # then delete identical shape
        boundary_border_within_positive_candidate_border_route_buffer_splitted_by_own_endpoints = os.path.join(workspace,"{0}_boundary_within_positive_candidate_border_route_buffer_splitted_by_own_endpoints".format(boundary))
        arcpy.SplitLineAtPoint_management(boundary_border_within_positive_candidate_border_route_buffer,boundary_border_within_positive_candidate_border_route_buffer_endpoints,\
                                          boundary_border_within_positive_candidate_border_route_buffer_splitted_by_own_endpoints,xy_resolution)
        arcpy.DeleteIdentical_management(boundary_border_within_positive_candidate_border_route_buffer_splitted_by_own_endpoints, ["Shape"])

        # Add 'SEGMENT_ID_BOUNDARY' field to boundary segments within offset distance from positive candidate route that within boundary offset and populate it with 'OBJECTID'
        arcpy.AddField_management(boundary_border_within_positive_candidate_border_route_buffer_splitted_by_own_endpoints,"SEGMENT_ID_BOUNDARY","LONG")
        arcpy.CalculateField_management(boundary_border_within_positive_candidate_border_route_buffer_splitted_by_own_endpoints, "SEGMENT_ID_BOUNDARY", "!OBJECTID!", "PYTHON")

        # locate boundary segments within offset distance of positive candidate route that within boundary offset along positive candidate route that within boundary offset
        boundary_border_within_positive_candidate_border_route_buffer_along_candidate_border_route = os.path.join(workspace,"{0}_boundary_border_within_positive_candidate_border_route_buffer_along_candidate_border_route".format(boundary))
        arcpy.LocateFeaturesAlongRoutes_lr(boundary_border_within_positive_candidate_border_route_buffer_splitted_by_own_endpoints,candidate_border_route_positive_within_offset,"SEGMENT_ID_POSITIVE_CANDIDATES",offset,\
                                           boundary_border_within_positive_candidate_border_route_buffer_along_candidate_border_route,"{0} {1} {2} {3}".format("RID","LINE","FMEAS","TMEAS"))

        # get left, right boundary topology of boundary within offset distance of positive candidate route that within boundary offset along positive candidate route that within boundary offset
        boundary_border_within_positive_candidate_border_route_buffer_with_polygon_topology_allcases= os.path.join(workspace,"{0}_boundary_border_within_positive_candidate_border_route_buffer_with_{1}_topology_allcases".format(boundary,boundary))
        arcpy.Identity_analysis(boundary_border_within_positive_candidate_border_route_buffer_splitted_by_own_endpoints, boundary, boundary_border_within_positive_candidate_border_route_buffer_with_polygon_topology_allcases,"ALL","","KEEP_RELATIONSHIPS")

        boundary_border_within_positive_candidate_border_route_buffer_with_polygon_topology_allcases_lyr = "in_memory\\{0}_boundary_border_within_positive_candidate_border_route_buffer_with_{1}_topology_allcases_lyr".format(boundary,boundary)
        arcpy.MakeFeatureLayer_management(boundary_border_within_positive_candidate_border_route_buffer_with_polygon_topology_allcases, boundary_border_within_positive_candidate_border_route_buffer_with_polygon_topology_allcases_lyr)

        where_clause = "\"{0}\"<>0 AND \"{1}\"<>0".format("LEFT_{0}".format(boundary),"RIGHT_{0}".format(boundary))
        arcpy.SelectLayerByAttribute_management(boundary_border_within_positive_candidate_border_route_buffer_with_polygon_topology_allcases_lyr, "NEW_SELECTION", where_clause)
        boundary_border_within_positive_candidate_border_route_buffer_with_polygon_topology = os.path.join(workspace,"{0}_boundary_border_within_positive_candidate_border_route_buffer_with_{1}_topology".format(boundary,boundary))
        arcpy.CopyFeatures_management(boundary_border_within_positive_candidate_border_route_buffer_with_polygon_topology_allcases_lyr,boundary_border_within_positive_candidate_border_route_buffer_with_polygon_topology)

        arcpy.JoinField_management(boundary_border_within_positive_candidate_border_route_buffer_along_candidate_border_route,"SEGMENT_ID_BOUNDARY",\
                                   boundary_border_within_positive_candidate_border_route_buffer_with_polygon_topology,"SEGMENT_ID_BOUNDARY",["LEFT_{0}".format(boundary_id_field),"RIGHT_{0}".format(boundary_id_field)])

        arcpy.JoinField_management(candidate_border_route_positive_within_offset,"SEGMENT_ID_POSITIVE_CANDIDATES",\
                                   boundary_border_within_positive_candidate_border_route_buffer_along_candidate_border_route,"RID",["SEGMENT_ID_BOUNDARY","LEFT_{0}".format(boundary_id_field),"RIGHT_{0}".format(boundary_id_field)])

        candidate_border_route_positive_within_offset_lyr = "in_memory\\candidate_{0}_border_route_positive_within_offset_lyr".format(boundary)
        arcpy.MakeFeatureLayer_management(candidate_border_route_positive_within_offset, candidate_border_route_positive_within_offset_lyr)
        where_clause = "\"{0}\"IS NOT NULL AND \"{1}\"IS NOT NULL".format("LEFT_{0}".format(boundary_id_field),"RIGHT_{0}".format(boundary_id_field))
        arcpy.SelectLayerByAttribute_management(candidate_border_route_positive_within_offset_lyr, "NEW_SELECTION", where_clause)
        candidate_border_route_positive_within_offset_with_polygon_topology = os.path.join(workspace,"candidate_{0}_border_route_positive_within_offset_with_{1}_topology".format(boundary,boundary))
        arcpy.CopyFeatures_management(candidate_border_route_positive_within_offset_lyr,candidate_border_route_positive_within_offset_with_polygon_topology)

        # get left, right boundary topology of candidate border route out of boundary offset
        candidate_border_route_positive_outof_offset_with_polygon_topology_allcases= os.path.join(workspace,"candidate_{0}_border_route_positive_outof_offset_with_{1}_topology_allcases".format(boundary,boundary))
        arcpy.Identity_analysis(candidate_border_route_positive_outof_offset, boundary, candidate_border_route_positive_outof_offset_with_polygon_topology_allcases,"ALL","","KEEP_RELATIONSHIPS")

        candidate_border_route_positive_outof_offset_with_polygon_topology_allcases_lyr = "in_memory\\candidate_{0}_border_route_positive_outof_offset_with_polygon_topology_allcases_lyr".format(boundary)
        arcpy.MakeFeatureLayer_management(candidate_border_route_positive_outof_offset_with_polygon_topology_allcases, candidate_border_route_positive_outof_offset_with_polygon_topology_allcases_lyr)
        where_clause = "\"{0}\"<>0 AND \"{1}\"<>0".format("LEFT_{0}".format(boundary),"RIGHT_{0}".format(boundary))
        arcpy.SelectLayerByAttribute_management(candidate_border_route_positive_outof_offset_with_polygon_topology_allcases_lyr, "NEW_SELECTION", where_clause)
        candidate_border_route_positive_outof_offset_with_polygon_topology = os.path.join(workspace,"candidate_{0}_border_route_positive_outof_offset_with_{1}_topology".format(boundary,boundary))
        arcpy.CopyFeatures_management(candidate_border_route_positive_outof_offset_with_polygon_topology_allcases_lyr,candidate_border_route_positive_outof_offset_with_polygon_topology)

        # merge
        candidate_border_route_positive_with_polygon_topology = "candidate_{0}_border_route_positive_with_{1}_topology".format(boundary,boundary)
        arcpy.FeatureClassToFeatureClass_conversion(candidate_border_route_positive_outof_offset_with_polygon_topology,workspace,candidate_border_route_positive_with_polygon_topology)
        arcpy.Append_management([candidate_border_route_positive_within_offset_with_polygon_topology],candidate_border_route_positive_with_polygon_topology,"NO_TEST")

        ################################################################################################################


        ################################################################################################################
        arcpy.AddMessage("Populate route_border_rule_table...")

        # calculate from measure and to measure of candidate border route
        # arcpy.AddMessage("Calculating from measure and to measure of candidate border routes...")
        arcpy.AddGeometryAttributes_management(candidate_border_route_positive_with_polygon_topology, "LINE_START_MID_END")

        # get candidte border route segment geometry
        arcpy.AddField_management(candidate_border_route_positive_with_polygon_topology,"SEGMENT_GEOMETRY","TEXT","","",100)
        arcpy.CalculateField_management(candidate_border_route_positive_with_polygon_topology,"SEGMENT_GEOMETRY","!shape.type!","PYTHON")

        # sort candidate border route segments based on route id and from measure, orderly
        # arcpy.AddMessage("sort validated output got above based on route id and from measure, orderly")
        candidate_border_route_positive_with_polygon_topology_sorted = os.path.join(workspace,"candidate_{0}_border_route_positive_with_polygon_topology_sorted".format(boundary))
        arcpy.Sort_management(candidate_border_route_positive_with_polygon_topology,candidate_border_route_positive_with_polygon_topology_sorted,[[route_id_field,"ASCENDING"],["START_M","ASCENDING"]])

        # create route_border_rule_table
        if arcpy.Exists(route_border_rule_table):
            arcpy.Delete_management(route_border_rule_table)
            create_route_border_rule_table_schema(workspace,route_border_rule_table)
        else:
            create_route_border_rule_table_schema(workspace,route_border_rule_table)

        # populate route_border_rule_table
        iCur = arcpy.da.InsertCursor(route_border_rule_table,["ROUTE_ID","ROUTE_START_MEASURE","ROUTE_END_MEASURE","BOUNDARY_LEFT_ID",\
                                                              "BOUNDARY_RIGHT_ID","SEGMENT_GEOMETRY","EFFECTIVE_FROM_DT","EFFECTIVE_TO_DT"])
        with arcpy.da.SearchCursor(candidate_border_route_positive_with_polygon_topology_sorted,[route_id_field,"START_M","END_M","LEFT_{0}".format(boundary_id_field),\
                                                                              "RIGHT_{0}".format(boundary_id_field),"SEGMENT_GEOMETRY","START_DATE","END_DATE"]) as sCur:
            for row in sCur:
                iCur.insertRow(row)

        del sCur
        del iCur

        arcpy.CalculateField_management(route_border_rule_table, "BRP_PROCESS_DT", "'{0}'".format(date_string), "PYTHON")
        ################################################################################################################

        arcpy.AddMessage("done!")

        return route_border_rule_table
    except Exception:
        # arcpy.AddMessage(traceback.format_exc())
        sys.exit(traceback.format_exc())
        return False
Example #14
0
def AddSegFromAddresses(AddressList, SegInput, RouteID, Output):
    import requests
    APIKey = 'AIzaSyCs80htAI4UAHHuF5m9IclsbMqg1FKxoEQ'

    PntLayer = CreateOutPath(Output, 'pnts', '')
    arcpy.CreateFeatureclass_management(out_path=os.path.dirname(Output),
                                        out_name=os.path.basename(PntLayer),
                                        geometry_type='POINT',
                                        spatial_reference=NAD1983IL)
    arcpy.AddField_management(PntLayer, 'SegID', 'SHORT')
    arcpy.AddField_management(PntLayer, 'Address', 'TEXT')
    IC = arcpy.InsertCursor(PntLayer)
    i = 0
    for add in AddressList:
        r = IC.newRow()
        r.setValue('SegID', i)
        r.setValue('Address', add[0])
        IC.insertRow(r)
        r = IC.newRow()
        r.setValue('SegID', i)
        r.setValue('Address', add[1])
        IC.insertRow(r)
        i += 1
    del IC
    AddPointFromAddress(PntLayer, 'Address')

    Buffer = "200 Feet"
    SPJ = CreateOutPath(MainFile=Output, appendix='SPJ', Extension='')
    arcpy.SpatialJoin_analysis(
        target_features=SegInput,
        join_features=PntLayer,
        out_feature_class=SPJ,
        join_operation="JOIN_ONE_TO_ONE",
        join_type="KEEP_COMMON",
        match_option="INTERSECT",
        search_radius=Buffer,
    )

    UnSplt = CreateOutPath(MainFile=Output, appendix='Unsplt', Extension='')
    arcpy.UnsplitLine_management(in_features=SPJ,
                                 out_feature_class=UnSplt,
                                 dissolve_field="",
                                 statistics_fields="")

    SPJ2 = CreateOutPath(MainFile=Output, appendix='SPJ2', Extension='')
    arcpy.SpatialJoin_analysis(
        target_features=UnSplt,
        join_features=PntLayer,
        out_feature_class=SPJ2,
        join_operation="JOIN_ONE_TO_ONE",
        join_type="KEEP_COMMON",
        match_option="INTERSECT",
        search_radius=Buffer,
    )

    Final_Layer = CreateOutLayer('FinalLayer')
    arcpy.MakeFeatureLayer_management(in_features=SPJ2, out_layer=Final_Layer)
    arcpy.SelectLayerByAttribute_management(in_layer_or_view=Final_Layer,
                                            selection_type='NEW_SELECTION',
                                            where_clause="Join_Count = 2")

    EventTable = CreateOutPath(MainFile=Output,
                               appendix='EventTable',
                               Extension='')
    arcpy.LocateFeaturesAlongRoutes_lr(in_features=PntLayer,
                                       in_routes=SPJ,
                                       route_id_field=RouteID,
                                       radius_or_tolerance=Buffer,
                                       out_table=EventTable,
                                       out_event_properties=" ".join(
                                           [RouteID, "POINT", "MP"]),
                                       route_locations="FIRST",
                                       distance_field="DISTANCE",
                                       in_fields="FIELDS",
                                       m_direction_offsetting="M_DIRECTON")

    SegTable = CreateOutPath(MainFile=Output,
                             appendix='SegTable',
                             Extension='')
    arcpy.CreateTable_management(out_path=os.path.dirname(SegTable),
                                 out_name=os.path.basename(SegTable))
    arcpy.AddField_management(SegTable, RouteID, 'TEXT')
    arcpy.AddField_management(SegTable, 'BEG_STA', 'DOUBLE')
    arcpy.AddField_management(SegTable, 'END_STA', 'DOUBLE')
    arcpy.AddField_management(SegTable, 'Address1', 'TEXT')
    arcpy.AddField_management(SegTable, 'Address2', 'TEXT')
    #SegIDDict = {r.getValue('SegID'):{'INV':'','BMP':0,'EMP':0,'Add1':'','Add2':''}}
    SegIDDict = {}
    for r in arcpy.SearchCursor(EventTable):
        k = r.getValue('SegID')
        if k in SegIDDict.keys():
            mp = r.getValue('MP')
            add = r.getValue('Address')
            if SegIDDict[k]['BMP'] <= mp:
                SegIDDict[k]['EMP'] = mp
                SegIDDict[k]['Add2'] = add
            else:
                SegIDDict[k]['EMP'] = SegIDDict[k]['BMP']
                SegIDDict[k]['BMP'] = mp
                SegIDDict[k]['Add2'] = SegIDDict[k]['Add1']
                SegIDDict[k]['Add1'] = add
        else:
            SegIDDict.update({
                r.getValue('SegID'): {
                    'INV': r.getValue(RouteID),
                    'BMP': r.getValue('MP'),
                    'EMP': -1,
                    'Add1': r.getValue('Address'),
                    'Add2': ''
                }
            })
            print('End point was not found')
    IC = arcpy.InsertCursor(SegTable)
    for k in SegIDDict.keys():
        r = IC.newRow()
        r.setValue(RouteID, SegIDDict[k]['INV'])
        r.setValue('BEG_STA', SegIDDict[k]['BMP'])
        r.setValue('END_STA', SegIDDict[k]['EMP'])
        r.setValue('Address1', SegIDDict[k]['Add1'])
        r.setValue('Address2', SegIDDict[k]['Add2'])
        IC.insertRow(r)
    del IC

    Overlay_Event_Layer = CreateOutLayer('OverlayEventLayer')
    arcpy.MakeRouteEventLayer_lr(in_routes=SegInput,
                                 route_id_field=RouteID,
                                 in_table=SegTable,
                                 in_event_properties=' '.join(
                                     [RouteID, 'LINE', 'BEG_STA', 'END_STA']),
                                 out_layer=Overlay_Event_Layer,
                                 offset_field="",
                                 add_error_field="ERROR_FIELD")

    Sort = CreateOutPath(MainFile=Output, appendix='sort', Extension='')
    arcpy.Sort_management(in_dataset=Overlay_Event_Layer,
                          out_dataset=Sort,
                          sort_field=';'.join([RouteID, 'BEG_STA', 'END_STA']))
    Final_Layer = CreateOutLayer('FinalLayer')

    arcpy.MakeFeatureLayer_management(in_features=Sort, out_layer=Final_Layer)
    arcpy.SelectLayerByAttribute_management(in_layer_or_view=Final_Layer,
                                            selection_type='NEW_SELECTION',
                                            where_clause="Shape_Length > 0")
    arcpy.Delete_management(Output)
    arcpy.CopyFeatures_management(in_features=Final_Layer,
                                  out_feature_class=Output)

    arcpy.Delete_management(PntLayer)
    arcpy.Delete_management(SPJ)
    arcpy.Delete_management(SPJ2)
    arcpy.Delete_management(EventTable)
    arcpy.Delete_management(SegTable)
    arcpy.Delete_management(Overlay_Event_Layer)
    arcpy.Delete_management(Sort)
    arcpy.Delete_management(Final_Layer)
    arcpy.Delete_management(UnSplt)
Example #15
0
            arcpy.CalculateField_management(zPts, 'zDEM', -999, 'PYTHON_9.3')

        #'DEM_Z' becomes the collar elevation field
        zField = 'zDEM'

        #clear the selection
        arcpy.SelectLayerByAttribute_management(ptLayer, "CLEAR_SELECTION")

    #add ORIG_ID for deleting identical events and for joining attributes later
    addAndCalc(zPts, 'ORIG_PTID', '[OBJECTID]')

    # locate points points along the cross-section
    eventTable = outName + '_ptEvents'
    rProps = 'rkey POINT RouteM'
    arcpy.AddMessage('Locating ' + zPts + ' on ' + zmLine)
    arcpy.LocateFeaturesAlongRoutes_lr(zPts, zmLine, 'ORIG_FID', buff,
                                       eventTable, rProps, '#', 'DISTANCE')
    arcpy.AddMessage('   ' + eventTable + ' written to ' +
                     arcpy.env.scratchWorkspace)

    #remove duplicate records that result from what appears to be
    #an unresolved bug in the Locate Features Along Routes tool
    #some points will get more than one record in the event table
    #and slightly different, sub-mapunit, mValues
    try:
        arcpy.DeleteIdentical_management(eventTable, 'ORIG_PTID')
    except:
        pass

    #place points as events on the cross section line
    eventLyr = '_lyr'
    rProps = 'rkey POINT RouteM'
Example #16
0
 
 # Loop through all the years for any given site
 for year in years:
     toshore = path + location + '_shoreline_' + str(year)
 
     if arcpy.Exists(toshore):
         print str(location) + ' - ' + str(year)
         
         # Create search cursor to insert new data into the table
         ins_cur = arcpy.InsertCursor(out_table)
         
         # Convert shoreline verticies to points to calculate minimum and mean distances
         arcpy.Intersect_analysis([toshore, transects], tempvert, "ONLY_FID", output_type="POINT")
         
         # Calculate the distance of the shoreling along each transect
         arcpy.LocateFeaturesAlongRoutes_lr(tempvert, temproute, "TRANSECT_ID", "100 Meters", temptable, "RID POINT MEAS", "FIRST", "DISTANCE", "ZERO", "FIELDS", "M_DIRECTON")
         
         # Initiate Search Cursor to cycle through the linear referencing output table
         search_cur = arcpy.SearchCursor(temptable)
         
         for s in search_cur:
             tran_id = s.RID
             dist = s.MEAS
                 
             r = ins_cur.newRow()
             r.TRANSECT_ID = str(tran_id)
             r.YEAR = str(year)
             r.DISTANCE = dist
             ins_cur.insertRow(r)
                 
             f.write(str(location) + '|' + str(year) + '|' + str(tran_id) + '|' + str(dist) + '\n')
arcpy.AddMessage("    Smoothing by Bezier interpolation - 3/9")
Bezier = arcpy.SmoothLine_cartography(Dissolve, "%ScratchWorkspace%\\Bezier", "BEZIER_INTERPOLATION")
arcpy.AddField_management(Bezier, "Start", "DOUBLE", "", "", "", "", "NULLABLE", "NON_REQUIRED", "")
arcpy.AddField_management(Bezier, "End", "DOUBLE", "", "", "", "", "NULLABLE", "NON_REQUIRED", "")
arcpy.CalculateField_management(Bezier, "Start", "0", "PYTHON_9.3", "")
arcpy.CalculateField_management(Bezier, "End", "!Shape_Length!", "PYTHON_9.3", "")

arcpy.AddMessage("    Converting in routes - 4/9")
BezierRoutes = arcpy.CreateRoutes_lr(Bezier, "Rank_UGO", "%ScratchWorkspace%\\BezierRoutes", "TWO_FIELDS", "Start", "End")

arcpy.AddMessage("    Up to date the \"Shape_Length\" field - 5/9")
UPD_SL.UpToDateShapeLengthField(BezierRoutes)

arcpy.AddMessage("    Locate inflection points on Bezier routes - 6/9")
InflectionPtTABLE = arcpy.LocateFeaturesAlongRoutes_lr(PtsForSplitting, BezierRoutes, "Rank_UGO", "1", "%ScratchWorkspace%\\InflectionPtTABLE", "RID POINT MEAS")


#/correction of the table : some errors have occured at confluences
rows1 = arcpy.UpdateCursor(InflectionPtTABLE)
rows2 = arcpy.UpdateCursor(InflectionPtTABLE)
rows3 = arcpy.SearchCursor(BezierRoutes)
line2 = next(rows2)
nrows = int(str(arcpy.GetCount_management(InflectionPtTABLE)))
    # Each inflection point has a MEAS field (distance from upstream)
n = 0
for line1 in rows1 : 
    if n >= nrows-1:
        # At the end of the table set the MEAS as the UGO (line3) length and stop the process
        line3 = next(rows3)
        line2.MEAS = line3.Shape_Length
arcpy.AddField_management(B_SourceData_CopyForLocate, "From_Date", "DATE", "", "", "", "", "NULLABLE", "NON_REQUIRED", "")

# Process: Calculate Unique Event_ID
arcpy.CalculateField_management(B_SourceData_CopyForLocate, "Event_ID", "CalcGUID()", "PYTHON", "def CalcGUID():\\n   import uuid\\n   return '{' + str(uuid.uuid4()).upper() + '}'\\n")

# Process: Calculate From_Date
arcpy.CalculateField_management(B_SourceData_CopyForLocate, "From_Date", "Date (  )", "VB", "")

# Process: Add Attribute Index (Event_ID)
arcpy.AddIndex_management(B_SourceData_CopyForLocate, "Event_ID", "index_EventID", "UNIQUE", "NON_ASCENDING")

# Process: Make Feature Layer
arcpy.MakeFeatureLayer_management(B_SourceData_CopyForLocate, B_SourceData_CopyForLocate_Layer, "", Workspace, "")

# Process: Locate Pts Along Routes (50ft buffer)
arcpy.LocateFeaturesAlongRoutes_lr(B_SourceData_CopyForLocate_Layer, LRS_Route_Network, "ROADWAY", "50 Feet", C_PointData_LocateFeatures, Output_Event_Table_Properties, "FIRST", "DISTANCE", "ZERO", "FIELDS", "M_DIRECTON")

# Process: Table to Table
arcpy.TableToTable_conversion(B_SourceData_CopyForLocate_Layer, Workspace, "E_CopyOfOriginalInputWithNewFields", "", "", "")

#if there's already a Measure field, create a new field named Source_Measure, copy those values in, and delete existing Measure field after copying out the values, and then process can pick up at next line.
###
# Process: Add Field (Source_Measure)
arcpy.AddField_management(B_SourceData_CopyForLocate, "Source_Measure", "DOUBLE", "", "", "", "", "NULLABLE", "NON_REQUIRED", "")

# Process: Calculate Source_Measure
arcpy.CalculateField_management(B_SourceData_CopyForLocate, "Source_Measure", "!Measure!", "PYTHON_9.3")

# Process: Delete Field (Measure)
arcpy.DeleteField_management(B_SourceData_CopyForLocate, "Measure")
###
arcpy.AddField_management(CopyinFC, "Start", "DOUBLE", "", "", "", "",
                          "NULLABLE", "NON_REQUIRED", "")
arcpy.AddField_management(CopyinFC, "End", "DOUBLE", "", "", "", "",
                          "NULLABLE", "NON_REQUIRED", "")
arcpy.CalculateField_management(CopyinFC, "Start", "0", "PYTHON_9.3", "")
arcpy.CalculateField_management(CopyinFC, "End", "!Shape_Length!",
                                "PYTHON_9.3", "")

Routes = arcpy.CreateRoutes_lr(CopyinFC, "Rank_UGO",
                               "%ScratchWorkspace%\\Routes", "TWO_FIELDS",
                               "Start", "End")
UPD_SL.UpToDateShapeLengthField(Routes)

LocateTABLE = arcpy.LocateFeaturesAlongRoutes_lr(
    InflectionPts, Routes, "Rank_UGO", "1", "%ScratchWorkspace%\\LocateTABLE",
    "RID POINT MEAS")
arcpy.LocateFeaturesAlongRoutes_lr(InflectionPts, Routes, "Rank_UGO", "1",
                                   "%ScratchWorkspace%\\LocateTABLE1",
                                   "RID POINT MEAS")

rows1 = arcpy.UpdateCursor(LocateTABLE)
rows2 = arcpy.UpdateCursor(LocateTABLE)
rows3 = arcpy.SearchCursor(Routes)
line2 = next(rows2)
nrows = int(str(arcpy.GetCount_management(LocateTABLE)))
n = 0
for line1 in rows1:
    if n >= nrows - 1:
        line3 = next(rows3)
        line2.MEAS = line3.Shape_Length
def convert_lec_nodes_to_line_events(
    workspace_gdb,
    lec_nodes_fc,
    lec_fault_id_field,
    routes_fc,
    routes_id_field,
    snapping_tolerance_meters,
    clean_up_temp_files=False,
):

    # Naming file variables
    temp_lines_fc = os.path.join(workspace_gdb, "temp_ConvertedLines")
    temp_events_table = os.path.join(workspace_gdb, "temp_LocatedAlongRoute")
    temp_events_lyr_name = "LEC_events_lyr"
    output_fc = os.path.join(workspace_gdb, "LEC_LinearEvents")

    # Snapping tolerance variable since GP tool accepts string with distance format
    snapping_tolerance = "{0} Meters".format(str(snapping_tolerance_meters))

    # GP Tool: LEC points to line, using a fault ID field to allow multiple edits to be processed
    arcpy.PointsToLine_management(Input_Features=lec_nodes_fc,
                                  Output_Feature_Class=temp_lines_fc,
                                  Line_Field=lec_fault_id_field,
                                  Sort_Field="OBJECTID",
                                  Close_Line="NO_CLOSE")

    # GP Tool: Locate features along route using lines and routes and write to a table.
    arcpy.LocateFeaturesAlongRoutes_lr(
        in_features=temp_lines_fc,
        in_routes=routes_fc,
        route_id_field=routes_id_field,
        radius_or_tolerance=snapping_tolerance,
        out_table=temp_events_table,
        out_event_properties="RID LINE FMEAS TMEAS",
        route_locations="FIRST",
        distance_field="DISTANCE",
        zero_length_events="ZERO",
        in_fields="FIELDS",
        m_direction_offsetting="M_DIRECTON")

    # GP Tool: Table conversion of edited events to a feature layer.
    event_layer = arcpy.MakeRouteEventLayer_lr(
        in_routes=routes_fc,
        route_id_field=routes_id_field,
        in_table=temp_events_table,
        in_event_properties="rid LINE fmeas tmeas",
        out_layer=temp_events_lyr_name,
        offset_field="",
        add_error_field="NO_ERROR_FIELD",
        add_angle_field="NO_ANGLE_FIELD",
        angle_type="NORMAL",
        complement_angle="ANGLE",
        offset_direction="LEFT",
        point_event_type="POINT").getOutput(0)

    # GP Tool: Copy feature layer to disk as feature class.
    arcpy.CopyFeatures_management(in_features=event_layer,
                                  out_feature_class=output_fc)

    # Optional clean-up of temp data.
    if clean_up_temp_files:
        arcpy.AddMessage("Cleaning up temporary content...")
        # print("Cleaning up temporary content...")

        content_to_delete = [temp_lines_fc, temp_events_table]

        for item in content_to_delete:
            arcpy.Delete_management(item)

        arcpy.AddMessage("Temp files cleaned up.")
Example #21
0
    "(FromDate is null or FromDate<=CURRENT_TIMESTAMP) and (ToDate is null or ToDate>CURRENT_TIMESTAMP)"
)
arcpy.CopyFeatures_management('useMe', reviewer_db + '/useMe')
in_features = reviewer_db + "/REVDATASET/REVTABLELINE"
in_routes = reviewer_db + '/useMe'
route_id_field = "ROUTEID"
radius_or_tolerance = "1 Feet"
point_radius = "20 Feet"
out_table_line = reviewer_db + "/LineRT"
props_line = "RID LINE FMEAS TMEAS"
# arcpy.env.overwriteOutput = "true"
# Write log of Locate Events tool
now = datetime.datetime.now()
writeMsg("\nStarting Line Table at: " + str(now)[:-7])
arcpy.LocateFeaturesAlongRoutes_lr(in_features, in_routes, route_id_field,
                                   radius_or_tolerance, out_table_line,
                                   props_line, "#", "#", "ZERO", "FIELDS")
now = datetime.datetime.now()
writeMsg("\nFinished Line Table at: " + str(now)[:-7])

# Set variables for joining tables.
# (This is what allows review records to be paired with the routes the tool just located.)
in_join_features = in_features
layerName = "Line_Checks"
in_field = "LINKGUID"
in_field2 = "LineRT.LINKGUID"
join_table = out_table_line
join_table2 = reviewer_db + "/REVTABLEMAIN"
join_field = "LINKGUID"
join_field2 = "ID"
join_type = "KEEP_COMMON"
    #the scratch gdb which has a length in the units of the SR of the dem.
    #interpolate the line to add z values
    zLine = lineLayer + '_z'
    arcpy.AddMessage('Getting elevation values for the cross-section in ' + lineLayer)
    arcpy.InterpolateShape_3d(dem, lineLayer, zLine)

    #measure it and turn it into a route
    zmLine = lineLayer + '_zm'
    arcpy.AddMessage('Measuring the length of the line in ' + zLine)
    arcpy.CreateRoutes_lr(zLine, 'ORIG_FID', zmLine, 'LENGTH', '#', '#', cp)

    #intersect with geology layer
    eventTable = polyLayer + '_polyEvents'
    rProps = 'rkey LINE FromM ToM'
    arcpy.AddMessage('Locating ' + polyLayer + ' on ' + zmLine)
    arcpy.LocateFeaturesAlongRoutes_lr(polyLayer, zmLine, 'ORIG_FID', '#', eventTable, rProps, 'FIRST', 'NO_DISTANCE', 'NO_ZERO')

    #place line events on interpolated route
    locatedEvents = polyLayer + '_located'
    placeEvents(zmLine, 'ORIG_FID', eventTable, 'rkey', 'FromM', 'ToM', locatedEvents)

    #flip the surface profile events
    #create an empty container for the features that has no spatial reference
    zmProfiles = outName + '_profiles'
    arcpy.AddMessage(scratchDir)
    arcpy.AddMessage(zmProfiles)
    arcpy.CreateFeatureclass_management(scratchDir, zmProfiles, 'POLYLINE', locatedEvents, 'ENABLED', 'ENABLED')

    #append the features from locatedEvents (map view) to locatedEvents2 (unknown SR)
    arcpy.Append_management(locatedEvents, zmProfiles)
Example #23
0
        if not saveIntermediate:
            for f in (tempPoints, eventTable, eventLyr, outFCa):
                testAndDelete(f)

addMsgAndPrint('\n  Projecting polygon feature classes:')
for polyFC in polyFCs:
    inFC = shortName(polyFC)
    addMsgAndPrint('    ' + inFC)
    arcpy.env.workspace = wsName(polyFC)
    # locate features along routes
    addMsgAndPrint('      making event table')
    eventTable = gdb + '/evTb_' + inFC
    addMsgAndPrint(eventTable)
    testAndDelete(eventTable)
    eventProperties = 'rtID LINE FromM ToM'
    arcpy.LocateFeaturesAlongRoutes_lr(inFC, ZMline, idField, '#', eventTable,
                                       eventProperties)
    addMsgAndPrint('      placing events on section line')
    eventLyr = 'xxxPolyEvents'
    arcpy.MakeRouteEventLayer_lr(ZMline, idField, eventTable, eventProperties,
                                 eventLyr)
    outFC = 'ed_CS' + outFdsTag + shortName(inFC)
    addMsgAndPrint('      creating feature class ' + outFC + ' in ' +
                   shortName(outFds))
    # make new feature class using old as template
    testAndDelete(outFds + '/' + outFC)
    addMsgAndPrint(outFds + ' ' + outFC + ' ' + inFC)
    try:
        arcpy.CreateFeatureclass_management(outFds, outFC, 'POLYLINE', inFC,
                                            'DISABLED', 'SAME_AS_TEMPLATE')
    except:
        addMsgAndPrint('Failed to create copy of ' + inFC +
Example #24
0
def ImportRoadwayData(Input, Route, AttTable, Fields, Output, RouteID, BMP,
                      EMP, XY_Tolerance):
    #Output should be on a GDB not a shapefile

    #Step 1: Create a route FC based on the input
    Sites_Event_Table = common.CreateOutPath(MainFile=Output,
                                             appendix='EventTab',
                                             Extension='')
    arcpy.LocateFeaturesAlongRoutes_lr(in_features=Input,
                                       in_routes=Route,
                                       route_id_field=RouteID,
                                       radius_or_tolerance=XY_Tolerance,
                                       out_table=Sites_Event_Table,
                                       out_event_properties=' '.join(
                                           [RouteID, 'LINE', BMP, EMP]),
                                       route_locations="FIRST",
                                       distance_field="DISTANCE",
                                       zero_length_events="ZERO",
                                       in_fields="FIELDS",
                                       m_direction_offsetting="M_DIRECTON")
    Sites_Event_Layer = common.CreateOutLayer('EventLayer')
    arcpy.MakeRouteEventLayer_lr(in_routes=Route,
                                 route_id_field=RouteID,
                                 in_table=Sites_Event_Table,
                                 in_event_properties=' '.join(
                                     [RouteID, 'LINE', BMP, EMP]),
                                 out_layer=Sites_Event_Layer,
                                 add_error_field="NO_ERROR_FIELD")

    Sites_Routes = common.CreateOutPath(MainFile=Output,
                                        appendix='route',
                                        Extension='')
    arcpy.CopyFeatures_management(in_features=Sites_Event_Layer,
                                  out_feature_class=Sites_Routes)

    IRIS_Diss = common.CreateOutPath(MainFile=Output,
                                     appendix='diss',
                                     Extension='')
    arcpy.DissolveRouteEvents_lr(
        in_events=AttTable,
        in_event_properties=' '.join([RouteID, 'LINE', BMP, EMP]),
        dissolve_field=';'.join(Fields),
        out_table=IRIS_Diss,
        out_event_properties=' '.join([RouteID, 'LINE', BMP, EMP]),
        dissolve_type="DISSOLVE",
        build_index="INDEX")

    Overlay_Event_Table1 = common.CreateOutPath(MainFile=Output,
                                                appendix='OverlayTab1',
                                                Extension='')
    arcpy.OverlayRouteEvents_lr(
        in_table=IRIS_Diss,
        in_event_properties=' '.join([RouteID, 'LINE', BMP, EMP]),
        overlay_table=Sites_Event_Table,
        overlay_event_properties=' '.join([RouteID, 'LINE', BMP, EMP]),
        overlay_type="INTERSECT",
        out_table=Overlay_Event_Table1,
        out_event_properties=' '.join([RouteID, 'LINE', BMP, EMP]),
        zero_length_events="NO_ZERO",
        in_fields="FIELDS",
        build_index="INDEX")

    Overlay_Event_Layer = common.CreateOutLayer('OverlayEventLayer')
    arcpy.MakeRouteEventLayer_lr(in_routes=Route,
                                 route_id_field=RouteID,
                                 in_table=Overlay_Event_Table1,
                                 in_event_properties=' '.join(
                                     [RouteID, 'LINE', BMP, EMP]),
                                 out_layer=Overlay_Event_Layer,
                                 offset_field="",
                                 add_error_field="ERROR_FIELD")

    Sites_segs1 = common.CreateOutPath(MainFile=Output,
                                       appendix='seg1',
                                       Extension='')
    arcpy.CopyFeatures_management(in_features=Overlay_Event_Layer,
                                  out_feature_class=Sites_segs1)

    #Curves_Table = common.CreateOutPath(MainFile=Output,appendix='curves',Extension='')
    #ExtractCurves(inp=Sites_segs1,IDField=RouteID,RMax=5280,RMin=10,DegMin=2,desd=1000,LenMin=1000,out=Curves_Table)

    #Overlay_Event_Table2 = common.CreateOutPath(MainFile=Output,appendix='OverlayTab2',Extension='')
    #arcpy.OverlayRouteEvents_lr(in_table = Overlay_Event_Table1,
    #                            in_event_properties = ' '.join([RouteID,'LINE',BMP,EMP]),
    #                            overlay_table = Curves_Table,
    #                            overlay_event_properties = ' '.join([RouteID,'LINE',BMP,EMP]),
    #                            overlay_type = "UNION",
    #                            out_table = Overlay_Event_Table2,
    #                            out_event_properties = ' '.join([RouteID,'LINE',BMP,EMP]),
    #                            zero_length_events = "NO_ZERO",
    #                            in_fields = "FIELDS",
    #                            build_index="INDEX")

    #Overlay_Event_Layer2 = common.CreateOutLayer('OverlayEventLayer2')
    #arcpy.MakeRouteEventLayer_lr(in_routes = Route,
    #                             route_id_field = RouteID,
    #                             in_table = Overlay_Event_Table2,
    #                             in_event_properties = ' '.join([RouteID,'LINE',BMP,EMP]),
    #                             out_layer = Overlay_Event_Layer2,
    #                             offset_field = "",
    #                             add_error_field = "ERROR_FIELD")

    Sort = common.CreateOutPath(MainFile=Output, appendix='sort', Extension='')
    arcpy.Sort_management(in_dataset=Sites_segs1,
                          out_dataset=Sort,
                          sort_field=';'.join([RouteID, BMP, EMP]))
    Final_Layer = common.CreateOutLayer('FinalLayer')

    arcpy.MakeFeatureLayer_management(in_features=Sort, out_layer=Final_Layer)
    arcpy.SelectLayerByAttribute_management(in_layer_or_view=Final_Layer,
                                            selection_type='NEW_SELECTION',
                                            where_clause="Shape_Length > 52")

    arcpy.Delete_management(Output)
    arcpy.MultipartToSinglepart_management(in_features=Final_Layer,
                                           out_feature_class=Output)
    arcpy.DeleteField_management(Output, 'ORIG_FID')
    FL = [
        f.name for f in arcpy.ListFields(Output)
        if f.name != arcpy.Describe(Output).OIDFieldName
    ]
    arcpy.DeleteIdentical_management(in_dataset=Output,
                                     fields=';'.join(FL),
                                     xy_tolerance="",
                                     z_tolerance="0")

    arcpy.Delete_management(Sites_Event_Table)
    arcpy.Delete_management(Sites_Event_Layer)
    arcpy.Delete_management(Sites_Routes)
    arcpy.Delete_management(IRIS_Diss)
    arcpy.Delete_management(Overlay_Event_Table1)
    arcpy.Delete_management(Overlay_Event_Layer)
    arcpy.Delete_management(Sites_segs1)
    #arcpy.Delete_management(Curves_Table)
    #arcpy.Delete_management(Overlay_Event_Table2)
    #arcpy.Delete_management(Overlay_Event_Layer2)
    arcpy.Delete_management(Sort)
    arcpy.Delete_management(Final_Layer)
Example #25
0
'''
Created on Apr 18, 2013

@author: kyleg
'''
import arcpy
arcpy.env.overwriteOutput = True
ws = r"\\gisdata\arcgis\GISdata\KDOT\BTST\DeerAccs3.gdb"
arcpy.env.workspace = ws
#start with Accident Data points
crashlyr = "DeerCrashes"
sumlyr = "Deer_Crash_Summary"
#locate the points along the County Route LRS
arcpy.LocateFeaturesAlongRoutes_lr(crashlyr, "LRS_Route_CRM", "LRS_KEY",
                                   "0 Feet", "LFAR_CRASHES",
                                   "LRS_KEY POINT CRMP", "FIRST", "DISTANCE",
                                   "ZERO", "FIELDS", "M_DIRECTON")
#Calculate the begin and end miles post integer around the CR_MP
arcpy.AddField_management("LFAR_CRASHES", "BeginCMP", "LONG")
arcpy.AddField_management("LFAR_CRASHES", "EndCMP", "LONG")
#take the crash location and calculate the integer part of the Logmile
arcpy.CalculateField_management("LFAR_CRASHES", "BeginCMP", "long( !CRMP! )",
                                "PYTHON_9.3", "#")
#and add one to it - now we have the crashes overlapping every mile covering the extent of the LRS Geometry
arcpy.CalculateField_management("LFAR_CRASHES", "EndCMP", "long( !CRMP! )+1",
                                "PYTHON_9.3", "#")
#locate the events now as lines
#dissolve the lines as follows
arcpy.MakeRouteEventLayer_lr("LRS_Route_CRM", "LRS_KEY", "LFAR_CRASHES",
                             "LRS_KEY LINE BeginCMP EndCMP",
                             "LFAR_CRASHES lines", "#", "ERROR_FIELD",
Example #26
0
    #check plotWRT boolean
    if plotWRT == 'true':

        #create points that represent the intersections between the profile lines
        #and the single intersection line
        intersectFC = outName + '_intersectPts'
        arcpy.Intersect_analysis([linesLayer, wrtLineFC], intersectFC, '#', '#', 'POINT')

        #now, locate those points on the profile routes
        #a field called 'mValue' will be created that shows the distance
        #from the beginning of the profile line to the point of intersection
        #the offset required to plot the profile wrt to the intersecting line
        intersectTab = outName + '_intersectTab'
        rProps = 'rkey POINT mValue'
        arcpy.AddMessage('Locating ' + linesLayer + ' on ' + zmLines)
        arcpy.LocateFeaturesAlongRoutes_lr(intersectFC, zmLines, 'ORIG_FID', 1, intersectTab, rProps, 'FIRST', 'NO_DISTANCE', 'NO_ZERO')

        #now update the profiles
        profiles = arcpy.UpdateCursor(zmProfiles)

        maxY = 0
        minY = 0
        for profile in profiles:
            #get the offset for this profile
            #first, get the route key of this profile
            rte = profile.ORIG_FID
            if not rte == None:
                #and create a search cursor of hopefully just one row where the rkeys
                #in the profiles fc and the intersect table are the same
                where = '"rkey" = ' + str(rte)
                #rows = arcpy.SearchCursor(intersectTab, where)
Example #27
0
    def recalculate_mileposts(self):
        arcpy.AddMessage("recalculating mileposts")

        routes = self._get_unique_routes()

        #: Identity_analysis creates multipart features. Bust them up.
        arcpy.MultipartToSinglepart_management(
            self._output._intermediate_identity_city_and_county,
            self._output._intermediate_singlepart_data)

        #: Intermediate step to recalculate milepost values. Need to from values of road as points
        arcpy.FeatureVerticesToPoints_management(
            self._output._intermediate_singlepart_data,
            self._output._intermediate_feature_to_vertices, "BOTH_ENDS")
        routesCompleted = 0
        totalRoutes = len(routes)
        for route in routes:
            #Limit Locatefeature with a def query
            #: Creates table with new milepost values
            if routesCompleted % 10 == 0:
                arcpy.AddMessage("route recalculations remaining: {}".format(
                    totalRoutes - routesCompleted))
            route_with_direction = route
            route = route[:4]

            arcpy.MakeFeatureLayer_management(
                self._input.lrs_routes, "definitionQueryRoute{}".format(route),
                """{} = '{}'""".format(
                    arcpy.AddFieldDelimiters(self._input.lrs_routes,
                                             'RT_NAME'), route))

            self.delete_if_exists(
                [self._output._intermediate_mileposts_along_route])

            arcpy.LocateFeaturesAlongRoutes_lr(
                in_features=self._output._intermediate_feature_to_vertices,
                in_routes="definitionQueryRoute{}".format(route),
                route_id_field="RT_NAME",
                radius_or_tolerance="50 Meter",
                out_table=self._output._intermediate_mileposts_along_route,
                out_event_properties="RID POINT MEAS",
                route_locations="FIRST",
                distance_field=False,
                zero_length_events="ZERO",
                in_fields="FIELDS",
                m_direction_offsetting=True)

            new_mileposts = self._get_new_milepost_values(route_with_direction)

            where_clause = """{} = '{}'""".format(
                arcpy.AddFieldDelimiters(
                    self._output._intermediate_singlepart_data,
                    self._fields.route_name), route_with_direction)
            with UpdateCursor(
                    self._output._intermediate_singlepart_data,
                ("OID@", self._fields.from_milepost, self._fields.to_milepost),
                    where_clause) as cursor:
                for row in cursor:
                    original_feature_id = row[0]

                    if original_feature_id not in new_mileposts:
                        print "objectid: {} was not found along LRS Routes. Data mismatch?".format(
                            original_feature_id)
                        continue

                    mileposts = sorted(new_mileposts[original_feature_id])

                    if len(mileposts) is not 2:
                        raise Exception(
                            "Road segment with id {} does not fall within a 50 meter diameter of LRS data. Fix data or update radius_or_tolerance value."
                            .format(row[0]))

                    if mileposts[0] > mileposts[1]:
                        print "objectid: {} has to milepost smaller than from milepost. Data issue?".format(
                            original_feature_id)

                    row[1] = mileposts[0]
                    row[2] = mileposts[1]

                    cursor.updateRow(row)
            routesCompleted += 1
        return routes
Example #28
0
def create_cond_events(workspace, condition, condlec_nodes_fc, condition_field,
                       routes_fc, routes_id_field, point_search_meters,
                       clean_up_temp_files):
    """
    
    :param workspace: 
    :param condition: 
    :param condlec_nodes_fc: 
    :param condition_field: 
    :param routes_fc: 
    :param routes_id_field: 
    :param point_search_meters: 
    :param clean_up_temp_files: 
    :return: 
    """

    # STEP 0: Set-up

    # Take the user parameter for search radius and append linear unit measurement for string
    search_distance = "{0} Meters".format(str(point_search_meters))

    # Create workspace file geodatabase
    timestamp = '{:%Y%m%d_%H%M}'.format(datetime.datetime.now())
    workspace_gdb_name = "ConditionPostProcessing_{0}".format(timestamp)

    arcpy.AddMessage("Creating workspace file geodatabase '{0}'...".format(
        workspace_gdb_name))
    workspace_gdb = arcpy.CreateFileGDB_management(
        workspace, workspace_gdb_name).getOutput(0)

    os.chdir(workspace)
    if os.path.isfile(os.path.join(workspace, "work_routes_lyr")):
        arcpy.AddMessage("Removing previously-existing layers...")
        os.remove(os.path.join(workspace, "work_routes_lyr"))

    work_event_table = os.path.join(workspace_gdb, "work_cond_events_table")

    out_condition_event_fc = os.path.join(workspace_gdb,
                                          "out_{0}_events".format(condition))

    # STEP 1: Create copy of our routes and condition points so we can operate on them for the splitting by point step.
    arcpy.AddMessage("Copying data to workspace...")
    work_nodes_fc = arcpy.FeatureClassToFeatureClass_conversion(
        condlec_nodes_fc, workspace_gdb, "work_condition_nodes").getOutput(0)

    work_routes_fc = arcpy.FeatureClassToFeatureClass_conversion(
        routes_fc, workspace_gdb, "work_routes").getOutput(0)

    work_routes_lyr = arcpy.MakeFeatureLayer_management(
        routes_fc, "work_routes_lyr").getOutput(0)

    # STEP 2: Perform Select-by-Location using the input points on the routes copy - the idea is to select only the
    # lines that were evaluated. Export this selection to disk as "Evaluated_Routes".
    arcpy.AddMessage("Finding evaluated roads...")
    arcpy.SelectLayerByLocation_management(work_routes_lyr, "INTERSECT",
                                           work_nodes_fc, search_distance)
    work_routes_evaluated = arcpy.CopyFeatures_management(
        work_routes_lyr, os.path.join(workspace_gdb,
                                      "work_evaluated_routes")).getOutput(0)

    # STEP 3: Use Split Line by Point to fracture the Routes into lines that are determined by the points entered.
    # Make sure to enter a search area.
    arcpy.AddMessage("Creating condition segments...")
    #TODO - Use the near tool to find the nearest point on the line instead of a search radius for "SplitLineAtPoint"
    work_route_evaluated_segments = arcpy.SplitLineAtPoint_management(
        in_features=work_routes_evaluated,
        point_features=work_nodes_fc,
        out_feature_class=os.path.join(workspace_gdb,
                                       "work_evaluated_route_segments"),
        search_radius=search_distance).getOutput(0)

    # STEP 4: Transfer the condition from the points to the line segments by using spatial join
    arcpy.AddMessage(
        "Transferring condition attributes to condition route segments...")
    arcpy.SpatialJoin_analysis(target_features=work_route_evaluated_segments,
                               join_features=work_nodes_fc,
                               out_feature_class=os.path.join(
                                   workspace_gdb,
                                   "work_evaluated_route_segment_conditions"),
                               join_operation="JOIN_ONE_TO_ONE",
                               join_type="KEEP_ALL",
                               match_option="INTERSECT",
                               search_radius=search_distance,
                               distance_field_name="closest_node_distance")

    work_evaluated_route_segment_conditions = os.path.join(
        workspace_gdb, "work_evaluated_route_segment_conditions")

    # STEP 5: Correct for the first line segment by selecting it and changing the condition rating to "Excellent"
    arcpy.AddMessage("Adding default start segment condition...")
    with arcpy.da.UpdateCursor(work_evaluated_route_segment_conditions,
                               condition_field) as cursor:
        for row in cursor:
            row[0] = "Excellent"
            cursor.updateRow(row)
            break

    # STEP 6: Create event table using condition segments
    arcpy.LocateFeaturesAlongRoutes_lr(
        in_features=work_evaluated_route_segment_conditions,
        in_routes=work_routes_evaluated,
        route_id_field=routes_id_field,
        out_table=work_event_table,
        radius_or_tolerance=search_distance,
        out_event_properties="RID LINE FMEAS TMEAS",
        route_locations="FIRST",
        distance_field="DISTANCE",
        zero_length_events="ZERO",
        in_fields="FIELDS",
        m_direction_offsetting="M_DIRECTON")

    # GP Tool: Table conversion of edited events to a feature layer.
    work_condition_events_lyr = arcpy.MakeRouteEventLayer_lr(
        in_routes=routes_fc,
        route_id_field=routes_id_field,
        in_table=work_event_table,
        in_event_properties="rid LINE fmeas tmeas",
        out_layer="work_condition_events_lyr").getOutput(0)

    # GP Tool: Copy feature layer to disk as feature class.
    arcpy.CopyFeatures_management(in_features=work_condition_events_lyr,
                                  out_feature_class=out_condition_event_fc)

    # Optional clean-up of temp data.
    if clean_up_temp_files:
        arcpy.AddMessage("Cleaning up temporary content...")
        # print("Cleaning up temporary content...")

        content_to_delete = [
            work_evaluated_route_segment_conditions, work_nodes_fc,
            work_routes_lyr, work_condition_events_lyr, work_event_table,
            work_route_evaluated_segments, work_routes_evaluated,
            work_routes_fc
        ]

        for item in content_to_delete:
            arcpy.Delete_management(item)

        arcpy.AddMessage("Temp files cleaned up.")
Example #29
0
    del updateRows
    del row

    #Use spatial join on target(endPoints) and join(OutputTransect)
    arcpy.SpatialJoin_analysis(endPoints, OutputTransect, endptTransctJoin)

    #Locate endpoint features along streamline route
    #Correct left/right orientation depends on direction that the streamlines were produced;
    #either from Mark's tools, or from digitizing direction
    arcpy.AddMessage("Locating endpoints along streamline route... ")
    props = "RID POINT MEAS"
    #Set search radius for locating features, set to the value of transect spacing minus 1
    distnce = str(DistanceSplit) + locateFeatUnit
    #Save the table as "locate_points" back into the wrkSpace user-inputted save location
    arcpy.LocateFeaturesAlongRoutes_lr(endptTransctJoin, strmCenterline,
                                       "Route", distnce, "locate_points",
                                       props, "FIRST", "DISTANCE", "NO_ZERO",
                                       "FIELDS", "NO_M_DIRECTION")

    #Create XY event layer from linear referencing table
    arcpy.MakeXYEventLayer_management("locate_points", "X_UTM", "Y_UTM",
                                      tableLayer, spatial_reference)

    #Find endpoints that are either on the left/right side of the streamline route
    arcpy.AddMessage(
        "Finding endpoints that are river left vs. river right... ")
    rivLeftExpr = '"DISTANCE" <= 0'
    rivRightExpr = '"DISTANCE" >= 0'
    ptRiverLeft = arcpy.FeatureClassToFeatureClass_conversion(
        tableLayer, General_GDB, "ptRiverLeft", rivLeftExpr)
    ptRiverRight = arcpy.FeatureClassToFeatureClass_conversion(
        tableLayer, General_GDB, "ptRiverRight", rivRightExpr)
Example #30
0
def ImportIntAtt(Intersections, TrafficControl, Routes, RouteID, BMP, EMP,
                 AttTable, Fields, Output, OutputTable):
    def FindAngle(O, P):
        import math
        if P[0] == O[0]:
            if P[1] == O[1]:
                #arcpy.AddWarning(str(O) + str(P))
                return 0  #1
            else:
                if P[1] > O[1]:
                    return 90  #2
                if P[1] < O[1]:
                    return 270  #3
        else:
            if P[1] == O[1]:
                if P[0] > O[0]:
                    return 0  #4
                else:
                    return 180  #5
            else:
                if (P[0] - O[0]) > 0 and (P[1] - O[1]) > 0:
                    return math.degrees(
                        math.atan((P[1] - O[1]) / (P[0] - O[0])))  #6
                elif (P[0] - O[0]) > 0 and (P[1] - O[1]) < 0:
                    return 360 - math.degrees(
                        math.atan(-(P[1] - O[1]) / (P[0] - O[0])))  #7
                elif (P[0] - O[0]) < 0 and (P[1] - O[1]) > 0:
                    return 180 - math.degrees(
                        math.atan(-(P[1] - O[1]) / (P[0] - O[0])))  #8
                elif (P[0] - O[0]) < 0 and (P[1] - O[1]) < 0:
                    return 180 + math.degrees(
                        math.atan((P[1] - O[1]) / (P[0] - O[0])))

    def FindClosestPoint(PolylineList, IntPoint):
        n = len(PolylineList)
        Dist0 = ((PolylineList[0][0] - IntPoint[0])**2 +
                 (PolylineList[0][1] - IntPoint[1])**2)**0.5
        Distn = ((PolylineList[n - 1][0] - IntPoint[0])**2 +
                 (PolylineList[n - 1][1] - IntPoint[1])**2)**0.5
        if Dist0 <= Distn:
            return [PolylineList[0], PolylineList[1]]
        else:
            return [PolylineList[n - 1], PolylineList[n - 2]]

    Buffer = "80 Feet"
    Tolerance = "10 Feet"
    Int = common.CreateOutPath(MainFile=Output, appendix='Int', Extension='')
    arcpy.Intersect_analysis(in_features=Routes,
                             out_feature_class=Int,
                             join_attributes="ALL",
                             cluster_tolerance="-1 Unknown",
                             output_type="POINT")

    SPJ = common.CreateOutPath(MainFile=Output, appendix='SPJ', Extension='')
    arcpy.SpatialJoin_analysis(target_features=Int,
                               join_features=Intersections,
                               out_feature_class=SPJ,
                               join_operation="JOIN_ONE_TO_ONE",
                               join_type="KEEP_COMMON",
                               match_option="CLOSEST",
                               search_radius=Buffer,
                               distance_field_name="")

    arcpy.DeleteIdentical_management(in_dataset=SPJ,
                                     fields=arcpy.Describe(SPJ).ShapeFieldName,
                                     xy_tolerance="",
                                     z_tolerance="0")

    OrgFields = [f.name for f in arcpy.ListFields(Intersections)]
    arcpy.DeleteField_management(SPJ, [
        f.name for f in arcpy.ListFields(SPJ)
        if not f.required and not f.name in OrgFields
    ])

    arcpy.SpatialJoin_analysis(target_features=SPJ,
                               join_features=TrafficControl,
                               out_feature_class=Output,
                               join_operation="JOIN_ONE_TO_ONE",
                               join_type="KEEP_COMMON",
                               match_option="CLOSEST",
                               search_radius=Buffer,
                               distance_field_name="")

    OrgFields.extend(['TRAF_CONT', 'LEG_COUNT', 'PeerGroup_CH2M_TJM'])
    arcpy.DeleteField_management(Output, [
        f.name for f in arcpy.ListFields(Output)
        if not f.required and not f.name in OrgFields
    ])

    EventTable = common.CreateOutPath(MainFile=Output,
                                      appendix='EventTable',
                                      Extension='')
    arcpy.LocateFeaturesAlongRoutes_lr(in_features=Output,
                                       in_routes=Routes,
                                       route_id_field=RouteID,
                                       radius_or_tolerance=Tolerance,
                                       out_table=EventTable,
                                       out_event_properties=" ".join(
                                           [RouteID, "POINT", "MP"]),
                                       route_locations="ALL",
                                       in_fields="FIELDS",
                                       m_direction_offsetting="M_DIRECTON")

    # Milepost Correction
    EMPDict = {
        r.getValue('INVENTORY'): r.getValue('Shape').lastPoint.M
        for r in arcpy.SearchCursor(Routes)
    }
    r = 0
    uc = arcpy.UpdateCursor(EventTable)
    for r in uc:
        inv = r.getValue('INVENTORY')
        MP = r.getValue('MP')
        if MP < 0:
            r.setValue('MP', 0)
            uc.updateRow(r)
        if MP > EMPDict[inv]:
            r.setValue('MP', EMPDict[inv])
            uc.updateRow(r)
    del uc, r

    AllF = [f.name for f in arcpy.ListFields(AttTable)]
    MF = [f for f in Fields if not f in AllF]
    if not MF == []:
        print(str(MF) + ' not found in ' + AttTable)
    IRIS_Diss = common.CreateOutPath(MainFile=Output,
                                     appendix='diss',
                                     Extension='')
    arcpy.DissolveRouteEvents_lr(
        in_events=AttTable,
        in_event_properties=' '.join([RouteID, 'LINE', BMP, EMP]),
        dissolve_field=';'.join(Fields),
        out_table=IRIS_Diss,
        out_event_properties=' '.join([RouteID, 'LINE', BMP, EMP]),
        dissolve_type="DISSOLVE",
        build_index="INDEX")

    arcpy.OverlayRouteEvents_lr(
        in_table=EventTable,
        in_event_properties=' '.join([RouteID, 'POINT', 'MP']),
        overlay_table=IRIS_Diss,
        overlay_event_properties=' '.join([RouteID, 'LINE', BMP, EMP]),
        overlay_type="INTERSECT",
        out_table=OutputTable,
        out_event_properties=' '.join([RouteID, 'POINT', 'MP']),
        in_fields="FIELDS",
        build_index="INDEX")

    common.AddField(Output, [
        fields_SC.intr.AADT_Major, fields_SC.intr.AADT_Minor,
        fields_SC.crash.ABuffer, fields_SC.crash.BBuffer
    ])

    arcpy.AddField_management(OutputTable, 'ApprType', 'TEXT')
    #arcpy.AddField_management(OutputTable,'ApprDeg','Double')
    Approach = {r.getValue('SiteID'): [] for r in arcpy.SearchCursor(Output)}

    OID = arcpy.Describe(OutputTable).OIDFieldName
    for r in arcpy.SearchCursor(OutputTable):
        k = r.getValue('SiteID')
        if k in Approach.keys():
            Approach[k].append({
                'OID': r.getValue(OID),
                'INV': r.getValue('INVENTORY'),
                'AADT': common.GetIntVal(r, 'AADT'),
                'Lanes': common.GetIntVal(r, 'LNS', 2),
                'Urban': r.getValue('URBAN'),
                'SurfWid': common.GetFloatVal(r, 'SURF_WTH', 24),
                'MedWid': common.GetFloatVal(r, 'MED_WTH')
            })
    for k in Approach.keys():
        AADT = [i['AADT'] for i in Approach[k]]
        INV = [i['INV'] for i in Approach[k]]
        major_i = AADT.index(max(AADT))
        major_inv = INV[major_i]
        for i, appr in enumerate(Approach[k]):
            if appr['AADT'] == max(AADT) or appr['INV'] == major_inv:
                Approach[k][i].update({'ApprType': 'Major'})
            else:
                Approach[k][i].update({'ApprType': 'Minor'})

    UC = arcpy.UpdateCursor(OutputTable)
    for r in UC:
        k = r.getValue('SiteID')
        o = r.getValue(OID)
        Type = ''
        for appr in Approach[k]:
            if appr['OID'] == o:
                Type = appr['ApprType']
        r.setValue('ApprType', Type)

        UC.updateRow(r)

    UC = arcpy.UpdateCursor(Output)
    for r in UC:
        k = r.getValue('SiteID')
        try:
            r.setValue(
                fields_SC.intr.AADT_Major['name'],
                max([
                    appr['AADT'] for appr in Approach[k]
                    if appr['ApprType'] == 'Major'
                ]))
        except:
            r.setValue(fields_SC.intr.AADT_Major['name'], 0)
        try:
            r.setValue(
                fields_SC.intr.AADT_Minor['name'],
                max([
                    appr['AADT'] for appr in Approach[k]
                    if appr['ApprType'] == 'Minor'
                ]))
        except:
            r.setValue(fields_SC.intr.AADT_Minor['name'], 0)
        try:
            W_Major = max([
                appr['SurfWid'] + appr['MedWid'] for appr in Approach[k]
                if appr['ApprType'] == 'Major'
            ])
        except:
            W_Major = 24
        try:
            W_Minor = max([
                appr['SurfWid'] + appr['MedWid'] for appr in Approach[k]
                if appr['ApprType'] == 'Minor'
            ])
        except:
            W_Minor = 24
        ABuffer = max(1.2 * (W_Major**2 + W_Minor**2)**0.5, 50)
        r.setValue(fields_SC.crash.ABuffer['name'], ABuffer)
        r.setValue(fields_SC.crash.BBuffer['name'], max(ABuffer, 250))
        AADT = [i['AADT'] for i in Approach[k]]
        major_i = AADT.index(max(AADT))
        LaneMajor = [i['Lanes'] for i in Approach[k]][0]
        UC.updateRow(r)

    arcpy.Delete_management(Int)
    arcpy.Delete_management(EventTable)
    arcpy.Delete_management(SPJ)
    arcpy.Delete_management(IRIS_Diss)