示例#1
0
def NONSTATE_INT():
    print "add intersection points where state routes intersect non-state routes"
    MakeFeatureLayer_management(nonstate, 'NON_STATE_SYSTEM',
                                "CITYNUMBER IS NOT NULL AND CITYNUMBER<999")
    MakeFeatureLayer_management(connection1 + NewRoute, NewRoute)
    Intersect_analysis(
        "CCL_LRS_ROUTE #;'NON_STATE_SYSTEM' #",
        connection1 + "Intersect_NONSTATE", "ALL", "5 Feet", "POINT"
    )  #this doesnt reference the newroute variable, its easier that way
    MakeFeatureLayer_management(connection1 + "Intersect_NONSTATE", "NSI")
    LocateFeaturesAlongRoutes_lr("NSI", "CCL_LRS_ROUTE", NewRouteKey, "5 Feet",
                                 connection1 + "INTR_CCL_NS",
                                 "CCL_LRS POINT MEASURE", "ALL", "DISTANCE",
                                 "ZERO", "FIELDS", "M_DIRECTON")
    MakeRouteEventLayer_lr("CCL_LRS_ROUTE", NewRouteKey,
                           connection1 + "INTR_CCL_NS",
                           "CCL_LRS POINT MEASURE", "INTR_CCL_NS Events", "#",
                           "ERROR_FIELD", "ANGLE_FIELD", "NORMAL", "ANGLE",
                           "LEFT", "POINT")
    AddField_management("INTR_CCL_NS Events", "CITY", "TEXT", "#", "#", "100")
    AddJoin_management("INTR_CCL_NS Events", "CITYNUMBER", citylimits,
                       "CITYNUMBER")
    #CalculateField_management("INTR_CCL_NS Events", schema+"INTR_CCL_NS_Features.CITY", "!GIS_DEV.CITY_LIMITS.CITY!", "PYTHON_9.3") #Preupdate
    CalculateField_management("INTR_CCL_NS Events",
                              schema + "INTR_CCL_NS_Features.CITY",
                              "!GIS.CITY_LIMITS.CITY!", "PYTHON_9.3")
    RemoveJoin_management("INTR_CCL_NS Events", "#")
    print "NonState_Int completed successfully."
示例#2
0
def AddInsert(fc, layer_name, newtbl, workspace):
    MakeTableView_management(newtbl, "NEWROWS_View", "#", "#", "#")
    addcount = int(GetCount_management("NEWROWS_View").getOutput(0))
    if addcount == 0:
        print "no new records"
        pass
    else:
        MakeFeatureLayer_management(fc, layer_name)
        MakeXYEventLayer_management(
            "NEWROWS_View", "CROSSINGLONGITUDE", "CROSSINGLATITUDE",
            "NEWROWS_Layer",
            "GEOGCS['GCS_WGS_1984',DATUM['D_WGS_1984',SPHEROID['WGS_1984',6378137.0,298.257223563]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]],VERTCS['NAVD_1988',VDATUM['North_American_Vertical_Datum_1988'],PARAMETER['Vertical_Shift',0.0],PARAMETER['Direction',1.0],UNIT['Meter',1.0]];-400 -400 1000000000;-100000 10000;-100000 10000;8.98315284119522E-09;0.001;0.001;IsHighPrecision",
            "#")
        FeatureClassToFeatureClass_conversion(
            "NEWROWS_Layer", "D:/Temp", "LOADTHIS1.shp", "#",
            """CROSSINGID "CROSSINGID" true false false 30 Text 0 0 ,First,#,Database Connections/sdedev_ciims.sde/CIIMS.NEWROWS_Features,CROSSINGID,-1,-1;CROSSINGLA "CROSSINGLA" true true false 8 Double 10 38 ,First,#,Database Connections/sdedev_ciims.sde/CIIMS.NEWROWS_Features,CROSSINGLATITUDE,-1,-1;CROSSINGLO "CROSSINGLO" true true false 8 Double 10 38 ,First,#,Database Connections/sdedev_ciims.sde/CIIMS.NEWROWS_Features,CROSSINGLONGITUDE,-1,-1;CROSSINGTY "CROSSINGTY" true true false 2 Text 0 0 ,First,#,Database Connections/sdedev_ciims.sde/CIIMS.NEWROWS_Features,CROSSINGTYPE,-1,-1""",
            "#")
        Append_management(
            "D:/Temp/LOADTHIS1.shp", layer_name, "NO_TEST",
            """CROSSINGID "CROSSINGID" true false false 30 Text 0 0 ,First,#,D:/Temp/LOADTHIS1.shp,CROSSINGID,-1,-1;CROSSINGLATITUDE "CROSSINGLATITUDE" true true false 8 Double 10 38 ,First,#,D:/Temp/LOADTHIS1.shp,CROSSINGLA,-1,-1;CROSSINGLONGITUDE "CROSSINGLONGITUDE" true true false 8 Double 10 38 ,First,#,D:/Temp/LOADTHIS1.shp,CROSSINGLO,-1,-1;CROSSINGTYPE "CROSSINGTYPE" true true false 2 Text 0 0 ,First,#,D:/Temp/LOADTHIS1.shp,CROSSINGTY,-1,-1;LOADDATE "LOADDATE" true true false 36 Date 0 0 ,First,#""",
            "#")
        Delete_management("D:/Temp/LOADTHIS1.shp", "#")
        updatelyr = layer_name + "new"
        MakeFeatureLayer_management(layer_name, updatelyr, "LOADDATE IS NULL")
        with da.Editor(workspace) as edit:
            CalculateField_management(updatelyr, "LOADDATE",
                                      "datetime.datetime.now( )", "PYTHON_9.3",
                                      "#")
        del fc, layer_name, newtbl, workspace, updatelyr
        print "new rows inserted into Static_Crossings"
