Example #1
0
def Custom_Erase(inFeature1, inFeature2, outFeature):
    # Instead of erase, might try a union, then selection for only the features
    # that do not have their centers within the 2nd feature class,
    # or that are not entirely within the 2nd feature class,
    # then output the selected features.
    # MakeFeatureLayer, Union, SelectByLocation, CopyFeatures.
    tempUnionFeatureClass = r'in_memory\UnionTemp'
    unionList = list()
    unionList.append(inFeature1)
    unionList.append(inFeature2)

    Union_analysis(unionList, tempUnionFeatureClass, "ALL")

    tempUnionLayer = MakeFeatureLayer_management(tempUnionFeatureClass,
                                                 "UnionLayer")
    tempFeature2 = MakeFeatureLayer_management(inFeature2, "Feature2")

    SelectLayerByLocation_management(tempUnionLayer, "HAVE_THEIR_CENTER_IN",
                                     tempFeature2)
    SelectLayerByLocation_management(tempUnionLayer, "WITHIN", tempFeature2,
                                     "0 Feet", "ADD_TO_SELECTION")
    CopyFeatures_management(
        tempUnionLayer,
        r'\\gisdata\ArcGIS\GISdata\GDB\CCL_Scratch_Boundary.gdb\TempUnionSelection'
    )
    SelectLayerByAttribute_management(tempUnionLayer, "SWITCH_SELECTION")
    CopyFeatures_management(
        tempUnionLayer,
        r'\\gisdata\ArcGIS\GISdata\GDB\CCL_Scratch_Boundary.gdb\TempUnionSelectionSwitch'
    )
    CopyFeatures_management(tempUnionLayer, outFeature)
Example #2
0
def preparingSourceCountyData():
    print("Starting the preparingSourceCountyData function!")

    if Exists(preRouteSourceCRML):
        try:
            Delete_management(preRouteSourceCRML)
        except:
            print("Could not delete the features located at: " +
                  str(preRouteSourceCRML) + ".")
    else:
        pass

    # Make a copy
    CopyFeatures_management(routesSourceCountyLRSArnold, preRouteSourceCRML)

    # Remove unnecessary fields
    preRouteSourceCRMLDescription = Describe(preRouteSourceCRML)
    preRouteSourceCRMLOIDFieldName = preRouteSourceCRMLDescription.OIDFieldName
    preRouteSourceCRMLShapeFieldName = preRouteSourceCRMLDescription.shapeFieldName
    preRouteSourceCRMLShapeAndOIDFieldNames = [
        preRouteSourceCRMLOIDFieldName, preRouteSourceCRMLShapeFieldName
    ]
    preRouteSourceCRMLFieldObjectsList = ListFields(preRouteSourceCRML)
    preRouteSourceFieldNames = [
        x.name for x in preRouteSourceCRMLFieldObjectsList
    ]
    fieldNamesToKeep = [
        y for y in preRouteSourceFieldNames if y in preRouteSourceCRMLFields
        or y in preRouteSourceCRMLShapeAndOIDFieldNames
    ]

    fieldNamesToRemove = [
        z for z in preRouteSourceFieldNames if z not in fieldNamesToKeep
    ]

    for fieldNameItem in fieldNamesToRemove:
        DeleteField_management(preRouteSourceCRML, fieldNameItem)

    print("Done deleting unnecessary fields.")

    MakeFeatureLayer_management(preRouteSourceCRML, fcAsFeatureLayerLG)
    selectionQueryL1 = """ SourceRouteId IS NULL OR LRS_ROUTE_PREFIX IN ('I', 'U', 'K') """
    SelectLayerByAttribute(fcAsFeatureLayerLG, NEW_SELECTION_CONST,
                           selectionQueryL1)
    CopyFeatures_management(fcAsFeatureLayerLG, stateRoutesAndNullRouteIDs)
    DeleteRows_management(fcAsFeatureLayerLG)
    selectionQueryL2 = """ SourceFromMeasure IS NULL OR SourceToMeasure IS NULL """
    SelectLayerByAttribute(fcAsFeatureLayerLG, NEW_SELECTION_CONST,
                           selectionQueryL2)
    CopyFeatures_management(fcAsFeatureLayerLG, preRouteSourceNoMeasures)
    selectionQueryL3 = """ SourceFromMeasure IS NULL """
    SelectLayerByAttribute(fcAsFeatureLayerLG, NEW_SELECTION_CONST,
                           selectionQueryL3)
    CalculateField_management(fcAsFeatureLayerLG, "SourceFromMeasure", "0",
                              PYTHON_9_3_CONST)
    selectionQueryL4 = """ SourceToMeasure IS NULL """
    SelectLayerByAttribute(fcAsFeatureLayerLG, NEW_SELECTION_CONST,
                           selectionQueryL4)
    CalculateField_management(fcAsFeatureLayerLG, "SourceToMeasure",
                              "!SHAPE.LENGTH@MILES!", PYTHON_9_3_CONST)
def routesSourceCreation():
    env.workspace = returnGDBOrSDEPath(routesSourceCenterlines)
    env.overwriteOutput = 1
    
    # Checking to see if the output already exists.
    # If so, remove it.
    if Exists(routesSourceCenterlines):
        Delete_management(routesSourceCenterlines)
    else:
        pass
    # Create a new file for the output.
    print("Making a copy of " + returnFeatureClass(inputCenterlines) + " called " + returnFeatureClass(routesSourceCenterlines) + ".")
    CopyFeatures_management(inputCenterlines, routesSourceCenterlines)
    
    print("Adding fields to " + returnFeatureClass(routesSourceCenterlines) + ".")
    #Addfields:
    # SourceRouteId (Text, 50)
    AddField_management(routesSourceCenterlines, "SourceRouteId", "TEXT", "", "", 50, "SourceRouteId", nullable)
    # SourceFromMeasure (Double)
    AddField_management(routesSourceCenterlines, "SourceFromMeasure", "DOUBLE", "", "", "", "SourceFromMeasure", nullable)
    # SourceToMeasure (Double)
    AddField_management(routesSourceCenterlines, "SourceToMeasure", "DOUBLE", "", "", "", "SourceToMeasure", nullable)
    
    if useNewFieldLogic == True:
        KDOTKeyCalculation_NewFieldLogic()
    else:
        TranscendFieldCalculation()
    
    TranscendRampReplacement()
    
    if useNewFieldLogic == True:
        KDOTKeyCalculation_NewFieldLogic()
    else:
        TranscendFieldCalculation()
    LocalRouteReduction()
