Exemplo n.º 1
0
def copyfromstaged(lyrlist, admin, fdset, fcoutpath):
    for lyr in lyrlist:
        print(fcoutpath + admin + '.' + lyr)
        if Exists(fcoutpath + admin + '.' + lyr):
            DeleteFeatures_management(fcoutpath + admin + '.' + lyr)
            Append_management(ws + "/" + tempgdb + '/' + lyr,
                              fcoutpath + admin + '.' + lyr, "NO_TEST", "#")
            print "updated " + lyr + " in " + fcoutpath
        else:
            FeatureClassToFeatureClass_conversion(
                ws + "/" + tempgdb + '/' + lyr, fcoutpath, lyr)
            print "copied new " + lyr + " feature class to " + fcoutpath
            print " Check roles and privleges on this " + lyr + " at " + fcoutpath
        try:
            CalculateField_management(fcoutpath + admin + '.' + lyr,
                                      "NETWORKDATE",
                                      "datetime.datetime.now( )", "PYTHON_9.3",
                                      "#")
            print "copy date field updated"
        except:
            AddField_management(fcoutpath + admin + '.' + lyr, "NETWORKDATE",
                                "DATE")
            CalculateField_management(fcoutpath + admin + '.' + lyr,
                                      "NETWORKDATE",
                                      "datetime.datetime.now( )", "PYTHON_9.3",
                                      "#")
            print "copy date field added and updated"
            pass
    return
Exemplo n.º 2
0
def Non_State_Centerpoint_Check():
    MakeFeatureLayer_management(in_features="Database Connections/SDEPROD_SHARED.sde/SHARED.NON_STATE_SYSTEM", out_layer="C_Routes", where_clause="LRS_KEY like '%C%' OR  LRS_ROUTE_PREFIX = 'C'")
    FeatureToPoint_management(NonState_fx, "C_Routes_Point", "INSIDE")
    #LocateFeaturesAlongRoutes_lr(NonState_fx, NUSYS, "ROUTE", "50 Feet", "Nonstate_Point_LFAR", "RID LINE FMEAS TMEAS", "FIRST", "DISTANCE", "ZERO", "FIELDS", "M_DIRECTON")
    Intersect_analysis("Nusys_Extract #;C_Routes #", out_feature_class="C:/temp/Nusys_Check.gdb/C_Routes_Point_Int5", join_attributes="ALL", cluster_tolerance="5 Feet", output_type="POINT")
    
    Dissolve_management("C_Routes_Point_Int5", out_feature_class="C:/temp/Nusys_Check.gdb/C_Routes_Point_Int_Route_Mileage_5D", dissolve_field="ROUTE;DIVIDED_UNDIVIDED;LRS_KEY", statistics_fields="COUNTY_BEGIN_MP MIN;COUNTY_END_MP MAX;LRS_BEG_CNTY_LOGMILE MIN;LRS_END_CNTY_LOGMILE MAX", multi_part="MULTI_PART", unsplit_lines="DISSOLVE_LINES")

    AddField_management(in_table="C_Routes_Point_Int_Route_Mileage_5D", field_name="Check_LRS", field_type="TEXT", field_precision="", field_scale="", field_length="15", field_alias="", field_is_nullable="NULLABLE", field_is_required="NON_REQUIRED", field_domain="")
    CalculateField_management(in_table="C_Routes_Point_Int_Route_Mileage_5D", field="Check_LRS", expression="!LRS_KEY![:11]", expression_type="PYTHON_9.3", code_block="")
    
    AddField_management(in_table="C_Routes_Point_Int_Route_Mileage_5D", field_name="Check_Route", field_type="TEXT", field_precision="", field_scale="", field_length="15", field_alias="", field_is_nullable="NULLABLE", field_is_required="NON_REQUIRED", field_domain="")
    CalculateField_management(in_table="C_Routes_Point_Int_Route_Mileage_5D", field="Check_Route", expression="!Route![:11]", expression_type="PYTHON_9.3", code_block="")    
    
    MakeFeatureLayer_management("C_Routes_Point_Int_Route_Mileage_5D", out_layer="C_Routes_Check_Del", where_clause="Check_Route <> Check_LRS OR Check_Route is null OR Check_LRS is null")
    DeleteFeatures_management("C_Routes_Check_Del")
Exemplo n.º 3
0
def delForTesting():
    env.workspace = repo
    whereClause = "ObjectID = 91783"
    enterprisedbRoutes = gdb + "\INTERMODAL.DBO.KTRIPS_ROUTES"
    loadedRoutesLayer = 'routesAsLyr'
    MakeFeatureLayer_management(enterprisedbRoutes, loadedRoutesLayer, "#",
                                "#")
    SelectLayerByAttribute_management(loadedRoutesLayer, "NEW_SELECTION",
                                      whereClause)
    currentCount = GetCount_management(loadedRoutesLayer)
    print "Selected " + str(currentCount) + " rows to delete."
    # Probably have to disconnect users before the next part will work. =(
    if int(str(currentCount)) > 0:
        print 'Deleting selected rows...'
        DeleteFeatures_management(loadedRoutesLayer)
    else:
        print 'Will not delete as there are no rows selected.'
Exemplo n.º 4
0
def ClearSteward(StewardID):
    from arcpy import DeleteFeatures_management, DeleteRows_management, GetCount_management
    targetpath = currentPathSettings.EntDB + '/' + currentPathSettings.EDBName + '.' + currentPathSettings.EDBO
    #\\gisdata\arcgis\GISdata\DASC\NG911\Final\[email protected]\NG911.GEO.NG911\NG911.GEO.RoadCenterline
    print targetpath
    env.workspace = targetpath
    where_clause = "STEWARD LIKE '" + StewardID + "'"

    MakeFeatureLayer_management(targetpath + ".RoadCenterline",
                                "Steward_Delete_Roads", where_clause)
    MakeTableView_management(targetpath + ".RoadAlias", "Steward_Delete_Alias",
                             where_clause)
    LineCount = GetCount_management("Steward_Delete_Roads")
    AliasCount = GetCount_management("Steward_Delete_Alias")
    print 'deleting ' + str(
        LineCount) + ' road center lines where ' + where_clause
    print 'deleting ' + str(AliasCount) + ' alias rows where ' + where_clause
    DeleteFeatures_management(in_features="Steward_Delete_Roads")
    DeleteRows_management(in_rows="Steward_Delete_Alias")