示例#3
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)
示例#4
0
def setupEnv():
    print "run at "+ str(datetime.datetime.now())
    rsel = "ENDDATE IS NULL"
    MakeTableView_management(resolve, "CCL_Resolution_tbl", rsel)
    CalculateField_management("CCL_Resolution_tbl", "CCL_LRS",  'str(!CITYNUMBER!)+str(!LRS_KEY![3:14])', "PYTHON" )
    MakeTableView_management(connection1+"CCL_Resolution", "CCL_Resolution_tbl10", 'CITYNUMBER<100')
    CalculateField_management("CCL_Resolution_tbl10", "CCL_LRS", '"0"+str(!CITYNUMBER!)+str(!LRS_KEY![3:14])', "PYTHON")
    MakeFeatureLayer_management(cntyroutelyr, "cmlrs")
    MakeFeatureLayer_management(stateroutelyr, "smlrs")
    MakeFeatureLayer_management(citylimits, "CityLimits", "TYPE IN ( 'CS', 'ON')")
    LocateFeaturesAlongRoutes_lr(citylimits,"cmlrs","LRS_KEY","0 Feet",connection1+"GIS_CITY","LRS_KEY LINE Beg_CMP End_CMP","FIRST","DISTANCE","NO_ZERO","FIELDS","M_DIRECTON")
    MakeRouteEventLayer_lr("cmlrs","LRS_KEY","CCL_Resolution_tbl","LRS_KEY LINE BEG_CNTY_LOGMILE END_CNTY_LOGMILE","City_Connecting_Links","#","ERROR_FIELD","NO_ANGLE_FIELD","NORMAL","ANGLE","LEFT","POINT")
    MakeTableView_management(connection1+"GIS_CITY", "GIS_CITY")
    MakeTableView_management(laneclass, "LaneClass")
    MakeRouteEventLayer_lr("cmlrs","LRS_KEY","GIS_CITY","LRS_KEY LINE BEG_CMP END_CMP","GIS_BASED_CCL","#","ERROR_FIELD","NO_ANGLE_FIELD","NORMAL","ANGLE","LEFT","POINT")
    OverlayRouteEvents_lr(connection1+"CCL_Resolution","LRS_KEY LINE BEG_CNTY_LOGMILE END_CNTY_LOGMILE",laneclass,"LRS_KEY LINE BCMP ECMP","INTERSECT",connection1+"CCL_LANE_CLASS_OVERLAY","LRS_KEY LINE BEG_CNTY_LOGMILE END_CNTY_LOGMILE","NO_ZERO","FIELDS","INDEX")
    print "create Route Layer specific to City Connecting Link locations"    
    FeatureClassToFeatureClass_conversion("City_Connecting_Links", connection0, "CITY_CONNECTING_LINK_CENTERLINE")
    LocateFeaturesAlongRoutes_lr(connection1+"CITY_CONNECTING_LINK_CENTERLINE",stateroutelyr,"LRS_ROUTE","0 Meters",connection1+"CCL_STATE_LRS_tbl","LRS_ROUTE LINE BEG_STATE_LOGMILE END_STATE_LOGMILE","FIRST","DISTANCE","ZERO","FIELDS","M_DIRECTON")
    MakeRouteEventLayer_lr("smlrs", "LRS_ROUTE",connection1+"CCL_STATE_LRS_tbl","LRS_ROUTE LINE BEG_STATE_LOGMILE END_STATE_LOGMILE","CCL_STATE_LRS","#","ERROR_FIELD","NO_ANGLE_FIELD","NORMAL","ANGLE","LEFT","POINT")
    FeatureClassToFeatureClass_conversion("CCL_STATE_LRS", connection0, "CITY_CONNECTING_LINK_STATEREF")
    if Exists(connection1+"CITY_CONNECTING_LINK_STATE"):
        Delete_management(connection1+"CITY_CONNECTING_LINK_STATE")
    Dissolve_management(connection1+"CITY_CONNECTING_LINK_STATEREF",connection1+"CITY_CONNECTING_LINK_STATE","LRS_ROUTE;CITY;CITYNUMBER;DESCRIPTION;CCL_LRS","BEG_STATE_LOGMILE MIN;END_STATE_LOGMILE MAX","MULTI_PART","UNSPLIT_LINES")
    Dissolve_management(connection1+"CITY_CONNECTING_LINK_STATEREF",connection1+"CITY_CONNECTING_LINK_STATE_D","CCL_LRS","BEG_STATE_LOGMILE MIN;END_STATE_LOGMILE MAX","MULTI_PART","DISSOLVE_LINES")
    
    print "processes to Create the layer that will be used to create a new LRS for city connecting links"
示例#5
0
def calibrationCCL_Edit():

    print "deriving CCL LRS starting points and calibrations"
    CCLEnd = "!" + schema + "CITY_CONNECTING_LINK_STATE.MAX_END_STATE_LOGMILE! - !" + schema + "CITY_CONNECTING_LINK_STATE_D.MIN_BEG_STATE_LOGMILE!"
    CCLBeg = "!" + schema + "CITY_CONNECTING_LINK_STATE.MIN_BEG_STATE_LOGMILE! - !" + schema + "CITY_CONNECTING_LINK_STATE_D.MIN_BEG_STATE_LOGMILE!"
    MakeFeatureLayer_management(LineFeatureClass, "CITY_CONNECTING_LINK_RESET")
    resln = "CITY_CONNECTING_LINK_RESET"
    AddField_management(resln, "CCL_BEGIN", "DOUBLE", 12, 3)
    AddField_management(resln, "CCL_END", "DOUBLE", 12, 3)
    AddJoin_management("CITY_CONNECTING_LINK_RESET", "CCL_LRS",
                       connection1 + "CITY_CONNECTING_LINK_STATE_D", "CCL_LRS",
                       "KEEP_ALL")
    CalculateField_management(resln, "CCL_BEGIN", CCLBeg, "PYTHON")
    CalculateField_management(resln, "CCL_END", CCLEnd, "PYTHON")
    print "calibrating LRS - point calibration method"
    #statecalpoints = stateroutelyr+"_Point"
    #print statecalpoints
    #MakeFeatureLayer_management(statecalpoints, "smlrs_pt")
    #print connection1+"CITY_CONNECTING_LINK_STATE_D"
    #MakeFeatureLayer_management(connection1+"CITY_CONNECTING_LINK_STATE_D", "dissolved_res_sects")
    #intersects = ["dissolved_res_sects", "smlrs_pt"]
    #Intersect_analysis(intersects,connection0+"\CALIBRATION_POINTS_CCL","ALL","#","POINT")
    #print connection1+"CALIBRATION_POINTS_CCL"
    #MakeFeatureLayer_management(connection1+"CALIBRATION_POINTS_CCL", "Calibrators")
    #querystr = "Substring( CCL_LRS,4, 12)<> LRS_ROUTE"
    #SelectLayerByAttribute_management("Calibrators","NEW_SELECTION",querystr)
    #DeleteRows_management("Calibrators")
    MakeFeatureLayer_management(connection1 + "CITY_CONNECTING_LINK_STATE",
                                "CCL_sections")
    #DeleteIdentical_management("Calibrators","LRS_KEY;POINT_X;POINT_Y;POINT_M","#","0")
    AddField_management("CCL_sections", "CCL_BEGIN", "DOUBLE", "#", "#", "#",
                        "#", "NULLABLE", "NON_REQUIRED", "#")
    AddField_management("CCL_sections", "CCL_END", "DOUBLE", "#", "#", "#",
                        "#", "NULLABLE", "NON_REQUIRED", "#")
    AddJoin_management("CCL_sections", "CCL_LRS", "dissolved_res_sects",
                       "CCL_LRS", "KEEP_ALL")
    CalculateField_management(
        "CCL_sections", schema + "CITY_CONNECTING_LINK_STATE.CCL_BEGIN", "!" +
        schema + "CITY_CONNECTING_LINK_STATE.MIN_BEG_STATE_LOGMILE! - !" +
        schema + "CITY_CONNECTING_LINK_STATE_D.MIN_BEG_STATE_LOGMILE!",
        "PYTHON", "#")
    CalculateField_management(
        "CCL_sections", schema + "CITY_CONNECTING_LINK_STATE.CCL_END", "!" +
        schema + "CITY_CONNECTING_LINK_STATE.MAX_END_STATE_LOGMILE! - !" +
        schema + "CITY_CONNECTING_LINK_STATE_D.MIN_BEG_STATE_LOGMILE!",
        "PYTHON", "#")
    #AddField_management(connection1+"CALIBRATION_POINTS_CCL","CCL_MEASURE", "DOUBLE", 12, 3)
    #CalculateField_management("Calibrators","CCL_MEASURE","!POINT_M! - !MIN_BEG_STATE_LOGMILE!","PYTHON","#")
    CreateRoutes_lr(LineFeatureClass, NewRouteKey,
                    connection1 + NewRoute + "base", "TWO_FIELDS", NewBeg,
                    NewEnd, "UPPER_LEFT", "1", "0", "IGNORE", "INDEX")
    CalibrateRoutes_lr(connection1 + "CCL_LRS_ROUTEbase", "CCL_LRS",
                       r"D:\workspaces\pythontests.gdb\CCL_Point_Calibrators",
                       "point_LRS", "point_Loc", connection1 + "CCL_LRS_ROUTE",
                       "MEASURES", "10 Feet", "BETWEEN", "NO_BEFORE",
                       "NO_AFTER", "NO_IGNORE", "KEEP", "INDEX")
    AddField_management(connection1 + NewRoute, "NETWORKDATE", "DATE")
    CalculateField_management(connection1 + NewRoute, "NETWORKDATE",
                              "datetime.datetime.now( )", "PYTHON_9.3", "#")
    MakeFeatureLayer_management(connection1 + "CCL_LRS_ROUTE", NewRoute)