def moveLocalErrorsToSQL(prefixKeyName):
    print("Moving errors from the Local gdb to SQL for the prefix key name of: " + str(prefixKeyName) + ".")
    for errorItemFC in prefixesToMoveErrorsFor:
        errorItemFCBaseName = returnFeatureClass(errorItemFC)
        sqlPath = returnGDBOrSDEPath(dailyProcessSDESourceCenterlinesLocation)
        errorItemCopyName = prefixKeyName + '_' + errorItemFCBaseName
        errorItemSQLLocation = os.path.join(sqlPath, errorItemCopyName)
        lowerstrErrorItemFCBaseName = str(errorItemFCBaseName).lower()
        if lowerstrErrorItemFCBaseName.find('selfintclassification') >= 0:
            # Already includes the prefix name in the basename, so just use the full BaseName for the class.
            errorItemSQLLocation = os.path.join(sqlPath, errorItemFCBaseName)
        else:
            pass
        if Exists(errorItemSQLLocation):
            try:
                Delete_management(errorItemSQLLocation)
            except:
                print("Could not delete the FC at: " + str(errorItemSQLLocation) + ".")
                print("Please make sure that the FC does not have any locks on it and try again.")
        try:
            CopyFeatures_management(errorItemFC, errorItemSQLLocation)
        except:
            print("Could not copy from the FC at: " + str(errorItemFC))
            print("to the FC at: " + str(errorItemSQLLocation) + ".")
            print("Please make sure that the FC to copy from exists")
            print("and that the FC to copy to is not locked.")
def nonStateAndCountyImport():

    # Copy the county polygons and the
    # non_state_system from Oracle.
    env.workspace = inMemGDB

    Delete_management(inMemGDB)

    print "Importing the Non_State_System..."
    nonStateSystemToCopy = sharedNonStateSystem
    nonStateSystemOutput = nSSNoZ
    CopyFeatures_management(nonStateSystemToCopy, nonStateSystemOutput)

    print "Importing the Counties..."
    countyPolygonsToCopy = sharedCounties  # Changed to sdeprod
    countyPolygonsOutput = countiesNoZ
    CopyFeatures_management(countyPolygonsToCopy, countyPolygonsOutput)
def archive_GDB_FC(fc, outdir):
    """
    Copies an input FC from a geodatabase into a temp folder in shapefile format.
    Creates a zip file in the outdir, and copies the shapefile files into that
    zip archive. Deletes the temp folder after archiving.

    Requires: fc -- the feature class in a GDB to archive as a zip
              outdir -- the output location of the zip file

    Returns:  zippath -- the path to the created zip archive
    """

    import zipfile
    import glob
    import errno

    from datetime import datetime
    from arcpy import CopyFeatures_management
    from tempfile import mkdtemp
    from shutil import rmtree

    fc_name = os.path.basename(fc)
    today = datetime.today()

    tempfolder = mkdtemp()

    CopyFeatures_management(fc, os.path.join(tempfolder, fc_name))

    filelist = glob.glob(os.path.join(tempfolder, fc_name + ".*"))

    # the path to the output zipfile is ARCHIVE_WS/YYYY/MM/DD/fc_name.zip
    zippath = os.path.join(
        settings.ARCHIVE_WORKSPACE,
        today.strftime(
            "%Y{0}%m{0}%d{0}%Y-%m-%d_{1}.zip".format(os.path.sep, fc_name)
        )
    )

    # if full directory path does not exist we need to make it
    # so we try and ignore the error if it is already there
    try:
        os.makedirs(os.path.dirname(zippath))
    except OSError as e:
        if e.errno != errno.EEXIST:
            raise e

    with zipfile.ZipFile(zippath, mode='w', compression=zipfile.ZIP_DEFLATED) as zfile:
        for f in filelist:
            if not f.upper().endswith('.LOCK'):
                newfile = today.strftime(
                    "%Y-%m-%d_{}".format(os.path.basename(f))
                )
                zfile.write(f, newfile)

    rmtree(tempfolder)

    return zippath
Example #7
0
def copyFCToTempLocation(inputFC, outputFC):
    if Exists(outputFC):
        try:
            Delete_management(outputFC)
        except:
            print("Could not delete the temp FC at: " + str(outputFC) + ".")
    else:
        pass
    try:
        CopyFeatures_management(inputFC, outputFC)
    except:
        print("Could not copy the feature class at: " + str(inputFC) +
              " to the output location at: " + str(outputFC) + ".")
    def restrictDomain(self, object, operation):
        """
        Restricts current instance's domain based on object's domain
        @param object: extent to which the object is restricted
        @param operation: valid options: "inside", "outside"
        """

        name = "restDom_" + str(self.sObj)
        outputLocation = "in_memory\\" + name

        if operation == 'inside':
            # select by location
            select = SelectLayerByLocation_management(self.filepath,
                                                      "INTERSECT",
                                                      object.filepath)
            CopyFeatures_management(select, outputLocation)
            restDom = utils.makeObject(outputLocation)

        elif operation == 'outside':
            # select by location
            sel = SelectLayerByLocation_management(self.filepath, "INTERSECT",
                                                   object.filepath)
            select = SelectLayerByLocation_management(sel, "INTERSECT",
                                                      object.filepath, "",
                                                      "SWITCH_SELECTION")
            CopyFeatures_management(select, outputLocation)
            restDom = utils.makeObject(outputLocation)

        else:
            raise NotImplementedError(operation)

        # update cc instance's attributes
        desc = Describe(outputLocation)
        restDom.domain = desc.extent
        restDom.filepath = outputLocation
        restDom.filename = os.path.basename(outputLocation)

        return restDom