def TranscendRampReplacement():
    MakeFeatureLayer_management (routesSourceCenterlines, routesSourceFeatureLayer)

    SelectLayerByAttribute_management(routesSourceFeatureLayer, "CLEAR_SELECTION")
    selectionQuery = """ "LRS_ROUTE_PREFIX" = 'X' AND "Ramps_LRSKey" IS NOT NULL AND "Ramps_LRSKey" <> '' """
    SelectLayerByAttribute_management(routesSourceFeatureLayer, "NEW_SELECTION", selectionQuery)

    countResult = GetCount_management(routesSourceFeatureLayer)
    intCount = int(countResult.getOutput(0))

    print('Selected ' + str(intCount) + ' ramp features to be replaced.')

    if intCount > 0:
        print("Deleting those ramp features from the " + returnFeatureClass(routesSourceCenterlines) + " layer.")
        DeleteFeatures_management(routesSourceFeatureLayer)
    else:
        print("No features selected. Skipping feature deletion.")

    # Remove the matching routes to prepare for the Interchange_Ramps information.
    ## After error matching is achieved, use replace geometry and replace attributes to not lose data
    ## from using the less effective method of:
    ## deleting the old Interchange_Ramps information, then re-adding with append.

    # Add the Interchange_Ramps information.

    # Checking to see if the copy for repairing already exists.
    # If so, remove it.
    if Exists(interchangeRampFCRepairCopy):
        Delete_management(interchangeRampFCRepairCopy)
    else:
        pass
    # Create a new file for the copy for repairing since repair modifies the input.
    CopyFeatures_management(interchangeRampFC, interchangeRampFCRepairCopy)

    # Repairs the geometry, modifies input.
    # Deletes features with null geometry (2 expected, until Shared.Interchange_Ramp is fixed).
    print("Repairing ramp geometry in the " + returnFeatureClass(interchangeRampFCRepairCopy) + " layer.")
    RepairGeometry_management(interchangeRampFCRepairCopy, "DELETE_NULL")

    # Create a fieldmapping object so that the Interchange_Ramps can be correctly imported with append.
    appendInputs = [interchangeRampFCRepairCopy]
    appendTarget = routesSourceCenterlines
    schemaType = "NO_TEST"

    # Field mapping goes here.
    # Interchange_Ramp.LRS_KEY to RoutesSource_Test.LRSKEY
    fm_Field1 = FieldMap()
    fm_Field1.addInputField(interchangeRampFCRepairCopy, "LRS_KEY")
    fm_Field1_OutField = fm_Field1.outputField
    fm_Field1_OutField.name = 'LRSKEY'
    fm_Field1.outputField = fm_Field1_OutField

    # Interchange_Ramp.BEG_CNTY_LOGMILE to RoutesSource_Test.NON_STATE_BEGIN_MP
    fm_Field2 = FieldMap()
    fm_Field2.addInputField(interchangeRampFCRepairCopy, "BEG_CNTY_LOGMILE")
    fm_Field2_OutField = fm_Field2.outputField
    fm_Field2_OutField.name = 'NON_STATE_BEGIN_MP'
    fm_Field2.outputField = fm_Field2_OutField

    # Interchange_Ramp.END_CNTY_LOGMILE to RoutesSource_Test.NON_STATE_END_MP
    fm_Field3 = FieldMap()
    fm_Field3.addInputField(interchangeRampFCRepairCopy, "END_CNTY_LOGMILE")
    fm_Field3_OutField = fm_Field3.outputField
    fm_Field3_OutField.name = 'NON_STATE_END_MP'
    fm_Field3.outputField = fm_Field3_OutField

    # Create the fieldMappings object
    interchangeRampsMappings = FieldMappings()
    interchangeRampsMappings.addFieldMap(fm_Field1)
    interchangeRampsMappings.addFieldMap(fm_Field2)
    interchangeRampsMappings.addFieldMap(fm_Field3)

    # Add the fieldMap objects to the fieldMappings object.
    print("Appending the features from " + returnFeatureClass(interchangeRampFCRepairCopy) + " into " + returnFeatureClass(routesSourceCenterlines) + ".")
    Append_management(appendInputs, appendTarget, schemaType, interchangeRampsMappings)