示例#6
0
def CreateNUSYSLocal():
    MakeFeatureLayer_management(
        NonState, "NonState",
        "(LRS_KEY LIKE '%C%' OR LRS_ROUTE_PREFIX = 'C') AND (MILEAGE_COUNTED = -1 OR SURFACE = 'Propose')"
    )

    #NonState System has unique IDS that are also the non_persistent Object ID's
    #To force persistence on the Unique IDS, perform an intersect to the state boundary layer
    print "buffering the state boundary"
    Buffer_analysis(
        r"Database Connections/SDEPROD_SHARED.sde/SHARED.STATE_BOUNDARY",
        r"C:/temp/Nusys_Check.gdb/State_Boundary_1Mile", "5280 Feet", "FULL",
        "ROUND", "NONE", "", "PLANAR")
    print "intersecting non_state system to the state boundary to preserve Object ID's and eliminate non-spatial segments"
    MakeFeatureLayer_management(
        r"C:/temp/Nusys_Check.gdb/State_Boundary_1Mile", "StateBnd")
    Intersect_analysis("NonState #;StateBnd #",
                       r"C:/temp/Nusys_Check.gdb/Non_State_Classified", "ALL",
                       "-1 Unknown", "LINE")
    print "adding layers to gp workflow or MXD"
    NonState_fx = r'C:/temp/Nusys_Check.gdb/Non_State_Classified'

    MakeFeatureLayer_management(NUSYS, "Nusys_Extract",
                                "NSEC_SUB_CLASS <> 'R'")
    MakeFeatureLayer_management(NonState_fx, "Non_State_Classified")
def FindOverlapsSausages():
    '''KDOT Checks are already simplifying lines
    technically this is an unnecessary step 
    and it is a time consuming, resource intensive process
    KDOT will run this script on lines that have already been simplified
    Data stewards are encouraged to simplify lines to improve their data quality and system performance
    using a tool or the following command, which is commented out'''
    #SimplifyLine_cartography(inroadcenterlines, ", algorithm="POINT_REMOVE", tolerance="3 Feet", error_resolving_option="RESOLVE_ERRORS", collapsed_point_option="NO_KEEP", error_checking_option="CHECK")
    
    #Check to Make sure that Shape_Length is the appropriate geometry column length in all geodatabases
    MakeFeatureLayer_management(roadcenterlines, "RoadCenterlinesS3_L10", "Shape_Length>=10")
    #test overlapping with a centerline midpoint
    FeatureVerticesToPoints_management("RoadCenterlinesS3_L10", "in_memory/RoadCenterlinesS3_L10_Mid", point_location="MID")
    #Get the count of roads within a distance of the centerline midpoint
    SpatialJoin_analysis("RoadCenterlinesS3_L10_Mid", roadcenterlines, "in_memory/ValidateOverlaps2", "JOIN_ONE_TO_ONE", "KEEP_ALL", '#', "INTERSECT", "2 Feet", "Distance")
    #return the midpoints with a count greater than 1 - indicating possible overlaps
    #output this next line into validation geodatabase and add to arcmap for user interface
    FeatureClassToFeatureClass_conversion("in_memory/ValidateOverlaps2", r"C:\temp\New File Geodatabase (2).gdb", "ValidateOverlaps",""""Join_Count" > 1""")
    #may need to dev code to test for endpoints
    #clean up in memory artifact
    Delete_management("ValidateOverlaps2")
    #In aggregated data, county boundary overlaps are expected.  It's also assumed that county bound left right should be coded correctly.  
    #the following feature layer are the most important overlaps for review
    MakeFeatureLayer_management("ValidateOverlaps", "ValidateOverlaps_Non_County_Boundary", "COUNTY_L = COUNTY_R")
    #now using same midpoints look for sausages, midpoints less than 60 feet apart, might explore different distances under 60 feet
    #it might help and also hurt to lengthen the minimum segment length to longer than 10 feet for this, test a little more
    SpatialJoin_analysis("RoadCenterlinesS3_L10_Mid", roadcenterlines, "in_memory/ValidateSausages60", "JOIN_ONE_TO_ONE", "KEEP_ALL", '#', "INTERSECT", "120 Feet", "Distance")
    
    FeatureClassToFeatureClass_conversion("in_memory/ValidateSausages60", r"C:\temp\New File Geodatabase (2).gdb", "ValidateSausages_60ft",""""Join_Count" > 1""")
    Delete_management("ValidateSausages60")
    MakeFeatureLayer_management("ValidateSausages_60ft", "ValidateSausages_Non_County_Boundary", "COUNTY_L = COUNTY_R")