Example #9
0
def Create_CCL_Calibration_Points():
    # Intersect GIS.City_Limits with SMLRS to obtain points layer
    # write to file geodatabase.
    MakeFeatureLayer_management(stateroutelyr, "smlrs_d")
    MakeFeatureLayer_management(citylimits, "citylimits_d",
                                "TYPE IN ( 'CS', 'ON')")
    intersectFeaures = ["smlrs_d", "citylimits_d"]
    print "Intersecting State Routes and City Limits"
    Intersect_analysis(intersectFeaures,
                       r"D:\workspaces\pythontests.gdb\cal_points_multi",
                       "NO_FID", "", "point")

    # Split the multipoint features into single points and place in another layer.
    print "Splitting multipart points into single points."
    MultipartToSinglepart_management(
        r"D:\workspaces\pythontests.gdb\cal_points_multi",
        r"D:\workspaces\pythontests.gdb\cal_points_simple")

    # Clean the simple points layer by removing extraneous fields.

    # Locate the created points layer along the SMLRS routes to
    # generate a table with measurements.
    print "Locating the edge of city boundary points along the state system."
    reloc_properties = "point_LRS POINT point_Loc"

    #fieldList = ListFields("smlrs_d")
    #for field in fieldList:
    #print str(field.name)

    LocateFeaturesAlongRoutes_lr(
        r"D:\workspaces\pythontests.gdb\cal_points_simple", "smlrs_d",
        "LRS_ROUTE", "10 Feet",
        r"D:\workspaces\pythontests.gdb\cal_points_reloc", reloc_properties,
        "FIRST", "NO_DISTANCE", "NO_ZERO", "NO_FIELDS")

    point_Properties = "point_LRS POINT point_Loc"
    MakeRouteEventLayer_lr("smlrs_d", "LRS_ROUTE",
                           r"D:\workspaces\pythontests.gdb\cal_points_reloc",
                           point_Properties, "new_point_locations")

    CopyFeatures_management(
        "new_point_locations",
        r"D:\workspaces\pythontests.gdb\CCL_Point_Calibrators")

    # Use this set of points as the calibration points for the
    # CCL_LRS_ROUTE layer's calibration.

    # Add the measure values to the points layer so that it can be
    # used to calibrate the measures of the CCL_LRS routes.
    print "Calibration Points created."
def save_FC(fc, outdir):
    """
    Copies an input FC from a geodatabase into a specified folder in shapefile format.
    Saves an input FC into a specified folder (outdir)

    Requires: fc -- the feature class to save
              outdir -- the output location for the feature class

    """
    from arcpy import CopyFeatures_management

    fc_name = os.path.basename(fc)

    CopyFeatures_management(fc, os.path.join(outdir, fc_name))

    return os.path.join(outdir, fc_name)
Example #11
0
def replace_wfs_data(newdata, target_workspace):
    """
    Copy the new FC into the target workspace.

    Requires: newdata -- the FC to be copied
              target_workspace -- the location into which the data will be copied

    Returns:  None
    """
    from arcpy import CopyFeatures_management
    from arcpy import env
    env.overwriteOutput = True
    CopyFeatures_management(
        newdata,
        os.path.join(target_workspace,
                     os.path.splitext(os.path.basename(newdata))[0]))
def join_to_copy(in_data, out_data, join_table, in_field, join_field):
    """given an input feature, make a copy, then execute a join on that copy.
    Return the copy.
    """
    msg(in_data)
    msg(out_data)
    msg(join_table)
    msg(in_field)
    msg(join_field)
    # copy the inlets file
    CopyFeatures_management(in_features=in_data, out_feature_class=out_data)
    # join the table to the copied file
    JoinField_management(in_data=out_data,
                         in_field=in_field,
                         join_table=join_table,
                         join_field=join_field)
    return out_data
def main():
    continueFlag = True
    if Exists(oneTimeProcessOutputSQLFeaturesLocation):
        print(
            "Are you absolutely SURE that you wish to overwrite the data at: "
            + str(oneTimeProcessOutputSQLFeaturesLocation))
        print("With the output from the initialonetimeprocess script?")
        print("(y/n)")
        userInput = rawInput('> ')
        if userInput.lower() == 'y':
            pass
        else:
            continueFlag = False
    else:
        print("There was nothing to overwrite at: " +
              str(oneTimeProcessOutputSQLFeaturesLocation) +
              "\nProceeding happily.")

    if continueFlag == True:
        # Go ahead and replace the data that existed (if any) with the output from the initialonetimeprocess.
        try:
            Delete_management(oneTimeProcessOutputSQLFeaturesLocation)
        except:
            print("Could not delete the feature class at: " +
                  str(oneTimeProcessOutputSQLFeaturesLocation) + ".")
            print("Please clear any locks and try again.")
        try:
            CopyFeatures_management(
                postInitialProcessRoadCenterlineOutputLocation,
                oneTimeProcessOutputSQLFeaturesLocation)
        except:
            print("Could not copy the feature class at: " +
                  str(postInitialProcessRoadCenterlineOutputLocation) +
                  "\nTo " + str(oneTimeProcessOutputSQLFeaturesLocation) + ".")
            print("Please make sure that: " +
                  str(postInitialProcessRoadCenterlineOutputLocation) +
                  " exists\nand that " +
                  str(oneTimeProcessOutputSQLFeaturesLocation) +
                  " does not yet exist.")

    else:
        print("Will not overwrite the data at: " +
              str(oneTimeProcessOutputSQLFeaturesLocation) + ".")
        return
    def addProperty(self, in_raster):
        """
        get value of a field and write it to a column named RASTERVALU in the object
        @param in_raster: raster where the value is taken from
        """

        desc = Describe(self.filepath)
        name = "addProperty" + str(self.sObj)
        outputLocation = "in_memory\\" + name

        if desc.shapeType == "Point":
            ExtractValuesToPoints(self.filepath, in_raster.filepath,
                                  outputLocation)
            addProperty = utils.makeObject(outputLocation)

        elif desc.shapeType == "Line":
            raise NotImplementedError(desc.shapeType)

        elif desc.shapeType == "Polygon":
            polyToPoint = "in_memory\\polyToPoint_" + str(self.sObj)
            FeatureToPoint_management(self.filepath, polyToPoint, "CENTROID")
            valueToPoint = "in_memory\\valueToPoint_" + str(self.sObj)
            ExtractValuesToPoints(polyToPoint, in_raster.filepath,
                                  valueToPoint)
            CopyFeatures_management(self.filepath, outputLocation)
            JoinField_management(outputLocation, "FID", valueToPoint, "FID",
                                 "RASTERVALU")
            addProperty = utils.makeObject(outputLocation)
            Delete_management(polyToPoint)
            Delete_management(valueToPoint)
            #TODO implement method that the parameters "CENTROID" or "INSIDE" for FeatureToPoint_management() can be selected

        else:
            raise NotImplementedError("unknown shapeType:", desc.shapeType)

        # update cc instance's attributes
        desc = Describe(outputLocation)
        addProperty.domain = desc.extent
        addProperty.filepath = outputLocation
        addProperty.filename = os.path.basename(outputLocation)

        return addProperty