def removeSmallRoads():

    # Going to have to build a list of OIDs for roads
    # with a Shape length less than or equal to 1500.
    # Not going to have the SQL information to do a
    # selection based on a clause.

    # Could also add a field and then calculate the
    # length into it prior to running this selection.

    # Need to make a search cursor that gets the ObjectID and ShapeLength
    # for each road.

    # Then, need to add the ObjectID for roads with ShapeLength less than
    # 1500 to a list, then build SQL queries dynamically to select
    # and add features from that list, until the list is exhausted
    # and all features have been selected.

    print "Removing the small roads from the data."

    #CopyFeatures_management(countyRoadsFeature, countyRoadsFeaturePrereduction_Q)

    inMemoryRoadsLayer = 'inMemoryRoadsLayerFC'

    MakeFeatureLayer_management(countyRoadsFeature, inMemoryRoadsLayer)

    inMemRoadsFields = ListFields(inMemoryRoadsLayer)

    for inMemRoadField in inMemRoadsFields:
        print str(inMemRoadField.name)

    smallRoadsSCFields = ['ID2', 'Shape@Length']

    smallRoadsSearchCursor = daSearchCursor(inMemoryRoadsLayer,
                                            smallRoadsSCFields)

    roadIDsToRemove = list()
    '''
    for smallRoadRow in smallRoadsSearchCursor:
        if int(str(smallRoadRow[0])) % 500 == 0:
            print str(smallRoadRow[0])
        else:
            pass
        
    raise("Stop error.")
    '''

    for smallRoadRow in smallRoadsSearchCursor:
        if smallRoadRow[1] <= 1500:
            roadIDsToRemove.append(smallRoadRow[0])
        else:
            pass

    roadRemovalCounter = 0

    roadsReductionWhereClause = """ "ID2" IN ("""

    for roadID in roadIDsToRemove:
        if roadRemovalCounter <= 998:
            roadsReductionWhereClause = roadsReductionWhereClause + str(
                roadID) + """, """
            roadRemovalCounter += 1
        else:
            # Remove the trailing ", " and add a closing parenthesis.
            roadsReductionWhereClause = roadsReductionWhereClause[:-2] + """) """
            SelectLayerByAttribute_management(inMemoryRoadsLayer,
                                              "ADD_TO_SELECTION",
                                              roadsReductionWhereClause)

            # Debug only
            print "Selecting..."
            selectedRoadsResult = GetCount_management(inMemoryRoadsLayer)
            selectedRoadsCount = int(selectedRoadsResult.getOutput(0))
            print "Number of roads selected: " + str(selectedRoadsCount)

            roadRemovalCounter = 0
            roadsReductionWhereClause = """ "ID2" IN ("""
            roadsReductionWhereClause = roadsReductionWhereClause + str(
                roadID) + """, """

    # Remove the trailing ", " and add a closing parenthesis.
    roadsReductionWhereClause = roadsReductionWhereClause[:-2] + """) """
    SelectLayerByAttribute_management(inMemoryRoadsLayer, "ADD_TO_SELECTION",
                                      roadsReductionWhereClause)

    # Debug only
    print "Selecting..."
    selectedRoadsResult = GetCount_management(inMemoryRoadsLayer)
    selectedRoadsCount = int(selectedRoadsResult.getOutput(0))
    print "Number of roads selected: " + str(selectedRoadsCount)

    selectedRoadsResult = GetCount_management(inMemoryRoadsLayer)

    selectedRoadsCount = int(selectedRoadsResult.getOutput(0))

    if selectedRoadsCount >= 1:
        DeleteFeatures_management(inMemoryRoadsLayer)
    else:
        pass
def countyAndRoadPreprocessing():

    print "Removing non-County roads and other roads not displayed on the map..."
    featureClass1 = nSSNoZ
    featureClass1Out = nSSNoZCounty

    inMemoryRoadsLayer1 = "roadsToCounty"

    # Need to delete out the non-county roads.
    CopyFeatures_management(featureClass1, featureClass1Out)

    # Load the feature class with all non_state roads.
    MakeFeatureLayer_management(featureClass1Out, inMemoryRoadsLayer1)

    # Now select & delete all the roads that do not have 999 as their city number, which would mean
    # that they are in the county.
    # Also select any roads that will not be shown in the map per Elaine's query:
    # (SURFACE <> 'Propose' AND SURFACE IS NOT NULL) AND VISIBILITY = 'Y'
    selectionString = """ "CITYNUMBER" <> 999 OR SURFACE = 'Propose' OR SURFACE IS NULL OR VISIBILITY <> 'Y' """

    SelectLayerByAttribute_management(inMemoryRoadsLayer1, "NEW_SELECTION",
                                      selectionString)

    countNumber = GetCount_management(inMemoryRoadsLayer1)

    if countNumber >= 1:
        try:
            DeleteFeatures_management(inMemoryRoadsLayer1)
        except Exception as e:
            # If an error occurred, print line number and error message
            tb = sys.exc_info()[2]
            print("Line {0}".format(tb.tb_lineno))
            print(e.message)
    else:
        pass

    # Cleanup
    if 'inMemoryRoadsLayer1' in locals():
        del inMemoryRoadsLayer1
    else:
        pass

    featureClass2 = nSSNoZCounty
    fieldListForRoads = ["RD_NAMES", "COUNTY_NUMBER"]
    featureClass2Out = nSSNoZCountyDS

    featureClass3 = featureClass2Out
    featureClass3Out = nSSNoZCountyClean

    inMemoryRoadsLayer2 = "roadsToDissolve"
    inMemoryRoadsLayer3 = "roadsToClean"

    print "Dissolving road segments by Name & County..."
    # Load the undissolved feature class.
    MakeFeatureLayer_management(featureClass2, inMemoryRoadsLayer2)

    # Dissolve based on RD_NAMES and COUNTY_NUMBER.
    Dissolve_management(inMemoryRoadsLayer2, featureClass2Out,
                        fieldListForRoads, "", "SINGLE_PART", "DISSOLVE_LINES")

    # Cleanup
    if 'inMemoryRoadsLayer2' in locals():
        del inMemoryRoadsLayer2
    else:
        pass

    print "Deleting unnamed road segments..."
    # Copy the feature class to prepare for deleting unnamed roads.
    CopyFeatures_management(featureClass3, featureClass3Out)

    # Load the copied feature class.
    MakeFeatureLayer_management(featureClass3Out, inMemoryRoadsLayer3)

    # Now select & delete all the roads that have <null> or "" as their roadname.
    selectionString = """ "RD_NAMES" IS NULL OR "RD_NAMES" = '' OR "COUNTY_NUMBER" = 0 OR "COUNTY_NUMBER" >= 106"""

    SelectLayerByAttribute_management(inMemoryRoadsLayer3, "NEW_SELECTION",
                                      selectionString)

    countNumber = GetCount_management(inMemoryRoadsLayer3)

    print "For " + selectionString + ", selected = " + str(countNumber)

    if countNumber >= 1:
        try:
            DeleteFeatures_management(inMemoryRoadsLayer3)
        except Exception as e:
            # If an error occurred, print line number and error message
            tb = sys.exc_info()[2]
            print("Line {0}".format(tb.tb_lineno))
            print(e.message)
            try:
                del tb
            except:
                pass
    else:
        pass

    # Cleanup
    if 'inMemoryRoadsLayer3' in locals():
        del inMemoryRoadsLayer3
    else:
        pass

    print "Preprocessing for county road label points is complete!"