示例#8
0
def CreateNonStateRoutes():
    FeatureClassToFeatureClass_conversion(in_features="Database Connections/SDEPROD_SHARED.sde/SHARED.NON_STATE_SYSTEM", out_path="C:/temp/Nusys_Check.gdb", out_name="Non_State_System", where_clause="", field_mapping="#", config_keyword="")
    NonState = r"C:/temp/Nusys_Check.gdb/Non_State_System"
    MakeFeatureLayer_management(NonState, "NonState", "MILEAGE_COUNTED = -1 AND SURFACE NOT LIKE 'Propose'")
    MakeFeatureLayer_management(NonState, "BackwardSegs", "LRS_BACKWARDS = -1")
    FlipLine_edit("BackwardSegs") 
    CreateRoutes_lr("NonState", "LRS_KEY", destdb+"\Route", "TWO_FIELDS", "LRS_BEG_CNTY_LOGMILE", "LRS_BEG_CNTY_LOGMILE", "UPPER_LEFT", "1", "0", "IGNORE", "INDEX")
    #Flip them back to the original direction
    FlipLine_edit(in_features="BackwardSegs") 
def writeStewardPointCounts():
    MakeFeatureLayer_management(originalPointsSource, originalPointsAsLayer)
    MakeFeatureLayer_management(simplifiedPointsSource, simplifiedPointsAsLayer)
    
    allStewardsDict = dict()
    
    #Programatically grab the stewards instead of manually listing them here
    newCursor = daSearchCursor(originalPointsAsLayer, ["OID@", "STEWARD"])
    
    for cursorItem in newCursor:
        allStewardsDict[cursorItem[1]] = 'True'
    
    if 'newCursor' in locals():
        try:
            del newCursor
        except:
            print("The cursor exists, but it could not be successfully removed.")
    else:
        print("The cursor has already been removed.")
    
    
    try:
        wHandle = open(outputFile,'w')
        columnNames = "StewardID , OriginalCount , SimplifiedCount\n"
        wHandle.write(columnNames)
        
        # For each steward in the list, get a count of all of the original centerline
        # points and the the simplified road centerlines points.
        # Next, write the data out to a text file in comma separated form.
        for stewardItem in allStewardsDict.keys():
            if stewardItem is not None:
                selectionQuery = """ "STEWARD" = '""" + stewardItem + """' """
                SelectLayerByAttribute_management(originalPointsAsLayer, selectionTypeToUse, selectionQuery)
                oCountResult = GetCount_management(originalPointsAsLayer)
                originalCount = int(oCountResult.getOutput(0))
                SelectLayerByAttribute_management(simplifiedPointsAsLayer, selectionTypeToUse, selectionQuery)
                sCountResult = GetCount_management(simplifiedPointsAsLayer)
                simplifiedCount = int(sCountResult.getOutput(0))
                strToWrite = "'" + stewardItem + "'" + ", " + str(originalCount) + ", " + str(simplifiedCount) + "\n"
                print("Writing " + strToWrite + " to the file: " + outputFile + ".")
                wHandle.write(strToWrite)
            else:
                print("The stewardItem is None, so it will be skipped.")
    
    except:
        errorInfo = sys.exc_info()[0]
        errorInfo1 = sys.exc_info()[1]
        print("An error occurred: " + str(errorInfo) + str(errorInfo1))
        try:
            wHandle.close()
        except:
            raise
        try:
            del errorInfo
            del errorInfo1
        except:
            pass
示例#10
0
def MakeRouteLayers(OpEnvironmentMode):
    from EXOR_GIS_CONFIG import OpEnvironment
    OpRunIn= OpEnvironment.OpRunInRoutes  # @UndefinedVariable
    OpRunOut= OpEnvironment.OpRunOut  # @UndefinedVariable
    #adm=OpEnvironment.adm  # @UndefinedVariable
    Owner=OpEnvironment.Owner  # @UndefinedVariable
    DB=OpEnvironment.DB  # @UndefinedVariable
    
    env.workspace = OpRunIn
    env.overwriteOutput = True
    print OpRunIn
    
    #combine the connection, db, and owner to the destination path for enterprise geodatabase output
    OpRunFullOut = OpRunOut+r"/"+DB+"."+Owner+"."
    
    print "Updating CRND"
    #add the Map Extract Event Table limited to primary direction into memory
    TruncateTable_management(OpRunFullOut+"CRND")
    Append_management("CRND", OpRunFullOut+"CRND", "NO_TEST")
    print "Updating SRND"
    TruncateTable_management(OpRunFullOut+"SRND")
    Append_management("SRND", OpRunFullOut+"SRND", "NO_TEST")
    print "Updating NSND"
    TruncateTable_management(OpRunFullOut+"NSND")
    Append_management("NSND", OpRunFullOut+"NSND", "NO_TEST")  
        
    if GetCount_management("MAP_EXTRACT")>0:
        MakeTableView_management("MAP_EXTRACT", "V_MV_MAP_EXTRACT", "DIRECTION < 3")
    
        #Add the CRND CANSYS rotue layer, dynseg the event table, truncate and load to CMLRS
        MakeFeatureLayer_management("CRND", "CRND")
        MakeRouteEventLayer_lr("CRND", "NE_UNIQUE", "MAP_EXTRACT", "NQR_DESCRIPTION LINE BEG_CNTY_LOGMILE END_CNTY_LOGMILE", "CMLRS1", "", "ERROR_FIELD", "NO_ANGLE_FIELD", "NORMAL", "ANGLE", "LEFT", "POINT")
        try:
            print "truncation and appending the CMLRS"
            TruncateTable_management(OpRunFullOut+"CMLRS")
            Append_management("CMLRS1", OpRunFullOut+"CMLRS", "NO_TEST")
        except:
            print "could not truncate, overwriting CMLRS"
            FeatureClassToFeatureClass_conversion("CMLRS1", OpRunOut, "CMLRS","#", "#", "#")
        #except:
        #    print "could not update the CMLRS"
        
        MakeFeatureLayer_management("SRND", "SRND")
        MakeRouteEventLayer_lr("SRND", "NE_UNIQUE", "MAP_EXTRACT", "STATE_NQR_DESCRIPTION LINE BEG_STATE_LOGMILE END_STATE_LOGMILE", out_layer="SMLRS1", offset_field="", add_error_field="ERROR_FIELD", add_angle_field="NO_ANGLE_FIELD", angle_type="NORMAL", complement_angle="ANGLE", offset_direction="LEFT", point_event_type="POINT")
        try:
            print "truncation and appending the SMLRS"
            TruncateTable_management(OpRunFullOut+"SMLRS")
            Append_management("SMLRS1", OpRunFullOut+"SMLRS", "NO_TEST")
        except:
            print "could not truncate, overwriting SMLRS"
            FeatureClassToFeatureClass_conversion("SMLRS1", OpRunOut, "SMLRS","#", "#", "#")
        #except:
        #    print "could not update the SMLRS" 
        
        print "Route Layers Updated"
    else: 
        print "the map extract is unreliable and was not exported"