Example #15
0
def archive_GDB_FC(fc, outdir):
    """
    Copies an input FC from a geodatabase into a temp folder in shapefile format.
    Creates a zip file in the outdir, and copies the shapefile files into that
    zip archive. Deletes the temp folder after archiving.

    Requires: fc -- the feature class in a GDB to archive as a zip
              outdir -- the output location of the zip file

    Returns:  zippath -- the path to the created zip archive
    """

    import zipfile
    import glob
    from datetime import datetime
    from arcpy import CopyFeatures_management
    from tempfile import mkdtemp
    from shutil import rmtree

    fc_name = os.path.basename(fc)
    today = "_" + datetime.today().strftime("%m-%d-%Y")

    tempfolder = mkdtemp()

    CopyFeatures_management(fc, tempfolder)

    filelist = glob.glob(os.path.join(tempfolder, fc_name + ".*"))

    zippath = os.path.join(ARCHIVE_WORKSPACE, fc_name + today + ".zip")

    with zipfile.ZipFile(zippath, mode='w',
                         compression=zipfile.ZIP_DEFLATED) as zfile:
        for f in filelist:
            if not f.upper().endswith('.LOCK'):
                newfile = os.path.splitext(
                    os.path.basename(f))[0] + today + os.path.splitext(f)[1]
                zfile.write(f, newfile)

    rmtree(tempfolder)

    return zippath
def main():
    if Exists(oneTimeProcessInputFeaturesLocation):
        try:
            Delete_management(oneTimeProcessInputFeaturesLocation)
        except:
            print("Could not delete the feature class at: " +
                  str(oneTimeProcessInputFeaturesLocation) + ".")
            print("Please clear any locks and try again.")
    else:
        pass
    try:
        CopyFeatures_management(initialGeoCommConflationDataLocation,
                                oneTimeProcessInputFeaturesLocation)
    except:
        print("Could not copy the feature class at: " +
              str(initialGeoCommConflationDataLocation) + "\nTo " +
              str(oneTimeProcessInputFeaturesLocation) + ".")
        print("Please make sure that: " +
              str(initialGeoCommConflationDataLocation) +
              " exists\nand that " + str(oneTimeProcessInputFeaturesLocation) +
              " does not yet exist.")
    def withProperty(self, sql):
        """
        :param sql: sql expression
        :returns: feature that meets the properties of the sql expression
        """

        name = "wProp_" + str(self.sObj)
        outputLocation = "in_memory\\" + name

        selByAtt = SelectLayerByAttribute_management(self.filepath,
                                                     "NEW_SELECTION", sql)
        CopyFeatures_management(selByAtt, outputLocation)
        wProp = utils.makeObject(outputLocation)

        # update cc instance's attributes
        desc = Describe(outputLocation)
        wProp.domain = desc.extent
        wProp.filepath = outputLocation
        wProp.filename = os.path.basename(outputLocation)

        return wProp
def main():
    print("Starting to dissolve the routes source.")
    stateSystemSelectedFeatures = 'StateSystem_Features'
    selectQuery1 = '''LRS_ROUTE_PREFIX in ('I', 'U', 'K')'''
    MakeFeatureLayer_management (routesSourceCenterlines, stateSystemSelectedFeatures, selectQuery1)
    CopyFeatures_management(stateSystemSelectedFeatures, routesSourcePreDissolveOutput)
    
    #GetCount on the features in the layer here.
    countResult = GetCount_management(stateSystemSelectedFeatures)
    intCount = int(countResult.getOutput(0))
    print('Found ' + str(intCount) + ' state system features to be dissolved.')
    
    # Removed STATE_FLIP_FLAG because we've already flipped the data prior to this process.
    dissolveFields = "KDOT_DIRECTION_CALC;KDOT_LRS_KEY;LRS_COUNTY_PRE;LRS_ROUTE_PREFIX;LRS_ROUTE_SUFFIX;LRS_UNIQUE_IDENT"
    statisticsFields = "BEG_NODE MIN;BEG_NODE MAX;END_NODE MAX;END_NODE MIN;COUNTY_BEGIN_MP MIN;COUNTY_END_MP MAX"
    multipart = "SINGLE_PART"
    unsplitLines = "DISSOLVE_LINES"
    ## Use a selection for the state system so that it will work the first time.
    ## Then, later expand the selection and the amount of routes that are attempted for
    ## the dissolve.
    Dissolve_management(stateSystemSelectedFeatures, routesSourceDissolveOutput, dissolveFields, statisticsFields, multipart, unsplitLines)
    print("Completed dissolving the routes source.")
def main():
    print(
        "Starting the process of copying centerlines from the server to run daily tests."
    )
    if Exists(inputCenterlines):
        try:
            Delete_management(inputCenterlines)
        except:
            print("Could not delete the feature class at: " +
                  str(inputCenterlines) + ".")
            print("Please clear any locks and try again.")
    else:
        pass
    try:
        CopyFeatures_management(dailyProcessSDESourceCenterlinesLocation,
                                inputCenterlines)
    except:
        print("Could not copy the feature class at: " +
              str(dailyProcessSDESourceCenterlinesLocation) + "\nTo " +
              str(inputCenterlines) + ".")
        print("Please make sure that: " +
              str(dailyProcessSDESourceCenterlinesLocation) +
              " exists\nand that " + str(inputCenterlines) +
              " does not yet exist.")