def featureReplacement(sourceFL, targetFL, featuresToSelect):
    # 1c.) Get the common fields so that you can search and insert correctly.
    targetFeatureDesc = Describe(targetFL)
    targetFeatureFields = targetFeatureDesc.fields
    targetFeatureOIDField = targetFeatureDesc.OIDFieldName
    targetFeatureShapeField = targetFeatureDesc.shapeFieldName
    targetFeatureFieldNames = [x.name for x in targetFeatureFields]
    
    sourceFeatureDesc = Describe(sourceFL)
    sourceFeatureFields = sourceFeatureDesc.fields
    sourceFeatureOIDField = sourceFeatureDesc.OIDFieldName
    sourceFeatureShapeField = sourceFeatureDesc.shapeFieldName
    sourceFeatureFieldNames = [x.name for x in sourceFeatureFields]
    
    excludeFieldNames = [targetFeatureOIDField, targetFeatureShapeField, sourceFeatureOIDField, sourceFeatureShapeField]
    
    searchCursorFields = [x for x in targetFeatureFieldNames if x in sourceFeatureFieldNames and x not in excludeFieldNames]
    searchCursorFields.append('SHAPE@')
    
    # Remove and then re-add the uniqueKeyField so that it is the last column and can be easily referenced.
    searchCursorFields.remove(str(uniqueKeyFieldToUse))
    searchCursorFields.append(str(uniqueKeyFieldToUse))
    insertCursorFields = searchCursorFields
    
    # Select the features in the source layer
    SelectLayerByAttribute_management(sourceFL, "NEW_SELECTION", featuresToSelect)
    # Repeat the selection in the target layer
    SelectLayerByAttribute_management(targetFL, "NEW_SELECTION", featuresToSelect)
    # Then select the common segments spatially, with some room for possible movement.
    SelectLayerByLocation_management(targetFL, 'WITHIN_A_DISTANCE', sourceFL, 50, 'SUBSET_SELECTION')
    
    # 5.) Count selected features in the target and delete them if there is at least 1.
    countResult0 = GetCount_management(targetFL)
    intCount0 = int(countResult0.getOutput(0))
    if intCount0 >= 1:
        # 12.) Delete the selected features in the input layer, if any.
        try:
            DeleteFeatures_management(targetFL)
        except:
            print("Could not delete features for the selection " + str(featuresToSelect) + ".")
    else:
        pass
    
    # 10.) Count to make sure that at least one feature is selected.
    countResult1 = GetCount_management(sourceFL)
    intCount1 = int(countResult1.getOutput(0))
    if intCount1 >= 1:
        # If so, cursor the features out
        featureList = list()
        
        newCursor = daSearchCursor(sourceFL, searchCursorFields)
        
        for cursorItem in newCursor:
            featureList.append(list(cursorItem))
        
        try:
            del newCursor
        except:
            pass
        
        # 11.) Insert the selected source features into the copy of the centerlines.
        newCursor = daInsertCursor(targetFL, insertCursorFields)
        
        for featureItem in featureList:
            newCursor.insertRow(featureItem)
        
        try:
            del newCursor
        except:
            pass
        try:
            del featureList
        except:
            pass