示例#11
0
def Report():
    OverlayRouteEvents_lr(
        connection1 + "MAINTENANCE_CCL", "CCL_LRS LINE CCL_BEGIN CCL_END",
        connection1 + "LANECLASS_CCL", "CCL_LRS LINE CCL_BEGIN CCL_END",
        "UNION", connection1 + "CCL_Report_M",
        "CCL_LRS LINE CCL_MA_BEGIN CCL_MA_END", "NO_ZERO", "FIELDS", "INDEX")
    DissolveRouteEvents_lr(connection1 + "CCL_Report_M",
                           "CCL_LRS LINE CCL_MA_BEGIN CCL_MA_END",
                           "CITYNO;MAINT_DESC;CITY_NAME;Lanes",
                           connection1 + "CCL_Report_D",
                           "CCL_LRS LINE CCL_MA_BEGIN CCL_MA_END",
                           "CONCATENATE", "INDEX")
    #cleanup border errors - make feature layers based on City, city number, and CCLLRS and delete where they are not consistent between Maintenance and Resolution sections
    if Exists(connection1 + "CCL_Report"):
        MakeTableView_management(connection1 + "CCL_Report", "Report_Clean1",
                                 "CCL_LRS2 <> CCL_LRS")
        DeleteRows_management("Report_Clean1")
    LocateFeaturesAlongRoutes_lr(LineFeatureClass,
                                 connection1 + "CCL_LRS_ROUTE", NewRouteKey,
                                 "#", connection1 + "RES_SECTION_CCL",
                                 "CCL_LRS LINE CCL_BEGIN CCL_END", "ALL",
                                 "DISTANCE", "ZERO", "FIELDS", "M_DIRECTON")
    OverlayRouteEvents_lr(
        connection1 + "RES_SECTION_CCL", "CCL_LRS LINE CCL_BEGIN CCL_END",
        connection1 + "CCL_Report_D", "CCL_LRS LINE CCL_MA_BEGIN CCL_MA_END",
        "INTERSECT", connection1 + "CCL_Report",
        "CCL_LRS LINE CCL_BEGIN CCL_END", "NO_ZERO", "FIELDS", "INDEX")
    MakeRouteEventLayer_lr(connection1 + "CCL_LRS_ROUTE", "CCL_LRS",
                           connection1 + "CCL_Report",
                           "CCL_LRS LINE CCL_BEGIN CCL_END",
                           "City Connecting Links Mapping", "#", "ERROR_FIELD",
                           "NO_ANGLE_FIELD", "NORMAL", "ANGLE", "LEFT",
                           "POINT")
    print "add mapping fields for lane miles"
    AddField_management("City Connecting Links Mapping", "CenterlineMiles",
                        "DOUBLE")
    CalculateField_management("City Connecting Links Mapping",
                              "CenterlineMiles", '[CCL_END]-[CCL_BEGIN]', "VB")
    AddField_management("City Connecting Links Mapping", "LaneMiles", "DOUBLE")
    CalculateField_management("City Connecting Links Mapping", "LaneMiles",
                              '([CCL_END]-[CCL_BEGIN])*[Lanes]', "VB")
    AddField_management(connection1 + "CITY_CONNECTING_LINK_CENTERLINE",
                        "CenterlineMiles", "DOUBLE")
    MakeFeatureLayer_management(
        connection1 + "CITY_CONNECTING_LINK_CENTERLINE", 'Res_centerline')
    CalculateField_management("Res_centerline", "CenterlineMiles",
                              '[END_CNTY_LOGMILE]-[BEG_CNTY_LOGMILE]', "VB")
    Dissolve_management("Res_centerline", connection1 + "CCL_LEGEND",
                        "CITY;LRS_KEY;CITYNUMBER;CCL_LRS",
                        "CenterlineMiles SUM", "MULTI_PART", "DISSOLVE_LINES")
    AddField_management(connection1 + "CCL_LEGEND", "CCL_LEGEND", "TEXT", "#",
                        "#", "50")
    legendexp = 'str(!CCL_LRS![3]) +"-" + str(!CCL_LRS![6:9]).lstrip("0")+"........"+ str(!SUM_CenterlineMiles!)'
    MakeFeatureLayer_management(connection1 + "CCL_LEGEND", 'LegendCalc')
    CalculateField_management("LegendCalc", "CCL_LEGEND", legendexp,
                              "PYTHON_9.3", "#")
示例#12
0
def ConflateKDOTrestart(gdb, DOTRoads):
    """Conflation restart for selecting KDOT roads to conflate to the NG911 Network"""
    from arcpy import SelectLayerByLocation_management, FeatureClassToFeatureClass_conversion
    from arcpy import env
    env.overwriteOutput = 1
    checkfile = gdb
    MakeFeatureLayer_management(DOTRoads+"/KDOT_HPMS_2012","KDOT_Roads","#","#","#")
    MakeFeatureLayer_management(checkfile+"/RoadCenterline","RoadCenterline","#","#","#")
    SelectLayerByLocation_management("KDOT_Roads","INTERSECT","RoadCenterline","60 Feet","NEW_SELECTION")
    FeatureClassToFeatureClass_conversion("KDOT_Roads",checkfile+r"/NG911","KDOT_Roads_Review","#","#","#")
示例#13
0
def ConflateKDOTrestart():
    """Conflation restart for selecting KDOT roads to conflate to the NG911 Network"""
    MakeFeatureLayer_management(DOTRoads + "/KDOT_HPMS_2012", "KDOT_Roads",
                                "#", "#", "#")
    MakeFeatureLayer_management(gdb + "/RoadCenterline", "RoadCenterline", "#",
                                "#", "#")
    SelectLayerByLocation_management("KDOT_Roads", "INTERSECT",
                                     "RoadCenterline", "60 Feet",
                                     "NEW_SELECTION")
    FeatureClassToFeatureClass_conversion("KDOT_Roads", gdb + r"/NG911",
                                          "KDOT_Roads_Review", "#", "#", "#")