Example #20
0
    v2_sectors = [initial_sector.intersection(x) for x in v2_sectors]
    v1_sectors = [x for x in v1_sectors if not x.is_empty]
    v2_sectors = [x for x in v2_sectors if not x.is_empty]
    v1_sectors = [x for x in v1_sectors if x.type == 'Polygon']
    v2_sectors = [x for x in v2_sectors if x.type == 'Polygon']
    union_sectors = []
    if len(v1_sectors) != 0:
        writeShp(v1_sectors, 'v1_sectors.shp')
        union_sectors.append('v1_sectors.shp')
    if len(v2_sectors) != 0:
        writeShp(v2_sectors, 'v2_sectors.shp')
        union_sectors.append('v2_sectors.shp')
    if len(v1_sectors) == 0:
        if len(v2_sectors) == 0:
            writeShp(dealt_obs, 'dealtobs.shp')
            CopyFeatures_management('cover_shp.shp', 'cover_1_shp.shp')
            Erase_analysis('cover_1_shp.shp', 'dealtobs.shp', 'cover_shp.shp')
            print 'end of loop, no sectors'
            #raw_input()
        else:
            Union_analysis(union_sectors, 'sectors.shp')

            writeShp(dealt_obs, 'dealtobs.shp')

            Union_analysis(['sectors.shp', 'other_sector.shp'], 'union_2.shp')
            Dissolve_management('union_2.shp', 'union_2_dissol.shp')
            Erase_analysis('union_2_dissol.shp', 'dealtobs.shp',
                           'cover_shp.shp')
            print "end of loop"

            #raw_input()
    dictKey_SourceGDB = gdbBasePart1 + '_' + gdbBasePart2 + '_' + dictKey + '_' + gdbForSourceNamePart + '.gdb'
    CreateFileGDB_management(mainFolder, dictKey_SourceGDB)
    # and create a new gdb in the same folder (2nd dictKey gdb) called gdbBasePart1 + '_' + gdbBasePart2 + '_' +  dictKey + '.gdb'
    dictKey_GDB = gdbBasePart1 + '_' + gdbBasePart2 + '_' + dictKey + '.gdb'
    CreateFileGDB_management(mainFolder, dictKey_GDB)
    # Then, load a feature layer of the RoutesSource from the gdbForSourceCreation so that you can do a selection on it
    MakeFeatureLayer_management(routesSource2, routesSource2FeatureLayer)
    # Use the value associated with the dict key as the selection where clause for the routesSourceFeatureLayer
    dictWhereClause = advancedErrorReportingDict[dictKey]
    SelectLayerByAttribute_management(routesSource2FeatureLayer,
                                      "CLEAR_SELECTION")
    SelectLayerByAttribute_management(routesSource2FeatureLayer,
                                      "NEW_SELECTION", dictWhereClause)
    # Copy the selected features from the feature layer to the dictKey_SourceGDB.
    dictKeyRoutesSource = os.path.join(dictKey_SourceGDB, routesSourceName)
    CopyFeatures_management(routesSource2FeatureLayer, dictKeyRoutesSource)

    try:
        del routesSource2FeatureLayer
    except:
        pass

    # Also copy the other feature classes from the fullRoadSet_SourceGDB besides All_Road_Centerlines to the first dictKey gdb.
    # Copy the CalPts and Routes FCs from the fullRoadSet_GDB to the second dictKey gdb.
    # # Consider renaming the Non_Source gdb to something like gdbBaseName + _RtsCalPts.gdb
    for additionalFCNameToCopy in otherFCsToCopyList:  # Loop inside a loop, not great, but the correct process at this time.
        # Copy the additional needed FCs for the routes testing... are there any FCs needed for that?
        # Have to copy the RoutesSourceCountyLRS_ARNOLD as RoutesSource iirc due to the way that the script runs when it recreates
        # the Routes and CalPts.
        fullFCPathToCopyFrom = os.path.join(gdbForSourceCreation,
                                            additionalFCNameToCopy)
 def save(self, Output_Folder, Output_Name, extension):
     outputLocation = Output_Folder + "\\" + Output_Name + extension
     CopyFeatures_management(self.filepath, outputLocation)