def dissolveBasedOnLocalRouteKeys(routesToDissolve, subsetSelectionQuery):
    # Moved out the selection building code to the other function where
    # it makes more sense.
    # Use similar code here to what is found in the main dissolve loop.
    # Just need to do multiselection on all of the possible routes that
    # match the subsetSelectionQuery and for each multiselection, create
    # a dissolve feature set, then use the same reintroduction tests
    # that are used in the main dissolve to reintroduce the dissolved
    # lines without removing any that weren't dissolved or adding
    # any new overlaps.

    fcAsFeatureLayerForDissolves = 'FCAsFeatureLayer_Dissolves'

    if Exists(fcAsFeatureLayerForDissolves):
        Delete_management(fcAsFeatureLayerForDissolves)
    else:
        pass

    MakeFeatureLayer_management(routesToDissolve, fcAsFeatureLayerForDissolves)

    lrsKeyFieldList = [str(lrsKeyToUse)]
    newCursor = daSearchCursor(routesToDissolve, lrsKeyFieldList,
                               subsetSelectionQuery)
    uniqueLRSKeysDict = dict()
    for cursorRow in newCursor:
        uniqueLRSKeysDict[str(cursorRow[0])] = 1

    try:
        del newCursor
    except:
        pass

    uniqueLRSKeysList = uniqueLRSKeysDict.keys()
    try:
        uniqueLRSKeysList.remove('None')
    except:
        print(
            "Could not remove 'None' from the list of uniqueLRSKeys since it was not a part of the list."
        )

    print("LRSKey list creation successful.")
    print('Found ' + str(len(uniqueLRSKeysList)) +
          ' unique LRS Keys in the centerline data for this query:')
    print(str(subsetSelectionQuery))

    #Use multiSelection

    multiSelectionQueryBase = str(
        str(subsetSelectionQuery) + ''' AND ''' + ''' "''' + str(lrsKeyToUse) +
        '''" IS NOT NULL AND "''' + str(lrsKeyToUse) + '''" IN (''')
    multiSelectionQuery = multiSelectionQueryBase
    multiCounter = 0
    multiDissolveFields = [
        str(lrsKeyToUse), 'LRS_COUNTY_PRE', 'LRS_ROUTE_PREFIX',
        'LRS_ROUTE_NUM', 'LRS_ROUTE_SUFFIX', 'LRS_UNIQUE_IDENT',
        'LRS_UNIQUE_IDENT1', 'KDOT_COUNTY_L', 'KDOT_COUNTY_R'
    ]
    ##multiDissolveFields = str(lrsKeyToUse) + ';LRS_COUNTY_PRE;LRS_ROUTE_PREFIX;LRS_ROUTE_NUM;LRS_ROUTE_SUFFIX;LRS_UNIQUE_IDENT;LRS_UNIQUE_IDENT1'
    ##multiStatsFields = str(n1FromMeas) + " MIN;" + str(n1ToMeas) + " MAX"
    multiStatsFields = ""
    singlePart = "SINGLE_PART"
    unsplitLines = "UNSPLIT_LINES"

    # 3.) Loop through the list of unique LRS Keys
    for uniqueKeyItem in uniqueLRSKeysList:
        # Make a selection list that includes 50 keys, then select the keys and dissolve to make a new
        # feature class.
        # After the selection is dissolved, use a spatial select on the original feature class and
        # an attribute selection on the original feature class to see which original features should
        # be deleted.
        # Then, delete the selected features (if at least 1 selected).
        #
        try:
            Delete_management(dissolveOutFC)
        except:
            print("Could not delete the dissolveOutFC layer.")

        # 4.) For groups of 2000 LRS Keys, select all the features with those LRS Keys.
        if multiCounter <= 1999:
            multiSelectionQuery += """'""" + str(
                uniqueKeyItem) + """'""" + """, """
            multiCounter += 1
        else:
            # Add the current item, then
            multiSelectionQuery += """'""" + str(
                uniqueKeyItem) + """'""" + """, """
            # Remove the trailing ", " and add a closing parenthesis.
            multiSelectionQuery = multiSelectionQuery[:-2] + """) """
            SelectLayerByAttribute_management(fcAsFeatureLayerForDissolves,
                                              "NEW_SELECTION",
                                              multiSelectionQuery)
            # Have to do from step 5 on here also.

            ### -shouldbeafunctionblock#1- ###
            # 5.) Count selected features.
            countResult0 = GetCount_management(fcAsFeatureLayerForDissolves)
            intCount0 = int(countResult0.getOutput(0))
            if intCount0 >= 1:
                # 6.) Make a new layer or dissolved layer from this selection.
                Dissolve_management(fcAsFeatureLayerForDissolves,
                                    dissolveOutFC, multiDissolveFields,
                                    multiStatsFields, singlePart, unsplitLines)

                # 7.) Count the number of dissolved features.
                countResult1 = GetCount_management(dissolveOutFC)
                intCount1 = int(countResult1.getOutput(0))
                print('Counted ' + str(intCount1) +
                      ' features returned for that dissolve.')
                # 8a.) If the number of dissolved features is 0, then append the error to the error file
                #       and go on to the next LRS Key in the loop.
                if intCount1 == 0:
                    with open(dissolveErrorsFile, 'a') as errorFile:
                        errorFile.write(str(multiSelectionQuery))
                # 8b.) From the spatial select, select the subset of features that also have a matching LRS Key.
                else:
                    SelectLayerByAttribute_management(
                        fcAsFeatureLayerForDissolves, 'NEW_SELECTION',
                        multiSelectionQuery)
                    # 9.) Else, spatially select features in the original feature class with 'SHARE_A_LINE_SEGMENT_WITH'.
                    SelectLayerByLocation_management(
                        fcAsFeatureLayerForDissolves,
                        'SHARE_A_LINE_SEGMENT_WITH', dissolveOutFC, 0,
                        'SUBSET_SELECTION')
                    # 10.) Count to make sure that at least one feature is selected.
                    countResult2 = GetCount_management(
                        fcAsFeatureLayerForDissolves)
                    intCount2 = int(countResult2.getOutput(0))
                    print(
                        'There were ' + str(intCount2) +
                        ' features selected for replacement in the fcAsFeatureLayerForDissolves layer.'
                    )
                    if intCount2 >= 1:
                        # 11.) If so, cursor the features out of the dissolve layer.
                        featureList = list()
                        searchCursorFields = [
                            str(lrsKeyToUse), 'LRS_COUNTY_PRE',
                            'LRS_ROUTE_PREFIX', 'LRS_ROUTE_NUM',
                            'LRS_ROUTE_SUFFIX', 'LRS_UNIQUE_IDENT',
                            'LRS_UNIQUE_IDENT1', 'KDOT_COUNTY_L',
                            'KDOT_COUNTY_R', 'SHAPE@'
                        ]
                        newCursor = daSearchCursor(dissolveOutFC,
                                                   searchCursorFields)

                        for cursorItem in newCursor:
                            featureList.append(list(cursorItem))

                        try:
                            del newCursor
                        except:
                            pass

                        # 12.) Delete the selected features in the input layer.
                        try:
                            DeleteFeatures_management(
                                fcAsFeatureLayerForDissolves)
                        except:
                            print(
                                "Could not delete features for the selection "
                                + str(multiSelectionQuery) + ".")
                        # 13.) Insert the features from the dissolve layer into the copy of the centerlines.
                        insertCursorFields = [
                            str(lrsKeyToUse), 'LRS_COUNTY_PRE',
                            'LRS_ROUTE_PREFIX', 'LRS_ROUTE_NUM',
                            'LRS_ROUTE_SUFFIX', 'LRS_UNIQUE_IDENT',
                            'LRS_UNIQUE_IDENT1', 'KDOT_COUNTY_L',
                            'KDOT_COUNTY_R', 'SHAPE@'
                        ]
                        newCursor = daInsertCursor(
                            fcAsFeatureLayerForDissolves, insertCursorFields)

                        for featureItem in featureList:
                            newCursor.insertRow(featureItem)

                        try:
                            del newCursor
                        except:
                            pass
                        try:
                            del featureList
                        except:
                            pass
                    else:
                        pass
            multiSelectionQuery = ''' "''' + str(
                lrsKeyToUse) + '''" IS NOT NULL AND "''' + str(
                    lrsKeyToUse) + '''" IN ('''
            multiCounter = 0
            ### -shouldbeafunctionblock#1- ###

    # After the for loop, if there is still anything remaining which was unselected in the
    # the previous multiSelectionQuery steps.
    # Remove the trailing ", " and add a closing parenthesis.
    if multiSelectionQuery != multiSelectionQueryBase:
        multiSelectionQuery = multiSelectionQuery[:-2] + """) """
    else:
        # The selection query would not select anything.
        return
    SelectLayerByAttribute_management(fcAsFeatureLayerForDissolves,
                                      "NEW_SELECTION", multiSelectionQuery)

    # Then redo from step 5 on at the end of the loop IF there is anything left to select
    # which was not selected... so if selectionCounter != 0.

    ### -shouldbeafunctionblock#2- ###
    # 5.) Count selected features.
    countResult0 = GetCount_management(fcAsFeatureLayerForDissolves)
    intCount0 = int(countResult0.getOutput(0))
    if intCount0 >= 1:
        # 6.) Make a new layer or dissolved layer from this selection. -- Question about fields.
        Dissolve_management(fcAsFeatureLayerForDissolves, dissolveOutFC,
                            multiDissolveFields, multiStatsFields, singlePart,
                            unsplitLines)

        # 7.) Count the number of dissolved features.
        countResult1 = GetCount_management(dissolveOutFC)
        intCount1 = int(countResult1.getOutput(0))
        print('Counted ' + str(intCount1) +
              ' features returned for that dissolve.')
        # 8a.) If the number of dissolved features is 0, then append the error to the error file
        #       and go on to the next LRS Key in the loop.
        if intCount1 == 0:
            with open(dissolveErrorsFile, 'a') as errorFile:
                errorFile.write(str(multiSelectionQuery))
        # 8b.) From the spatial select, select the subset of features that also have a matching LRS Key.
        else:
            SelectLayerByAttribute_management(fcAsFeatureLayerForDissolves,
                                              'NEW_SELECTION',
                                              multiSelectionQuery)
            # 9.) Else, spatially select features in the original feature class with 'SHARE_A_LINE_SEGMENT_WITH'.
            SelectLayerByLocation_management(fcAsFeatureLayerForDissolves,
                                             'SHARE_A_LINE_SEGMENT_WITH',
                                             dissolveOutFC, 0,
                                             'SUBSET_SELECTION')
            # 10.) Count to make sure that at least one feature is selected.
            countResult2 = GetCount_management(fcAsFeatureLayerForDissolves)
            intCount2 = int(countResult2.getOutput(0))
            print(
                'There were ' + str(intCount2) +
                ' features selected in the fcAsFeatureLayerForDissolves layer.'
            )
            if intCount2 >= 1:
                # 11.) If so, cursor the features out of the dissolve layer.
                featureList = list()
                searchCursorFields = [
                    str(lrsKeyToUse), 'LRS_COUNTY_PRE', 'LRS_ROUTE_PREFIX',
                    'LRS_ROUTE_NUM', 'LRS_ROUTE_SUFFIX', 'LRS_UNIQUE_IDENT',
                    'LRS_UNIQUE_IDENT1', 'KDOT_COUNTY_L', 'KDOT_COUNTY_R',
                    'SHAPE@'
                ]
                newCursor = daSearchCursor(dissolveOutFC, searchCursorFields)

                for cursorItem in newCursor:
                    featureList.append(list(cursorItem))

                try:
                    del newCursor
                except:
                    pass

                # 12.) Delete the selected features in the input layer.
                try:
                    DeleteFeatures_management(fcAsFeatureLayerForDissolves)
                except:
                    print("Could not delete features for the selection " +
                          str(multiSelectionQuery) + ".")
                # 13.) Insert the features from the dissolve layer into the copy of the centerlines.
                insertCursorFields = [
                    str(lrsKeyToUse), 'LRS_COUNTY_PRE', 'LRS_ROUTE_PREFIX',
                    'LRS_ROUTE_NUM', 'LRS_ROUTE_SUFFIX', 'LRS_UNIQUE_IDENT',
                    'LRS_UNIQUE_IDENT1', 'KDOT_COUNTY_L', 'KDOT_COUNTY_R',
                    'SHAPE@'
                ]
                newCursor = daInsertCursor(fcAsFeatureLayerForDissolves,
                                           insertCursorFields)

                for featureItem in featureList:
                    newCursor.insertRow(featureItem)

                try:
                    del newCursor
                except:
                    pass
                try:
                    del featureList
                except:
                    pass
            else:
                pass