示例#14
0
def Annually():
    #arcpy.MakeFeatureLayer_management(CPMSlyr, 'CPMS', ProjectSelect)
    MakeFeatureLayer_management(CPMSlyr, 'CPMS')
    MakeFeatureLayer_management(CountyLyr, 'County')
    MakeFeatureLayer_management(HPMSlyr, 'HPMS')
    MakeFeatureLayer_management(MPOLyr, 'MPO')
    MakeFeatureLayer_management(CONGDistlyr, 'CONG')

    #make the polygon analysis layer for Districts, Counties, and MPOs
    Union_analysis("CONG #;MPO #;County #", ws + "/Polygons", "ALL", "1 feet",
                   "GAPS")
示例#15
0
def CreateRuralRMLocal():
    MakeFeatureLayer_management(NonState, "NonStateRM", "((LRS_KEY LIKE '%R%' OR LRS_ROUTE_PREFIX = 'R') OR (LRS_KEY LIKE '%M%' OR LRS_ROUTE_PREFIX = 'M')) AND (MILEAGE_COUNTED = -1 OR SURFACE = 'Propose')")
    print "buffering the state boundary"
    Buffer_analysis(r"Database Connections/SDEPROD_SHARED.sde/SHARED.STATE_BOUNDARY", r"C:/temp/Nusys_Check.gdb/State_Boundary_1Mile", "5280 Feet", "FULL", "ROUND", "NONE", "", "PLANAR")
    print "intersecting non_state system to the state boundary to preserve Object ID's and eliminate non-spatial segments"
    MakeFeatureLayer_management(r"C:/temp/Nusys_Check.gdb/State_Boundary_1Mile", "StateBnd" )
    Intersect_analysis("NonStateRM #;StateBnd #", r"C:/temp/Nusys_Check.gdb/Non_State_RuralClass", "ALL", "-1 Unknown", "LINE")
    print "adding layers to gp workflow or MXD"
    NonState_fx = r'C:/temp/Nusys_Check.gdb/Non_State_RuralClass'
    
    #MakeFeatureLayer_management(NUSYS, "Nusys_Extract", "NSEC_SUB_CLASS <> 'R'" )
    MakeFeatureLayer_management(NonState_fx, "Non_State_RuralClass" )
示例#16
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."
示例#17
0
def checkFeatureLocations(gdb):
    userMessage("Checking feature locations...")
    from os import path
    from arcpy import MakeFeatureLayer_management, SelectLayerByAttribute_management, SelectLayerByLocation_management, GetCount_management, Delete_management, da

    values = []
    #make sure feature are all inside authoritative boundary

    #get authoritative boundary
    authBound = path.join(gdb, "NG911", "AuthoritativeBoundary")
    ab = "ab"

    MakeFeatureLayer_management(authBound, ab)

    for dirpath, dirnames, filenames in da.Walk(gdb, True, '', False,
                                                ["FeatureClass"]):
        for filename in filenames:
            if filename != "AuthoritativeBoundary":
                #get full path name & create a feature layer
                fullPath = path.join(gdb, filename)
                fl = "fl"
                MakeFeatureLayer_management(fullPath, fl)

                #select by location to get count of features outside the authoritative boundary
                SelectLayerByLocation_management(fl, "INTERSECT", ab)
                SelectLayerByAttribute_management(fl, "SWITCH_SELECTION", "")
                #get count of selected records
                result = GetCount_management(fl)
                count = int(result.getOutput(0))

                #report results
                if count > 0:
                    fields = ("OBJECTID")
                    with da.SearchCursor(fl, fields) as rows:
                        for row in rows:
                            val = (today,
                                   "Feature not inside authoritative boundary",
                                   filename, "", row[0])
                            values.append(val)
                else:
                    userMessage(filename +
                                ": all records inside authoritative boundary")

                #clean up
                Delete_management(fl)

    userMessage("Completed check on feature locations")

    if values != []:
        RecordResults("fieldValues", values, gdb)
示例#18
0
def LatLongFields(fc, tbl, layer_name, table_name, workspace):
    #Updates the XY attributes values in the GIS database from the CANSYS table
    try:
        MakeFeatureLayer_management(fc, layer_name)
        MakeQueryTable_management(tbl, table_name, "USE_KEY_FIELDS",
                                  "CIIMS.CIIMS_VWCROSSINGGIS3.CROSSINGID", "#",
                                  "#")
        AddJoin_management(layer_name, "CROSSINGID", table_name, "CROSSINGID",
                           "KEEP_ALL")
        #select the rows where the CIIMS position has been changed
        SelectLayerByAttribute_management(
            layer_name, "NEW_SELECTION",
            "CIIMS.Static_Crossings.CROSSINGLATITUDE <> vwcrossings3.CROSSINGLATITUDE OR CIIMS.Static_Crossings.CROSSINGLONGITUDE <> vwcrossings3.CROSSINGLONGITUDE"
        )
        with da.Editor(
                workspace) as edit:  # @UnusedVariable @UndefinedVariable
            CalculateField_management(
                layer_name, 'CIIMS.Static_Crossings.CROSSINGLATITUDE',
                '!vwcrossings3.CROSSINGLATITUDE!', 'PYTHON_9.3')
            CalculateField_management(
                layer_name, 'CIIMS.Static_Crossings.CROSSINGLONGITUDE',
                '!vwcrossings3.CROSSINGLONGITUDE!', 'PYTHON_9.3')
            CalculateField_management(layer_name,
                                      "CIIMS.Static_Crossings.LOADDATE",
                                      "datetime.datetime.now( )", "PYTHON_9.3",
                                      "#")
        del layer_name, fc, table_name, tbl
    except ExecuteError:
        print(GetMessages(2))
        endingTime = datetime.datetime.now()
        ScriptStatusLogging('POINT_UPDATE_PROD.py', 'CIIMS.Static_Crossings',
                            scriptFailure, startingTime, endingTime,
                            GetMessages(2))
示例#19
0
def AnnualizeData(YearToAnnualize):
    annualLayer = gdb + "\KTRIPS.SDE.Ktrips_Annual"
    currentyYear = gdb + "\KTRIPS.SDE.Ktrips_CurrentYear"
    SelectYear = YearSelTest
    CalcYear = str(int(YearSelTest - 1))
    YearSelTest = "TripYear = '" + SelectYear + "'"
    if Exists("Check1"):
        Delete_management("Check1")
    MakeFeatureLayer_management(annualLayer, "Check1", YearSelTest)
    CheckExistence = GetCount_management("Check1")
    print CheckExistence
    if int(str(CheckExistence)) > 0:
        print "This source file info  is already in the target feature"
        runnext = False
    elif int(str(CheckExistence)) == 0:
        print 'the information is new for this source file and will be added.'
        runnext = True
        Append_management(currentyYear, annualLayer, "NO_TEST", "#")
        CalculateField_management(annualLayer, "TripYear", CalcYear,
                                  "PYTHON_9.3")
        TruncateTable_management(currentyYear)
    else:
        print 'something isnt working here'
    print runnext
    pass