def createShortGradiculeLinesForEachCounty():
    # Get/use the same projection as the one used for the county roads.
    spatialReferenceProjection = Describe(
        sharedNonStateSystem).spatialReference

    env.workspace = sqlGdbLocation

    inputCountyGradicule = countyCountyGradicule
    bufferedCounties = 'bufferedCounties'
    countiesToCopy = 'countiesToCopy'
    gradiculeToCopy = 'gradiculeToCopy'
    loadedGradiculeCopy = 'loadedGradiculeCopy'
    loadedTempGradicule = 'loadedTempGradicule'
    #unBufferedCounties = 'unBufferedCounties'
    # Using the miniBuffered process changes it from
    # 1457 total output features to 1481 (at 2.1k)
    # total output features.
    miniBufferedCounties = 'miniBufferedCounties'
    loadedOutputGradicule = 'loadedOutputGradicule'
    tempCounties = r'in_memory\tempCounties'
    tempCountyGradicule = r'in_memory\tempCountyGradicule'
    tempCountyGradiculePostErase = r'in_memory\tempCountyGradiculePostErase'
    tempCountyGradiculeSinglePart = r'in_memory\tempCountyGradiculeSinglePart'
    bufferCursorFields = ["OBJECTID", "COUNTY_NAME"]

    MakeFeatureLayer_management(sharedCounties, countiesToCopy)

    MakeFeatureLayer_management(countyCountyGradicule, gradiculeToCopy)
    CopyFeatures_management(gradiculeToCopy, countyGradiculeCopied)
    MakeFeatureLayer_management(countyGradiculeCopied, loadedGradiculeCopy)

    # Might be worth dissolving based on COORD & County_Name prior
    # to removing the County_Name field, if that's a possibility.

    # Or better yet, just make it so that the Gradicule lines for
    # a particular county are eligible for intersecting and
    # erasing with that same county's polygon's.  All we're
    # trying to do here is make it so that the county's original
    # gradicule lines are about half of their original size.
    # Don't need to find out which gradicule lines are close to
    # the county or anything else like that. Just need to reduce
    # the size of the lines and keep the parts that are nearest
    # the county that they go with.

    # Remove the County_Name field so that the intersect can add it
    # back and populate it only where the county buffer actually
    # intersects the lines.
    #DeleteField_management(countyGradiculeCopied, "County_Name")

    # Elaine requested that this be 1000 Feet shorter.
    # I made it 2000 feet shorter, because it still seemed too big.
    Buffer_analysis(sharedCounties, countiesBuffered, "8000 Feet")
    Buffer_analysis(sharedCounties, countiesMiniBuffered, "1500 Feet")

    bufferedCountyPolygonList = list()
    outputFeatureList = list()

    # 1st SearchCursor
    newCursor = daSearchCursor(countiesBuffered, bufferCursorFields)
    for newRow in newCursor:
        bufferedCountyPolygonList.append(list(newRow))

    if 'newCursor' in locals():
        del newCursor
    else:
        pass

    MakeFeatureLayer_management(countiesBuffered, bufferedCounties)
    MakeFeatureLayer_management(countiesMiniBuffered, miniBufferedCounties)

    loadedCountiesFields = ListFields(bufferedCounties)

    for loadedCountiesField in loadedCountiesFields:
        print "A loadedCountiesField was found: " + str(
            loadedCountiesField.name)

    countyGradiculeFields = ListFields(loadedGradiculeCopy)

    for countyGradiculeField in countyGradiculeFields:
        print "A countyGradiculeField was found: " + str(
            countyGradiculeField.name)

    for listedRow in bufferedCountyPolygonList:
        print str(listedRow)
        selectCounty = listedRow[1]

        whereClause = """ "COUNTY_NAME" = '""" + str(selectCounty) + """' """
        print "The whereClause is " + str(whereClause)
        SelectLayerByAttribute_management(bufferedCounties, "NEW_SELECTION",
                                          whereClause)

        SelectLayerByAttribute_management(loadedGradiculeCopy, "NEW_SELECTION",
                                          whereClause)

        Intersect_analysis([loadedGradiculeCopy, bufferedCounties],
                           tempCountyGradicule, "ALL")

        MultipartToSinglepart_management(tempCountyGradicule,
                                         tempCountyGradiculeSinglePart)

        # Selects the same county as the other Select, but does it from the miniBufferedCounties
        # so that the lines which lay inside of the county and running just along its edges
        # are erased, as they should only exist as gradicules for the counties adjoining this
        # one, but not for this one itself.
        SelectLayerByAttribute_management(miniBufferedCounties,
                                          "NEW_SELECTION", whereClause)

        MakeFeatureLayer_management(tempCountyGradiculeSinglePart,
                                    loadedTempGradicule)

        SelectLayerByAttribute_management(loadedTempGradicule, "NEW_SELECTION",
                                          whereClause)

        secVerGradiculeFields = ListFields(loadedTempGradicule)

        #for secVerGradiculeField in secVerGradiculeFields:
        #    print "A secVerGradiculeField was found: " + str(secVerGradiculeField.name)

        Erase_analysis(loadedTempGradicule, miniBufferedCounties,
                       tempCountyGradiculePostErase, xyToleranceVal)

        fieldsToCopy = [
            "SHAPE@", "County_Number", "County_Name", "DIRECTION", "COORD"
        ]

        # 2nd SearchCursor
        newCursor = daSearchCursor(tempCountyGradiculePostErase, fieldsToCopy)
        for newRow in newCursor:
            outputFeatureList.append(newRow)

        if 'newCursor' in locals():
            del newCursor
        else:
            pass

    try:
        Delete_management(countyGradiculeShortWithUser)
    except:
        pass

    CreateFeatureclass_management(sqlGdbLocation, countyGradiculeShortNoPath,
                                  "POLYLINE", "", "", "",
                                  spatialReferenceProjection)

    AddField_management(countyGradiculeShortNoPath, "County_Number", "DOUBLE",
                        "", "", "")

    AddField_management(countyGradiculeShortNoPath, "County_Name", "TEXT", "",
                        "", "55")

    AddField_management(countyGradiculeShortNoPath, "DIRECTION", "TEXT", "",
                        "", "5")

    AddField_management(countyGradiculeShortNoPath, "COORD", "TEXT", "", "",
                        "30")

    print "First Intersected County Gradicule Row: " + str(
        outputFeatureList[0])

    newCursor = daInsertCursor(countyGradiculeShortPath, fieldsToCopy)
    counter = 1
    for outputFeature in outputFeatureList:
        rowToInsert = ([outputFeature])

        insertedOID = newCursor.insertRow(outputFeature)

        counter += 1

        print "Inserted Row with Object ID of " + str(insertedOID)

    # Load the feature class. Remove anything shorter than 850 feet.
    MakeFeatureLayer_management(countyGradiculeShortPath,
                                loadedOutputGradicule)

    # Select the rows that have geometry which is shorter than 850 feet.
    ## Note that Shape.STLength() returns units in the projection
    ## or coordinate system that it the feature class is stored in.
    whereClause = """ Shape.STLength() <  850 """
    print "The whereClause is " + str(whereClause)
    SelectLayerByAttribute_management(loadedOutputGradicule, "NEW_SELECTION",
                                      whereClause)

    # If there is at least one row selected, delete each selected row.
    if int(GetCount_management(loadedOutputGradicule).getOutput(0)) > 0:
        print str(GetCount_management(loadedOutputGradicule).getOutput(
            0)) + "rows selected."
        DeleteRows_management(loadedOutputGradicule)
    else:
        print "No rows were selected to delete."

    if 'newCursor' in locals():
        del newCursor
    else:
        pass
                                                     area)

# select buildings within area
building_inArea = SelectLayerByLocation_management(building, 'INTERSECT', area)

# elevation of waterPoints
waterPoint_elev = ExtractValuesToPoints(waterPoint_inArea, dem,
                                        'in_memory/wp_elev')

# calculate elevation of buildings (using centroid)
building_point = FeatureToPoint_management(building_inArea,
                                           'in_memory/building_point',
                                           'CENTROID')
building_pt_elev = ExtractValuesToPoints(building_point, dem,
                                         'in_memory/building_pt_elev')
building_elevation = CopyFeatures_management(building_inArea,
                                             'in_memory/building_elevation')
JoinField_management(building_elevation, 'FID', building_pt_elev, 'FID',
                     'RASTERVALU')