Exemplo n.º 10
0
def transferBasedOnLocalRouteKeys():
    # Build a list of the unique route keys that match the given criteria:
    # Then, use that list to select the features in the source with those
    # keys.
    # Next, spatially select features in the target layer with the
    # selected features from the source layer.
    # If there are more than 0 features selected, delete the selected
    # target features.
    # Then, cursor in the selected source features.

    subsetSelectionQuery = """ KDOT_LRS_KEY LIKE '%L%' AND NOT KDOT_LRS_KEY LIKE '%W%' """

    fcAsFeatureLayerForTransferring = 'FCAsFeatureLayer_Transferring'

    if Exists(fcAsFeatureLayerForTransferring):
        Delete_management(fcAsFeatureLayerForTransferring)
    else:
        pass

    MakeFeatureLayer_management(fcWithroutesToTransferFrom,
                                fcAsFeatureLayerForTransferring)
    MakeFeatureLayer_management(targetFC1, targetFC1asFeatureLayer)

    lrsKeyFieldList = [str(lrsKeyToUse)]
    newCursor = daSearchCursor(fcWithroutesToTransferFrom, lrsKeyFieldList,
                               subsetSelectionQuery)
    uniqueLRSKeysDict = dict()
    for cursorRow in newCursor:
        uniqueLRSKeysDict[str(cursorRow[0])] = 1

    try:
        del newCursor
    except:
        pass

    uniqueLRSKeysList = uniqueLRSKeysDict.keys()
    try:
        uniqueLRSKeysList.remove('None')
    except:
        print(
            "Could not remove 'None' from the list of uniqueLRSKeys since it was not a part of the list."
        )

    print("LRSKey list creation successful.")
    print('Found ' + str(len(uniqueLRSKeysList)) +
          ' unique LRS Keys in the centerline data for this query:')
    print(str(subsetSelectionQuery))

    #Use multiSelection

    multiSelectionQueryBase = str(
        str(subsetSelectionQuery) + ''' AND ''' + ''' "''' + str(lrsKeyToUse) +
        '''" IS NOT NULL AND "''' + str(lrsKeyToUse) + '''" IN (''')
    multiSelectionQuery = multiSelectionQueryBase
    multiCounter = 0
    ##multiDissolveFields = [str(lrsKeyToUse), 'LRS_COUNTY_PRE', 'LRS_ROUTE_PREFIX', 'LRS_ROUTE_NUM', 'LRS_ROUTE_SUFFIX', 'LRS_UNIQUE_IDENT',
    ##    'LRS_UNIQUE_IDENT1', 'KDOT_COUNTY_L', 'KDOT_COUNTY_R']
    ##multiDissolveFields = str(lrsKeyToUse) + ';LRS_COUNTY_PRE;LRS_ROUTE_PREFIX;LRS_ROUTE_NUM;LRS_ROUTE_SUFFIX;LRS_UNIQUE_IDENT;LRS_UNIQUE_IDENT1'
    ##multiStatsFields = str(n1FromMeas) + " MIN;" + str(n1ToMeas) + " MAX"
    ##multiStatsFields = ""
    ##singlePart = "SINGLE_PART"
    ##unsplitLines = "UNSPLIT_LINES"

    # 3.) Loop through the list of unique LRS Keys
    for uniqueKeyItem in uniqueLRSKeysList:
        # Make a selection list that includes 50 keys, then select the keys and dissolve to make a new
        # feature class.
        # After the selection is dissolved, use a spatial select on the original feature class and
        # an attribute selection on the original feature class to see which original features should
        # be deleted.
        # Then, delete the selected features (if at least 1 selected).

        # Basically, doing it piece by piece is a problem since I'm not including LRS KEY
        # selections to prevent the spatial selection from deleting pieces that overlap, but
        # that should have different LRS Keys. Need to do all of the features
        # at once to make sure that I'm not deleting pieces that should actually be there.
        # Seems like it shouldn't be a problem, but the numbers say it is.
        # 4.) For groups of 200000 LRS Keys, select all the features with those LRS Keys.
        if multiCounter <= 199999:
            multiSelectionQuery += """'""" + str(
                uniqueKeyItem) + """'""" + """, """
            multiCounter += 1
        else:
            # Add the current item, then
            multiSelectionQuery += """'""" + str(
                uniqueKeyItem) + """'""" + """, """
            # Remove the trailing ", " and add a closing parenthesis.
            multiSelectionQuery = multiSelectionQuery[:-2] + """) """
            SelectLayerByAttribute_management(fcAsFeatureLayerForTransferring,
                                              "NEW_SELECTION",
                                              multiSelectionQuery)
            # Have to do from step 5 on here also.

            ### -shouldbeafunctionblock#1- ###
            # 5.) Count selected features.
            countResult0 = GetCount_management(fcAsFeatureLayerForTransferring)
            intCount0 = int(countResult0.getOutput(0))
            if intCount0 >= 1:
                print(
                    "Spatially selecting with the fcAsFeatureLayerForTransferring features, of which there are "
                    + str(intCount0) + " selected.")
                ##print("Selected by this query:")
                ##print(str(multiSelectionQuery))
                # 9.) Else, spatially select features in the original feature class with 'SHARE_A_LINE_SEGMENT_WITH'.
                SelectLayerByLocation_management(
                    targetFC1asFeatureLayer, "SHARE_A_LINE_SEGMENT_WITH",
                    fcAsFeatureLayerForTransferring, 0, "NEW_SELECTION")
                # Added to prevent the Selection from taking over '%W%' routes at this time.
                SelectLayerByAttribute_management(targetFC1asFeatureLayer,
                                                  "SUBSET_SELECTION",
                                                  subsetSelectionQuery)

                # 10.) Count to make sure that at least one feature is selected.
                countResult2 = GetCount_management(targetFC1asFeatureLayer)
                intCount2 = int(countResult2.getOutput(0))
                print(
                    'There were ' + str(intCount2) +
                    ' features selected for replacement in the targetFC1asFeatureLayer layer.'
                )
                if intCount2 >= 1:
                    # 11.) If so, cursor the features out of the dissolve layer.
                    featureList = list()
                    searchCursorFields = [
                        str(lrsKeyToUse),
                        str(startMeasure),
                        str(endMeasure), 'LRS_COUNTY_PRE', 'LRS_ROUTE_PREFIX',
                        'LRS_ROUTE_NUM', 'LRS_ROUTE_SUFFIX',
                        'LRS_UNIQUE_IDENT', 'LRS_UNIQUE_IDENT1',
                        'KDOT_COUNTY_L', 'KDOT_COUNTY_R', 'LABEL', 'SHAPE@'
                    ]
                    newCursor = daSearchCursor(fcAsFeatureLayerForTransferring,
                                               searchCursorFields)

                    for cursorItem in newCursor:
                        featureList.append(list(cursorItem))

                    try:
                        del newCursor
                    except:
                        pass

                    # 12.) Delete the selected features in the input layer.
                    try:
                        DeleteFeatures_management(targetFC1asFeatureLayer)
                    except:
                        print("Could not delete features for the selection " +
                              str(multiSelectionQuery) + ".")
                    # 13.) Insert the features from the dissolve layer into the copy of the centerlines.
                    insertCursorFields = [
                        str(lrsKeyToUse),
                        str(startMeasure),
                        str(endMeasure), 'LRS_COUNTY_PRE', 'LRS_ROUTE_PREFIX',
                        'LRS_ROUTE_NUM', 'LRS_ROUTE_SUFFIX',
                        'LRS_UNIQUE_IDENT', 'LRS_UNIQUE_IDENT1',
                        'KDOT_COUNTY_L', 'KDOT_COUNTY_R', 'LABEL', 'SHAPE@'
                    ]
                    newCursor = daInsertCursor(targetFC1asFeatureLayer,
                                               insertCursorFields)

                    for featureItem in featureList:
                        newCursor.insertRow(featureItem)

                    try:
                        del newCursor
                    except:
                        pass
                    try:
                        del featureList
                    except:
                        pass

                else:
                    pass
            ### -shouldbeafunctionblock#1- ###
            multiSelectionQuery = ''' "''' + str(
                lrsKeyToUse) + '''" IS NOT NULL AND "''' + str(
                    lrsKeyToUse) + '''" IN ('''
            multiCounter = 0

    # After the for loop, if there is still anything remaining which was unselected in the
    # the previous multiSelectionQuery steps.
    # Remove the trailing ", " and add a closing parenthesis.
    if multiSelectionQuery != multiSelectionQueryBase:
        multiSelectionQuery = multiSelectionQuery[:-2] + """) """
    else:
        # The selection query would not select anything.
        return
    SelectLayerByAttribute_management(fcAsFeatureLayerForTransferring,
                                      "NEW_SELECTION", multiSelectionQuery)

    # Then redo from step 5 on at the end of the loop IF there is anything left to select
    # which was not selected... so if selectionCounter != 0.

    ### -shouldbeafunctionblock#2- ###
    # 5.) Count selected features.
    countResult0 = GetCount_management(fcAsFeatureLayerForTransferring)
    intCount0 = int(countResult0.getOutput(0))
    if intCount0 >= 1:
        print(
            "Spatially selecting with the fcAsFeatureLayerForTransferring features, of which there are "
            + str(intCount0) + " selected.")
        ##print("Selected by this query:")
        ##print(str(multiSelectionQuery))
        # 9.) Else, spatially select features in the original feature class with 'SHARE_A_LINE_SEGMENT_WITH'.
        SelectLayerByLocation_management(targetFC1asFeatureLayer,
                                         "SHARE_A_LINE_SEGMENT_WITH",
                                         fcAsFeatureLayerForTransferring, 0,
                                         "NEW_SELECTION")
        # Added to prevent the Selection from taking over '%W%' routes at this time.
        SelectLayerByAttribute_management(targetFC1asFeatureLayer,
                                          "SUBSET_SELECTION",
                                          subsetSelectionQuery)

        # 10.) Count to make sure that at least one feature is selected.
        countResult2 = GetCount_management(targetFC1asFeatureLayer)
        intCount2 = int(countResult2.getOutput(0))
        print(
            'There were ' + str(intCount2) +
            ' features selected for replacement in the targetFC1asFeatureLayer layer.'
        )
        if intCount2 >= 1:
            # 11.) If so, cursor the features out of the dissolve layer.
            featureList = list()
            searchCursorFields = [
                str(lrsKeyToUse),
                str(startMeasure),
                str(endMeasure), 'LRS_COUNTY_PRE', 'LRS_ROUTE_PREFIX',
                'LRS_ROUTE_NUM', 'LRS_ROUTE_SUFFIX', 'LRS_UNIQUE_IDENT',
                'LRS_UNIQUE_IDENT1', 'KDOT_COUNTY_L', 'KDOT_COUNTY_R', 'LABEL',
                'SHAPE@'
            ]
            newCursor = daSearchCursor(fcAsFeatureLayerForTransferring,
                                       searchCursorFields)

            for cursorItem in newCursor:
                featureList.append(list(cursorItem))

            try:
                del newCursor
            except:
                pass

            # 12.) Delete the selected features in the input layer.
            try:
                DeleteFeatures_management(targetFC1asFeatureLayer)
            except:
                print("Could not delete features for the selection " +
                      str(multiSelectionQuery) + ".")
            # 13.) Insert the features from the dissolve layer into the copy of the centerlines.
            insertCursorFields = [
                str(lrsKeyToUse),
                str(startMeasure),
                str(endMeasure), 'LRS_COUNTY_PRE', 'LRS_ROUTE_PREFIX',
                'LRS_ROUTE_NUM', 'LRS_ROUTE_SUFFIX', 'LRS_UNIQUE_IDENT',
                'LRS_UNIQUE_IDENT1', 'KDOT_COUNTY_L', 'KDOT_COUNTY_R', 'LABEL',
                'SHAPE@'
            ]
            newCursor = daInsertCursor(targetFC1asFeatureLayer,
                                       insertCursorFields)

            for featureItem in featureList:
                newCursor.insertRow(featureItem)

            try:
                del newCursor
            except:
                pass
            try:
                del featureList
            except:
                pass

        else:
            pass