示例#20
0
def FileChecker(ShapeFileDate, CheckLayer):
    #runnext = False
    SourceFileTxt = str(ShapeFileDate.replace("-", "_"))
    print ShapeFileDate
    selectdate = "Sourcefile = '" + SourceFileTxt + "'"
    print selectdate
    print CheckLayer
    if Exists("Check1"):
        Delete_management("Check1")
    try:
        MakeFeatureLayer_management(CheckLayer, "Check1", selectdate)
    except:
        MakeTableView_management(CheckLayer, "Check1", selectdate)
    CheckExistence = GetCount_management("Check1")
    print CheckExistence
    if int(str(CheckExistence)) > 0:
        print "This source file info  is already in the target feature"
        runnext = False
    elif int(str(CheckExistence)) == 0:
        print 'the information is new for this source file and will be added.'
        runnext = True
    else:
        print 'something isnt working here'
    print runnext
    return runnext
示例#21
0
def LatLongFields(fc, tbl, layer_name, table_name, workspace):
    #Updates the XY attributes  values in the GIS database from the CANSYS table
    try:
        MakeFeatureLayer_management(fc, layer_name)
        MakeTableView_management(tbl, table_name)
        AddJoin_management(layer_name, "CROSSINGID", table_name, "CROSSINGID",
                           "KEEP_ALL")
        SelectLayerByAttribute_management(
            layer_name, "NEW_SELECTION",
            "CIIMS.Static_Crossings.CROSSINGLATITUDE <> CIIMS.CIIMS_VWCROSSINGGIS3.CROSSINGLATITUDE OR CIIMS.Static_Crossings.CROSSINGLONGITUDE <> CIIMS.CIIMS_VWCROSSINGGIS3.CROSSINGLONGITUDE"
        )
        with da.Editor(workspace) as edit:
            CalculateField_management(
                layer_name, 'CIIMS.Static_Crossings.CROSSINGLATITUDE',
                '!CIIMS.CIIMS_VWCROSSINGGIS3.CROSSINGLATITUDE!', 'PYTHON_9.3')
            CalculateField_management(
                layer_name, 'CIIMS.Static_Crossings.CROSSINGLONGITUDE',
                '!CIIMS.CIIMS_VWCROSSINGGIS3.CROSSINGLONGITUDE!', 'PYTHON_9.3')
            CalculateField_management(layer_name,
                                      "CIIMS.Static_Crossings.LOADDATE",
                                      "datetime.datetime.now( )", "PYTHON_9.3",
                                      "#")
        del layer_name, fc, table_name, tbl
    except ExecuteError:
        print(GetMessages(2))
示例#22
0
def UpdateGISPROD_NON_STATE_Check():

    print "what route number should be updated?"
    try:
        RID = GetParameterAsText(0)
    except:
        RID = '460C0387500W0'
    RIDExp = "RID = '" + RID + "'"
    MakeTableView_management(r"C:\temp\Nusys_Check.gdb\NON_STATE_EVENTS",
                             "UpdateGISPROD", "#", "in_memory")
    # Replace a layer/table view name with a path to a dataset (which can be a layer file) or create the layer/table view within the script
    # The following inputs are layers or table views: "UpdateGISPROD"
    TableToTable_conversion(in_rows="UpdateGISPROD",
                            out_path="in_memory",
                            out_name="updatetblh",
                            RIDExp,
                            "#",
                            config_keyword="")
    AddIndex_management("updatetblh", "FID_NON_STATE_SYSTEM", "ID2", "UNIQUE",
                        "ASCENDING")
    MakeFeatureLayer_management(NonState, "NonStateAll")
    AddJoin_management("NonStateAll", "ID2", "updatetblh",
                       "FID_NON_STATE_SYSTEM", "KEEP_COMMON")
    print "Check the numbers one more time, and review"
    print "start Edit session on NON_STATE_SYSTEM now and type /'Calc()/' if it all looks good "
def reportExtensionForRAndHCheck(featuresToCheck):
    if Exists(featuresToCheck):
        featuresName = returnFeatureClass(featuresToCheck)
        errorsFromRAndH = 'RAndHErrorsAsFeatureLayer'
        MakeFeatureLayer_management(featuresToCheck, errorsFromRAndH)
        errorsFromRAndHResult = GetCount_management(errorsFromRAndH)
        errorsFromRAndHCount = int(errorsFromRAndHResult.getOutput(0))

        print("Roads & Highways Non-Monotonic Check output was found.")
        print(
            "Extending the errors report with information from the Roads & Highways Non-Monotonicity Check."
        )

        with open(errorReportCSV, 'a') as fHandle:
            fHandle.write('\n' + 'Roads & Highways checks follow: ' + '\n')
            fHandle.write(featuresName + ', ' + str(errorsFromRAndHCount) +
                          '\n')

        #errorsRHGDB = returnGDBOrSDEName(featuresToCheck)
        #errorsFeatureClass = returnFeatureClass(featuresToCheck)
        #previousWorkspace = env.workspace
        #env.workspace = errorsRHGDB

        #time.sleep(25)
        #print("Also adding ReviewUser and ReviewInfo text fields to the")
        #print("Roads & Highways Non-Monotonicity Check error output feature class.")
        #AddField_management(errorsFeatureClass, "OptionalInfo", "TEXT", "", "", 250, "ReviewingInfo", nullable)

        #env.workspace = previousWorkspace

    else:
        print("No Roads & Highways Non-Monotonic Check output found.")
        print("Will not add additional information to the errors report csv.")
def calculateMeasuresForLocalRoutes(routesToMeasure, subsetSelectionQuery):
    # Make a feature layer
    # Select it with the subsetSelectionQuery
    # If the number of selected features is at least 1
    # Then, run the calculateField_management calls for
    # the selected features.
    fcAsFeatureLayerForMeasuring = 'FCAsFeatureLayer_Measures'

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

    MakeFeatureLayer_management(routesToMeasure, fcAsFeatureLayerForMeasuring)

    SelectLayerByAttribute_management(fcAsFeatureLayerForMeasuring,
                                      'CLEAR_SELECTION')
    SelectLayerByAttribute_management(fcAsFeatureLayerForMeasuring,
                                      'NEW_SELECTION', subsetSelectionQuery)

    countResult = GetCount_management(fcAsFeatureLayerForMeasuring)
    intCount = int(countResult.getOutput(0))
    print('There were ' + str(intCount) +
          ' features selected in the fcAsFeatureLayerForMeasuring layer.')
    if intCount >= 1:
        expressionText1 = 0
        CalculateField_management(fcAsFeatureLayerForMeasuring, startMeasure,
                                  expressionText1, "PYTHON_9.3")
        expressionText2 = 'float("{0:.3f}".format(!Shape_Length! / 5280.00))'
        CalculateField_management(fcAsFeatureLayerForMeasuring, endMeasure,
                                  expressionText2, "PYTHON_9.3")
    else:
        print "Not calculating due to lack of selected features."