cursor = SearchCursor(waterPoint_elev, ['OID@', 'SHAPE@', 'RASTERVALU'])
for wp in cursor:
    geom = wp[1]

    # select buildings within distance
    D = str(distance) + ' Meters'
    inDistance = SelectLayerByLocation_management(building_elevation,
                                                  'WITHIN_A_DISTANCE', geom, D)

    # select buildings within elevation
    sql = 'RASTERVALU >= ' + str(
        wp[2] - elevation) + ' AND ' + 'RASTERVALU <= ' + str(wp[2] +
def main():
    if usePrefixSetTestingAndReporting == True:
        for prefixKey in prefixSetErrorReportingDict.keys():
            prefixAttributeQuery = prefixSetErrorReportingDict[prefixKey]
            prefixKeyItemDict = outerTestDict[prefixKey]
            prefixSetGdbBaseName = prefixKeyItemDict["prefixSetGdbBaseName"]
            prefixSetSourceGDBName = prefixSetGdbBaseName + '_Source.gdb'
            prefixSetSourceGDBLocation = os.path.join(mainFolder,
                                                      prefixSetSourceGDBName)
            routesSourceOutputLocation = os.path.join(
                prefixSetSourceGDBLocation, 'RoutesSource')

            try:
                Delete_management(
                    routesSourceFCAsALayer
                )  #pre-emptive layer delete prior to rebuilding it
                time.sleep(3)
            except:
                pass

            MakeFeatureLayer_management(routesSourceFC, routesSourceFCAsALayer)
            routesSourceSelectionClause = """ """ + str(
                prefixAttributeQuery) + """ """
            SelectLayerByAttribute_management(routesSourceFCAsALayer,
                                              "NEW_SELECTION",
                                              routesSourceSelectionClause)

            if Exists(returnGDBOrSDEPath(routesSourceOutputLocation)):
                pass
            else:
                CreateFileGDB_management(
                    mainFolder,
                    returnGDBOrSDEName(
                        returnGDBOrSDEPath(routesSourceOutputLocation)))
            # Checking to see if the output already exists.
            # If so, remove it.
            if Exists(routesSourceOutputLocation):
                print(
                    "Deleting the previous routesSourceOutputLocation at: \n" +
                    str(routesSourceOutputLocation) + ".")
                Delete_management(routesSourceOutputLocation)
                time.sleep(7)
            else:
                pass
            # Create a new file for the output.
            print(
                "Making a copy of the selection in the routesSourceFCAsALayer at: \n"
                + routesSourceOutputLocation + ".")
            CopyFeatures_management(routesSourceFCAsALayer,
                                    routesSourceOutputLocation)

            #Repeat for each of the other layers to be copied into the new *_Source.gdb.
            for itemToCopy in otherFCsToCopyList:
                itemToCopyInputLocation = os.path.join(
                    returnGDBOrSDEPath(routesSourceFC), itemToCopy)
                itemToCopyOutputLocation = os.path.join(
                    prefixSetSourceGDBLocation, itemToCopy)
                if Exists(itemToCopyOutputLocation):
                    print(
                        "Deleting the previous itemToCopyOutputLocation at: \n"
                        + str(itemToCopyOutputLocation) + ".")
                    Delete_management(itemToCopyOutputLocation)
                    time.sleep(7)
                else:
                    pass
                print("Making a copy of the itemToCopy at: \n" +
                      str(itemToCopyOutputLocation) + ".")
                CopyFeatures_management(itemToCopyInputLocation,
                                        itemToCopyOutputLocation)

    else:
        print(
            "The usePrefixSetTestingAndReporting value is not True. Will not create separate prefix set gdbs."
        )
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!"
Example #27
0
def addingDividedAttributeAndCreatingRoutes():
    print("Starting the addingDividedAttributeAndCreatingRoutes function!")

    #try:
    #    Delete_management(fcAsFeatureLayerLG)
    #except:
    #    pass
    #MakeFeatureLayer_management(unprunedAttributesRoadCenterlines, fcAsFeatureLayerLG)
    selectionQueryL5 = """ LRS_ROUTE_PREFIX NOT IN ('I', 'U', 'K') AND KDOT_DIRECTION_CALC = '1' """
    #SelectLayerByAttribute_management(fcAsFeatureLayerLG, NEW_SELECTION_CONST, selectionQueryL5)
    #CopyFeatures_management(fcAsFeatureLayerLG, scratchFC)
    try:
        Delete_management(fcAsFeatureLayerLG)
    except:
        pass
    #MakeFeatureLayer_management(scratchFC, fcAsFeatureLayerLG)
    preRouteSourceCRMLFieldObjectsList = ListFields(preRouteSourceCRML)
    preRouteSourceCRMLFieldNamesList = [
        x.name for x in preRouteSourceCRMLFieldObjectsList
    ]
    dividedFilterFieldName = "DividedFilter"
    dividedFilterFieldType = "TEXT"
    dividedFilterFieldLength = 3
    dividedFilterFieldAlias = dividedFilterFieldName
    if fieldName not in preRouteSourceCRMLFieldNamesList:
        AddField_management(preRouteSourceCRML, dividedFilterFieldName,
                            dividedFilterFieldType, "", "",
                            dividedFilterFieldLength, dividedFilterFieldAlias,
                            nullable)
    else:
        pass
    #MakeFeatureLayer_management(preRouteSourceCRML, fcAsFeatureLayerLG2)
    #AddRelate_management(fcAsFeatureLayerLG, 'Non_State_System_LRSKey', fcAsFeatureLayerLG2, 'SourceRouteId', 'TempRelate', "MANY_TO_MANY")
    # Bypass definition query and relate nonsense with a searchcursor / updatecursor pair.
    nonStateDividedKeysList = list()
    searchCursorFields = ['Non_State_System_LRSKey']
    newCursor = daSearchCursor(unprunedAttributesRoadCenterlines,
                               searchCursorFields, selectionQueryL5)

    for cursorRowItem in newCursor:
        nonStateDividedKeysList.append(cursorRowItem)

    try:
        del newCursor
    except:
        pass

    updateCursorFields = ['SourceRouteId', dividedFilterFieldName]
    newCursor = daUpdateCursor(preRouteSourceCRML, updateCursorFields)
    for cursorRowItem in newCursor:
        if cursorRowItem[0] is not None and str(
                cursorRowItem[0]) in nonStateDividedKeysList:
            cursorListItem = list(cursorRowItem)
            cursorListItem[1] = "yes"
            newCursor.update(cursorListItem)
        else:
            pass

    try:
        del newCursor
    except:
        pass

    selectionQueryL6 = ''' DividedFiler = "yes" '''
    MakeFeatureLayerManagement(preRouteSourceCRML, fcAsFeatureLayerLG2)
    SelectLayerByAttribute_management(fcAsFeatureLayerLG2, selectionQueryL6)
    CopyFeatures_management(fcAsFeatureLayerLG2, scratchFC2)
    FeatureVerticesToPoints(scratchFC2, scratchFC3, 'MID')
    raise KeyboardError("Stop. scratchFC3 created.")
Example #28
0
    # SQL to select only one city
    queryString = '"' + nameField + '" = ' + "'" + nameCity + "'"  # It means the same that: " nameField + " = ' nameCity '

    # Name of new layer of city
    nameCityLayer = nameCity.replace(" ", "_") + '_lyr'

    # Make a feature layers
    MakeFeatureLayer_management(parkAndRide, "parkAndRide_lry")
    MakeFeatureLayer_management(cityBoundaries, nameCityLayer, queryString)

    # Select all park and ride into of only city
    SelectLayerByLocation_management("parkAndRide_lry", "CONTAINED_BY",
                                     nameCityLayer)

    # Name of new feature class
    nameFeatureOut = nameCity + '_ParkAndRide'

    # Create a new feature class only with park and ride into of city
    CopyFeatures_management("parkAndRide_lry", nameOut)

    # Detele feature layers
    Delete_management("parkAndRide_lry")
    Delete_management(nameCityLayer)

# If happen some error
except:

    # Show the message
    print 'It was not possible selects all the park and ride facilities in a given city and saves them out to a new feature class'
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)
Example #30
0
def main():
    # tool inputs
    INPUT_NETWORK = argv[1]
    INPUT_POINTS = argv[2]
    INPUT_ORIGINS_FIELD = argv[3]
    INPUT_DESTINATIONS_FIELD = argv[4]
    INPUT_COEFF = float(argv[5])
    INPUT_SEARCH_RADIUS = float(argv[6]) if is_number(
        argv[6]) else float('inf')
    INPUT_OUTPUT_DIRECTORY = argv[7]
    INPUT_OUTPUT_FEATURE_CLASS_NAME = argv[8]
    INPUT_COMPUTE_WAYFINDING = argv[9] == "true"
    INPUT_VISUALIZATION = argv[10]

    # check that network has "Length" attribute
    if "Length" not in network_cost_attributes(INPUT_NETWORK):
        AddError("Network <%s> does not have Length attribute" % INPUT_NETWORK)
        return

    # check that coeff is at least 1
    if INPUT_COEFF < 1:
        AddError("Redundancy coefficient <%s> must be at least 1" %
                 INPUT_COEFF)
        return

    # extract origin and destination ids
    origin_ids = flagged_points(INPUT_POINTS, INPUT_ORIGINS_FIELD)
    if len(origin_ids) != 1:
        AddError("Number of origins <%s> must be 1" % len(origin_ids))
        return
    origin_id = origin_ids[0]
    destination_ids = flagged_points(INPUT_POINTS, INPUT_DESTINATIONS_FIELD)
    if len(destination_ids) == 0 or origin_ids == destination_ids:
        AddWarning("No OD pair found, no computation will be done")
        return

    # check that the output file does not already exist
    output_feature_class = "%s.shp" % join(INPUT_OUTPUT_DIRECTORY,
                                           INPUT_OUTPUT_FEATURE_CLASS_NAME)
    if Exists(output_feature_class):
        AddError("Output feature class <%s> already exists" %
                 output_feature_class)
        return

    # obtain visualization method
    visualize_segments = visualize_polylines = False
    if INPUT_VISUALIZATION == "Unique Segments":
        visualize_segments = True
    elif INPUT_VISUALIZATION == "Path Polylines":
        visualize_polylines = True
    elif INPUT_VISUALIZATION != "None":
        AddError("Visualization method <%s> must be one of 'Unique Segments', "
                 "'Path Polylines', or 'None'" % INPUT_VISUALIZATION)
        return

    # setup
    env.overwriteOutput = True

    # construct network and points
    network, points, edge_to_points = construct_network_and_load_buildings(
        INPUT_POINTS, INPUT_NETWORK)

    # find redundant paths for each origin-destination
    AddMessage("Computing redundant paths ...")
    progress_bar = Progress_Bar(len(destination_ids), 1, "Finding paths ...")
    # build output table one row at a time, starting from header row
    answers = [["OrigID", "DestID", "NumPaths", "Redundancy"]]
    if INPUT_COMPUTE_WAYFINDING:
        answers[0].append("Wayfinding")
    # visualization state
    if visualize_polylines:
        polylines = []
        polyline_data = []
    elif visualize_segments:
        all_unique_segment_counts = defaultdict(int)
    for destination_id in destination_ids:
        if origin_id != destination_id:
            all_paths = find_all_paths(network, points, INPUT_COEFF, origin_id,
                                       destination_id, INPUT_SEARCH_RADIUS,
                                       INPUT_COMPUTE_WAYFINDING)
            if all_paths is not None:
                if INPUT_COMPUTE_WAYFINDING:
                    (all_path_points, unique_segment_counts, num_paths,
                     redundancy, waypoint) = all_paths
                    answers.append([
                        origin_id, destination_id, num_paths, redundancy,
                        waypoint
                    ])
                else:
                    (all_path_points, unique_segment_counts, num_paths,
                     redundancy) = all_paths
                    answers.append(
                        [origin_id, destination_id, num_paths, redundancy])
                if visualize_polylines:
                    for i, path_points in enumerate(all_path_points):
                        polylines.append(
                            Polyline(
                                Array([
                                    Point(*coords) for coords in path_points
                                ])))
                        polyline_data.append((origin_id, destination_id, i))
                elif visualize_segments:
                    for edge_id in unique_segment_counts:
                        all_unique_segment_counts[
                            edge_id] += unique_segment_counts[edge_id]
        progress_bar.step()
    AddMessage("\tDone.")

    # write out results
    if len(answers) > 1:
        AddMessage("Writing out results ...")
        # write out to a table
        write_rows_to_csv(answers, INPUT_OUTPUT_DIRECTORY,
                          INPUT_OUTPUT_FEATURE_CLASS_NAME)
        # visualize
        if visualize_polylines:
            CopyFeatures_management(polylines, output_feature_class)
            data_fields = ["OrigID", "DestID", "PathID"]
            for field in data_fields:
                AddField_management(in_table=output_feature_class,
                                    field_name=field,
                                    field_type="INTEGER")
            rows = UpdateCursor(output_feature_class, data_fields)
            for j, row in enumerate(rows):
                row[0], row[1], row[2] = polyline_data[j]
                rows.updateRow(row)
            # create a layer of the polylines shapefile and symbolize
            polylines_layer_name = "%s_layer" % INPUT_OUTPUT_FEATURE_CLASS_NAME
            polylines_layer = "%s.lyr" % join(INPUT_OUTPUT_DIRECTORY,
                                              INPUT_OUTPUT_FEATURE_CLASS_NAME)
            MakeFeatureLayer_management(output_feature_class,
                                        polylines_layer_name)
            SaveToLayerFile_management(polylines_layer_name, polylines_layer,
                                       "ABSOLUTE")
            ApplySymbologyFromLayer_management(
                polylines_layer,
                join(path[0],
                     "Symbology_Layers\sample_polylines_symbology.lyr"))
            add_layer_to_display(polylines_layer)
        elif visualize_segments:
            id_mapping, edges_file = select_edges_from_network(
                INPUT_NETWORK, all_unique_segment_counts.keys(),
                INPUT_OUTPUT_DIRECTORY,
                "%s_edges" % INPUT_OUTPUT_FEATURE_CLASS_NAME)
            AddField_management(in_table=edges_file,
                                field_name="PathCount",
                                field_type="INTEGER")
            rows = UpdateCursor(edges_file, ["OID@", "PathCount"])
            for row in rows:
                row[1] = all_unique_segment_counts[id_mapping[row[0]]]
                rows.updateRow(row)
        AddMessage("\tDone.")
    else:
        AddMessage("No results to write out.")