示例#25
0
def AttribFields(fc, tbl, layer_name, table_name, workspace):
    #Updates the crossing type attribute values in the GIS database from the CANSYS table.  I believe this should work but needs to be tested more.
    try:
        MakeFeatureLayer_management(fc, layer_name)
        MakeQueryTable_management(tbl, table_name, "USE_KEY_FIELDS",
                                  "CIIMS.CIIMS_VWCROSSINGGIS3.CROSSINGID", "#",
                                  "#")
        AddJoin_management(layer_name, "CROSSINGID", table_name, "CROSSINGID",
                           "KEEP_ALL")
        SelectLayerByAttribute_management(
            layer_name, "NEW_SELECTION",
            "CIIMS.Static_Crossings.CROSSINGTYPE <> vwcrossings3.CROSSINGTYPE")
        with da.Editor(
                workspace) as edit:  # @UnusedVariable @UndefinedVariable
            CalculateField_management(layer_name,
                                      'CIIMS.Static_Crossings.CROSSINGTYPE',
                                      '!vwcrossings3.CROSSINGTYPE!',
                                      'PYTHON_9.3')
            CalculateField_management(layer_name,
                                      "CIIMS.Static_Crossings.LOADDATE",
                                      "datetime.datetime.now( )", "PYTHON_9.3",
                                      "#")
        del layer_name, fc, table_name, tbl
        print "attrib fields updated for crossing type"
    except ExecuteError:
        print(GetMessages(2))
        endingTime = datetime.datetime.now()
        ScriptStatusLogging('POINT_UPDATE_PROD.py', 'CIIMS.Static_Crossings',
                            scriptFailure, startingTime, endingTime,
                            GetMessages(2))
示例#26
0
def select_edges_from_network(network, edges, directory, name):
    """
  Selects the edges in the given |network| path whose edge ids are in the given
      |edges| set, and saves a shapefile of the selected edges at the given
      location. Also saves a symbolized layer of the shapefile. Returns a
      mapping from the ids in the created file to ids in the original edges
      file, as recorded in the |edges| set. Also returns the path to the created
      shape file.
  """
    network_edges = getEdgePathFromNetwork(network)
    id_name = ("FID"
               if Describe(network_edges).extension == "shp" else "OBJECTID")
    query = ' OR '.join(
        ['"%s" = %d' % (id_name, edge_id) for edge_id in edges])
    selected_edges = "%s.shp" % join(directory, name)
    Select_analysis(network_edges, selected_edges, query)
    edges_layer = "%s.lyr" % join(directory, name)
    MakeFeatureLayer_management(in_features=selected_edges, out_layer=name)
    SaveToLayerFile_management(name, edges_layer, "ABSOLUTE")
    ApplySymbologyFromLayer_management(
        edges_layer,
        join(path[0], "Symbology_Layers\sample_edges_symbology.lyr"))
    add_layer_to_display(edges_layer)
    # TODO(mikemeko): this is a bit hacky, relies on the fact that ids appear in
    #     sorted order in tables, and that ids for shape files start from 0
    id_mapping = dict(zip(range(len(edges)), sorted(edges)))
    return id_mapping, selected_edges
示例#27
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)
示例#28
0
def calculateRampUniqueIdValues():
    layerForRampsSelection = 'layerForRampsSelection'
    MakeFeatureLayer_management(fcToCalculateTargetKeysIn,
                                layerForRampsSelection)
    selectionQuery = """ SourceRouteId LIKE '___X%' OR LRS_ROUTE_PREFIX = 'X' """
    updateFields = ['SourceRouteId', uniqueIdTarget]

    newCursor = daUpdateCursor(fcToCalculateTargetKeysIn, updateFields,
                               selectionQuery)

    for updateItem in newCursor:
        updateListItem = list(updateItem)
        keyToUse = ''
        if updateListItem[0] is not None:
            sourceIdFull = str(updateListItem[0])
            if len(sourceIdFull) >= 11:
                idToUse = sourceIdFull[9:11]
            else:
                idToUse = '00'
        else:
            idToUse = '00'

        updateListItem[1] = idToUse
        newCursor.updateRow(updateListItem)

    try:
        del newCursor
    except:
        pass
示例#29
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")
示例#30
0
def RouteCheck(RID):
    #when running this function, pass the RID/LRS KEY Value into the function to update the desired RID
    #RID is structured '030C0011800W0'
    #Class should be L, C, or RM
    print "what route number should be updated?"
    #RID = '030C0011800W0'
    Class = RID[3]
    if Class in ("R", "M"):
        Class = "RM"
    else:
        pass
    print RID
    RID_ = RID.replace('-', '_')
    RIDExp = "RID = '" + RID + "'"
    tablename = Class + RID_
    print RIDExp
    print "Updating route " + str(RID) + " in table " + str(RID_)
    if Exists("UpdateGISPROD"):
        print "this exists"
        pass
    else:
        AddTable = Class + "P_NON_STATE_EVENTS"
        MakeTableView_management(r"in_memory/" + AddTable, tablename + "_view",
                                 "#")
        MakeFeatureLayer_management(
            NonState, "NonStateUpdate",
            "((LRS_KEY LIKE '%C%' OR LRS_ROUTE_PREFIX = 'C') AND (MILEAGE_COUNTED = -1)) OR (LRS_DIR_OF_TRAVEL = 'P' and SURFACE = 'Propose')"
        )

    TableToTable_conversion(tablename + "_view", "in_memory", tablename,
                            RIDExp)
    if str(GetCount_management(tablename)) == '0':
        print "No Records to Calculate"
    else:
        try:
            RemoveJoin_management("NonStateUpdate")
        except:
            print "no NonStateUpdate, creating the NonStateSystem layer"
        MakeFeatureLayer_management(
            NonState, "NonStateUpdate",
            "(MILEAGE_COUNTED = -1 OR SURFACE = 'Propose')")
        AddJoin_management("NonStateUpdate", "ID2", tablename,
                           "FID_NON_STATE_SYSTEM", "KEEP_COMMON")
        print "Check the numbers one more time, and review"
        print "start Edit session on NonStateUpdate now and type RouteCalc(RID) if it all looks good"
    print "RteChk script completed successfully"