Esempio n. 1
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", "#")
Esempio n. 2
0
 def StateHighwaySystemDissolve():
     # Create an in-memory copy of state highay system routes based on LRS Route Prefix
     FeatureClassToFeatureClass_conversion(routesSourceCenterlines, "in_memory", inMemFeatureClassName, "LRS_ROUTE_PREFIX in ('I', 'U', 'K')")
     MakeFeatureLayer_management(inMemFeatureClass, stateSystemFeatureLayer)
     #about 941 records in Southwest Kansas had reverse mileages and need to be flipped
     #this should be corrected in the final conflation delivery
     #if it is not corrected, these route segments should be explored in more detail
     
     SelectLayerByAttribute_management(stateSystemFeatureLayer, "NEW_SELECTION", """("COUNTY_BEGIN_MP" > "COUNTY_END_MP" OR "STATE_BEGIN_MP" > "STATE_END_MP") AND "STATE_FLIP_FLAG" IS NULL""")
     CalculateField_management(stateSystemFeatureLayer, "STATE_FLIP_FLAG", """'Y'""", "PYTHON_9.3", "")
     
     SelectLayerByAttribute_management(stateSystemFeatureLayer, "NEW_SELECTION", """"STATE_FLIP_FLAG" = 'Y' """)
     FlipLine_edit(stateSystemFeatureLayer)
     #need to flip mileages where geometry was flipped so add fields
     AddField_management(stateSystemFeatureLayer, "F_CNTY_2", "DOUBLE", "", "", "", "", "NULLABLE", "NON_REQUIRED", "")
     AddField_management(stateSystemFeatureLayer, "T_CNTY_2", "DOUBLE", "", "", "", "", "NULLABLE", "NON_REQUIRED", "")
     AddField_management(stateSystemFeatureLayer, "F_STAT_2", "DOUBLE", "", "", "", "", "NULLABLE", "NON_REQUIRED", "")
     AddField_management(stateSystemFeatureLayer, "T_STAT_2", "DOUBLE", "", "", "", "", "NULLABLE", "NON_REQUIRED", "")
     
     #check if there are any state system segments where the to is greater than the from and flag them for review
     AddField_management(stateSystemFeatureLayer, "MileFlipCheck", "LONG", "", "", "", "", "NULLABLE", "NON_REQUIRED", "")
     
     CalculateField_management(stateSystemFeatureLayer, "F_CNTY_2", "!COUNTY_END_MP!", "PYTHON_9.3", "")
     CalculateField_management(stateSystemFeatureLayer, "T_CNTY_2", "!COUNTY_BEGIN_MP!", "PYTHON_9.3", "")
     CalculateField_management(stateSystemFeatureLayer, "F_STAT_2", "!STATE_END_MP!", "PYTHON_9.3", "")
     CalculateField_management(stateSystemFeatureLayer, "T_STAT_2", "!STATE_BEGIN_MP!", "PYTHON_9.3", "")
     
     # Switch selection and calculate mileages
     
     SelectLayerByAttribute_management(in_layer_or_view=stateSystemFeatureLayer, selection_type="SWITCH_SELECTION", where_clause="")
     
     CalculateField_management(stateSystemFeatureLayer, "F_CNTY_2", "!COUNTY_BEGIN_MP!", "PYTHON_9.3", "")
     CalculateField_management(stateSystemFeatureLayer, "T_CNTY_2", "!COUNTY_END_MP!", "PYTHON_9.3", "")
     CalculateField_management(stateSystemFeatureLayer, "F_STAT_2", "!STATE_BEGIN_MP!", "PYTHON_9.3", "")
     CalculateField_management(stateSystemFeatureLayer, "T_STAT_2", "!STATE_END_MP!", "PYTHON_9.3", "")
     #KDOT Direction should already be calculated, by running "DualCarriagweayIdentity.py" and updating the KDOT_DIRECTION_CALC to 1 where dual carriagway is found
     #Validation_CheckOverlaps can also help do identify sausage link/parallel geometries that may indicate dual carriagway, but that script does not yet 
     #identify and calculate the KDOT_DIRECTION_CALC flag.  It probably could with more development
     # Select the EB routes and change the LRS_Direction to WB
     
     SelectLayerByAttribute_management(stateSystemFeatureLayer, "NEW_SELECTION", """"KDOT_DIRECTION_CALC" = '1' AND "LRS_DIRECTION" = 'EB'""")
     CalculateField_management(stateSystemFeatureLayer, "LRS_DIRECTION", "'WB'", "PYTHON_9.3", "")
     #Select the SB routes to chante hte LRS direction to SB
     SelectLayerByAttribute_management(stateSystemFeatureLayer, "NEW_SELECTION", """"KDOT_DIRECTION_CALC" = '1' AND "LRS_DIRECTION" = 'NB'""")
     CalculateField_management(stateSystemFeatureLayer, "LRS_DIRECTION", "'SB'", "PYTHON_9.3", "")
     # Clear the selections
     SelectLayerByAttribute_management(stateSystemFeatureLayer, "CLEAR_SELECTION", "")
     
     #Calculate County LRS Key in CountyKey1 field for State Highway system
     #Need to add CountyKey2 for iteration 2, also go ahead and add new LRS Key format
     CalculateField_management(stateSystemFeatureLayer, "CountyKey1", """[LRS_COUNTY_PRE] + [LRS_ROUTE_PREFIX] + [LRS_ROUTE_NUM] + [LRS_ROUTE_SUFFIX] + [LRS_UNIQUE_IDENT] +"-" + [LRS_DIRECTION]""", "VB")
     CalculateField_management(stateSystemFeatureLayer, "StateKey1", """[LRS_ROUTE_PREFIX] + [LRS_ROUTE_NUM] + [LRS_ROUTE_SUFFIX] + [LRS_UNIQUE_IDENT] +"-" + [LRS_DIRECTION]""", "VB")
     
     #this is the dissolve - the output of this is a feature class which is clean for route creation of the state highway system
     Dissolve_management(stateSystemFeatureLayer, routesSourceDissolveOutput+"_Dissolve_EO", "CountyKey1;LRS_COUNTY_PRE;LRS_ROUTE_PREFIX;LRS_ROUTE_NUM;LRS_ROUTE_SUFFIX;LRS_UNIQUE_IDENT;LRS_DIRECTION", "F_CNTY_2 MIN;T_CNTY_2 MAX", "SINGLE_PART", "DISSOLVE_LINES")
     Dissolve_management(stateSystemFeatureLayer, routesSourceDissolveOutput+"_Unsplit_EO", "CountyKey1;LRS_COUNTY_PRE;LRS_ROUTE_PREFIX;LRS_ROUTE_NUM;LRS_ROUTE_SUFFIX;LRS_UNIQUE_IDENT;LRS_DIRECTION", "F_CNTY_2 MIN;T_CNTY_2 MAX", "SINGLE_PART", "UNSPLIT_LINES")
Esempio n. 3
0
def UniqueIDgen():
    for i in range(87, 88):
        c = str(i).zfill(3)
        #print "filling in unique Route IDs for county %s" %c
        expression = "LRS_ROUTE_PREFIX = 'L' AND LRS_COUNTY_PRE = '%s'" % c
        layer = "County" + c
        MakeFeatureLayer_management(target, layer, expression)
        #this part of the script performs a couple types of dissolves  to create a unique set of numbers in 4 characters for every route in a county
        #first, do an unsplit dissolve for each local road in the county based on the RD, STS, and POD fields
        #this creates nice segments from which to build the destination routes
        Dissolve_management(layer, "in_memory/" + layer + "d1",
                            "RD;STS;POD;LRS_COUNTY_PRE", "GCID COUNT",
                            "SINGLE_PART", "UNSPLIT_LINES")
        #add, calculate, and index a field for a join operation
        #cant add index to in memory database so skip that part
        AddField_management(layer + "d1", "ConCatRtName", "TEXT", "", "", "50",
                            "", "NULLABLE", "NON_REQUIRED", "")
        AddField_management(layer + "d1", "RouteNum1", "TEXT", "", "", "6", "",
                            "NULLABLE", "NON_REQUIRED", "")
        AddField_management(layer + "d1", "UniqueNum1", "TEXT", "", "", "3",
                            "", "NULLABLE", "NON_REQUIRED", "")
        CalculateField_management(
            layer + "d1", "ConCatRtName",
            """[LRS_COUNTY_PRE]&[RD] & [STS] & [POD] """, "VB", "")
        #dissolve the unsplit dissolve layer to a multipart, full dissolve to get unique road names
        Dissolve_management(layer + "d1", "in_memory/" + layer + "d2",
                            "ConCatRtName;RouteNum1", "", "MULTI_PART",
                            "DISSOLVE_LINES")
        #A spatial sort here might be nice
        #Calculate a unique 4 digit number for each road name
        #I'm just using the Object ID to calculate the unique number string, with a spatial sort another incrementation method would be needed
        #the road names should mostly be unique, so a spatial sort at this level would only be beneficial of there is POD field is the only road name distinction
        #otherwise an attribute sort would be sufficient, if necessary
        CalculateField_management("in_memory/" + layer + "d2", "RouteNum1",
                                  "str(!OBJECTID!).zfill(4)", "PYTHON_9.3", "")
        # add the unique id field and increment each duplicate road name part
        # calculate that unique number back to the split dissolve
        AddJoin_management(layer + "d1", "ConCatRtName", "County087d2",
                           "ConCatRtName", "KEEP_ALL")
        CalculateField_management(layer + "d1", layer + "d1.RouteNum1",
                                  "[" + layer + "d2.RouteNum1]", "VB", "")
        #AddField_management("in_memory/"+layer+"d2", "UniqueNum1", "TEXT", "", "", "3", "", "NULLABLE", "NON_REQUIRED", "")
        RemoveJoin_management(layer + "d1")
        #try this spatial sort thing here
        Sort_management("in_memory/" + layer + "d1",
                        "in_memory/" + layer + "d1_Sort",
                        "Shape ASCENDING;RouteNum1 ASCENDING", "LL")
        #now we run the incrementer to calcualte the unique ID's
        #the incrementer isnt working here, but it is calculating a unique ID on for the segments, and it is going it better and much faster than the join method
        #it might be better to use the incrementer to do this calculation on the sorted table, then figure out the unique ID
        Incrementer("in_memory/" + layer + "d1")
        Delete_management("in_memory/" + layer + "d1")
        Delete_management("in_memory/" + layer + "d2")
        Delete_management("in_memory/" + layer + "d2_Sort")
Esempio n. 4
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")
Esempio n. 5
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."
 def process(self, input_raster, input_points, field_name):
     """
     creates a new field called point_elevation on the feature class
     and populates it with values from the raster at the intersection
     """
     AddField_management(input_points, field_name, "FLOAT")
     calculatePointElevationField(input_points, input_raster, field_name)
Esempio n. 7
0
def createSourceRoutes123():
    from arcpy import CreateRoutes_lr, FlipLine_edit, AddField_management, FeatureClassToFeatureClass_conversion, SelectLayerByAttribute_management, CalculateField_management
    from KhubCode25.KhubCode25Config import localProFileGDBWorkspace

    fileformatDateStr = startDateTime.strftime("%Y%m%d")
    localfilegdb = localProFileGDBWorkspace + '\\' + 'KhubRoadCenterlines' + fileformatDateStr + '.gdb'
    FeatureClassToFeatureClass_conversion(
        localfilegdb + "\\All_Road_Centerlines", "in_memory",
        "SourceRoadCenterlines123",
        "LRS_ROUTE_SUFFIX in ( '0' , 'A' , 'B' , 'C' , 'Y' , 'S' ) AND LRS_ROUTE_PREFIX in ( 'I' , 'K' , 'U' )"
    )

    #flip backward routes
    #selecting by End less than begin mileage: 3/7/2018, 14948 routes need flipped
    #Selection by State Flip Flag = "Y" 3/7/2018, 14752 routes need flipped
    #for county_log_end < county_log_begin AND STATE_FLIP_FLAG NOT LIKE 'Y' there are 5 records, all 5 are K-14 on the mitchell/jewell county line
    #flip flag has become unreliable, do not use, just use mileage relationship

    AddField_management("SourceRoadCenterlines123", "TmpDblVal", "DOUBLE", "",
                        "", "", "", "NULLABLE", "NON_REQUIRED", "")
    SelectLayerByAttribute_management("SourceRoadCenterlines123",
                                      "NEW_SELECTION",
                                      "county_log_end < county_log_begin")

    CalculateField_management("SourceRoadCenterlines123", "TmpDblVal",
                              "!county_log_begin!", "PYTHON")
    CalculateField_management("SourceRoadCenterlines123", "county_log_begin",
                              "!county_log_end!", "PYTHON", "")
    CalculateField_management("SourceRoadCenterlines123", "county_log_end",
                              "!TmpDblVal!", "PYTHON", "")
    FlipLine_edit("SourceRoadCenterlines123")
    #once these lines have been flipped, we will flag them with an F in the state flip flag field
    CalculateField_management("SourceRoadCenterlines123", "STATE_FLIP_FLAG",
                              "'F'", "PYTHON")
Esempio n. 8
0
def copyfromstaged(lyrlist, admin, fdset, fcoutpath):
    for lyr in lyrlist:
        print(fcoutpath + admin + '.' + lyr)
        if Exists(fcoutpath + admin + '.' + lyr):
            DeleteFeatures_management(fcoutpath + admin + '.' + lyr)
            Append_management(ws + "/" + tempgdb + '/' + lyr,
                              fcoutpath + admin + '.' + lyr, "NO_TEST", "#")
            print "updated " + lyr + " in " + fcoutpath
        else:
            FeatureClassToFeatureClass_conversion(
                ws + "/" + tempgdb + '/' + lyr, fcoutpath, lyr)
            print "copied new " + lyr + " feature class to " + fcoutpath
            print " Check roles and privleges on this " + lyr + " at " + fcoutpath
        try:
            CalculateField_management(fcoutpath + admin + '.' + lyr,
                                      "NETWORKDATE",
                                      "datetime.datetime.now( )", "PYTHON_9.3",
                                      "#")
            print "copy date field updated"
        except:
            AddField_management(fcoutpath + admin + '.' + lyr, "NETWORKDATE",
                                "DATE")
            CalculateField_management(fcoutpath + admin + '.' + lyr,
                                      "NETWORKDATE",
                                      "datetime.datetime.now( )", "PYTHON_9.3",
                                      "#")
            print "copy date field added and updated"
            pass
    return
Esempio n. 9
0
def CITY ():
    itemname = "CITY"
    cantbl = itemname+"_ln_1"
    
    domname0 = 'CITY_TYPE'
    domstate = """IAL_DOMAIN = 'CITY_TYPE' AND IAL_END_DATE is NULL"""
    domfields = "CT_CITY_NBRR_INCORPORATED_CITY"
    domtbl = itemname+"_"+domfields
    disfields = domfields
    
    domname = "CT_CITY_NBR"
  
    MakeTableView_management("Database Connections/ATLASPROD.odc/V_NM_CTY",domname)
    TableToTable_conversion(domname, wsouttbl, domname+"R", "#")
    MakeTableView_management(wsouttbl+"//"+cantbl,itemname+"PD",""""NE_OWNER" IN ( 'EB' , 'NB' )""","#")
    DissolveRouteEvents_lr(itemname+"PD","LRS_ROUTE LINE Beg_State_Logmile End_State_Logmile", "CITY_NBR", wsouttbl+"//"+itemname+"_SD","LRS_ROUTE LINE Beg_State_Logmile End_State_Logmile","CONCATENATE","INDEX")
    AddIndex_management(wsouttbl+"//"+itemname+"_SD","CITY_NBR","CITY_NBR","NON_UNIQUE","NON_ASCENDING")
    AddField_management(wsouttbl+"//"+domname+"R", "CITY_NBR", "FLOAT", "#", "#", "#")
    CalculateField_management(wsouttbl+"//"+domname+"R", "CITY_NBR", "[CITY_NUMBER]", "VB")
    MakeTableView_management(wsouttbl+"//"+itemname+"_SD", itemname+"_view", "#")
    AddJoin_management(itemname+"_view", "CITY_NBR", wsouttbl+"//"+domname+"R", "CITY_NBR", "KEEP_ALL")
    TableToTable_conversion(itemname+"_view", wsouttbl, itemname+"_EVENT", "#")
    
    AssignDomainToField_management(wsouttbl+"//"+itemname+"_EVENT",domfields,domname0)
    
    DeleteField_management(wsouttbl+"//"+itemname+"_EVENT","CTYR_OBJECTID;CTYR_IIT_NE_ID;CTYR_IIT_INV_TYPE;CTYR_IIT_PRIMARY_KEY;CTYR_IIT_START_DATE;CTYR_IIT_DATE_CREATED;CTYR_IIT_DATE_MODIFIED;CTYR_IIT_CREATED_BY;CTYR_IIT_MODIFIED_BY;CTYR_IIT_ADMIN_UNIT;CTYR_IIT_NOTE;CTYR_IIT_PEO_INVENT_BY_ID;CTYR_NAU_UNIT_CODE;CTYR_IIT_END_DATE;CTYR_CITY_NBR")
    MakeRouteEventLayer_lr(wsouttbl+"//SMLRS","LRS_ROUTE",wsouttbl+"//"+itemname+"_EVENT","LRS_ROUTE LINE Beg_State_Logmile End_State_Logmile",itemname+"_ITEM","#","ERROR_FIELD","NO_ANGLE_FIELD","NORMAL","ANGLE","LEFT","POINT")
    FeatureClassToFeatureClass_conversion(itemname+"_ITEM", wsouttbl, itemname)
    DeleteField_management(wsouttbl+"//"+itemname,"CTYR_OBJECTID;CTYR_IIT_NE_ID;CTYR_IIT_INV_TYPE;CTYR_IIT_PRIMARY_KEY;CTYR_IIT_START_DATE;CTYR_IIT_DATE_CREATED;CTYR_IIT_DATE_MODIFIED;CTYR_IIT_CREATED_BY;CTYR_IIT_MODIFIED_BY;CTYR_IIT_ADMIN_UNIT;CTYR_IIT_NOTE;CTYR_IIT_PEO_INVENT_BY_ID;CTYR_NAU_UNIT_CODE;CTYR_IIT_END_DATE;CTYR_CITY_NBR")
    print "we have cities"
Esempio n. 10
0
def RecordResults(resultType, values, gdb):
    from os.path import join
    from arcpy import Exists, CreateTable_management, AddField_management
    from arcpy.da import InsertCursor

    if resultType == "template":
        tbl = "TemplateCheckResults"
    elif resultType == "fieldValues":
        tbl = "FieldValuesCheckResults"

    table = join(gdb, tbl)
    fieldList = []

    if not Exists(table):
        CreateTable_management(gdb, tbl)
        fieldInfo = getAddFieldInfo(table)

        for fi in fieldInfo:
            #add field with desired parameters
            AddField_management(fi[0], fi[1], fi[2], fi[3], fi[4], fi[5])
            #populate field list
            fieldList.append(fi[1])

    if fieldList == []:
        fieldList = getResultsFieldList(table)

    cursor = InsertCursor(table, fieldList)

    for row in values:
        cursor.insertRow(row)

    del cursor
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 fieldLogicToUse == fieldLogicToUseOptions[
            0] or fieldLogicToUse == fieldLogicToUseOptions[1]:
        KDOTKeyCalculation_NewFieldLogic()
    else:
        TranscendFieldCalculation()

    TranscendRampReplacement()

    if fieldLogicToUse == fieldLogicToUseOptions[
            0] or fieldLogicToUse == fieldLogicToUseOptions[1]:
        KDOTKeyCalculation_NewFieldLogic()
    else:
        TranscendFieldCalculation()
    LocalRouteReduction()
    def process(self, attach_table, out_folder):
        """
        creates a new field on the attachments table and uses
        extract attachments function to move the attachments to
        the output path.
        """

        # add a file name field
        AddField_management(attach_table, 'file_name', "TEXT", field_length=50)

        # run the task
        extract_attachments(attach_table, out_folder)
Esempio n. 13
0
def MSAG_CHECK_LRS1():
    #Add fields to model the MSAG Street keys and ranges
    AddField_management("RoadCenterline", "MSAG_KEY", "TEXT", "#", "#", "#",
                        "#", "NULLABLE", "NON_REQUIRED", "#")
    AddField_management("RoadCenterline", "MSAG_HIGH", "TEXT", "#", "#", "6",
                        "#", "NULLABLE", "NON_REQUIRED", "#")
    AddField_management("RoadCenterline", "MSAG_LOW", "TEXT", "#", "#", "6",
                        "#", "NULLABLE", "NON_REQUIRED", "#")

    #these are the rows where the left from address is the lowest valid address range number
    SelectLayerByAttribute_management(
        "RoadCenterline", "NEW_SELECTION",
        "(PARITY_L  in ( 'E' , 'O' ) AND L_F_ADD < R_T_ADD AND L_F_ADD < R_F_ADD AND L_F_ADD <= L_T_ADD ) OR (PARITY_R= 'Z' AND PARITY_L  in ( 'E' , 'O' ))"
    )
    CalculateField_management("RoadCenterline", "MSAG_LOW", "!L_F_ADD!",
                              "PYTHON_9.3", "#")

    #these are the rows where the right from address is the lowest valid address range number
    SelectLayerByAttribute_management(
        "RoadCenterline", "NEW_SELECTION",
        "(PARITY_R  in ( 'E' , 'O' ) AND R_F_ADD < R_T_ADD AND R_F_ADD < L_F_ADD AND R_F_ADD <= L_T_ADD ) OR (PARITY_L= 'Z' AND PARITY_R  in ( 'E' , 'O' ))"
    )
    CalculateField_management("RoadCenterline", "MSAG_LOW", "!R_F_ADD!",
                              "PYTHON_9.3", "#")

    #these are the rows where the left TO address is the lowest valid address range number
    SelectLayerByAttribute_management(
        "RoadCenterline", "NEW_SELECTION",
        "(PARITY_L  in ( 'E' , 'O' ) AND L_T_ADD < L_F_ADD AND L_T_ADD < R_T_ADD AND L_T_ADD <= R_T_ADD ) OR (PARITY_R= 'Z' AND PARITY_L  in ( 'E' , 'O' ))"
    )
    CalculateField_management("RoadCenterline", "MSAG_LOW", "!L_F_ADD!",
                              "PYTHON_9.3", "#")

    #these are the rows where the right TO address is the lowest valid address range number
    SelectLayerByAttribute_management(
        "RoadCenterline", "NEW_SELECTION",
        "(PARITY_R  in ( 'E' , 'O' ) AND R_F_ADD < R_T_ADD AND R_F_ADD < L_F_ADD AND R_F_ADD <= L_T_ADD ) OR (PARITY_L= 'Z' AND PARITY_R  in ( 'E' , 'O' ))"
    )
    CalculateField_management("RoadCenterline", "MSAG_LOW", "!R_F_ADD!",
                              "PYTHON_9.3", "#")
Esempio n. 14
0
def line_to_endpoints(input_fc, output_fc, id_field=None):
    """
    copies the endpoints of a feature class into a point
    feature class
    """

    # id field can either be provided or obtained automagically
    oid_field = id_field if id_field else Describe(input_fc).OIDFieldName

    # we add two custom fields to track the related id and the type of end point
    related_field = 'related_oid'
    type_field = 'point_type'
    AddField_management(output_fc, related_field, 'LONG')
    AddField_management(output_fc, type_field, 'TEXT', field_length=10)


    fields = [f.name for f in Describe(input_fc).fields if f.name not in ['SHAPE@', 'Shape', 'Shape_Length']]
    output_fields = fields + ['SHAPE@', related_field, type_field]

    #shape will be the last column selected
    search_cursor = SearchCursor(input_fc, fields + ['SHAPE@'])

    #our insert cursor
    insert_cursor = InsertCursor(output_fc, output_fields)

    #identify the spatial reference for projecting the geometry
    spatial_reference = Describe(output_fc).spatialReference

    for row in search_cursor:
        # project and store the geometry
        geom = row[len(row) - 1].projectAs(spatial_reference)

        # get the row id
        oid = row[fields.index(oid_field)]
        
        # insert two entries but with our new custom geometry
        insert_cursor.insertRow(row[:-1] + (geom.firstPoint, oid, 'START'))
        insert_cursor.insertRow(row[:-1] + (geom.lastPoint, oid, 'END'))

    del search_cursor, insert_cursor, spatial_reference
Esempio n. 15
0
def FormatGeocoding():
    fcname = "ReferencePosts"
    fcnameout = "CardinalRefposts"
    cardfcfull = gdbin + r"/" + fcnameout
    print cardfcfull
    from arcpy import AddField_management, CalculateField_management, FeatureClassToFeatureClass_conversion
    try:
        FeatureClassToFeatureClass_conversion(gdbin + r"/" + fcname, gdbin,
                                              fcnameout,
                                              """DIRECTION in (1, 3)""")
        AddField_management(cardfcfull, "Address", "TEXT", "", "", "55", "",
                            "NULLABLE", "NON_REQUIRED", "")
        AddField_management(cardfcfull, "CountyNum", "TEXT", "", "", "3", "",
                            "NULLABLE", "NON_REQUIRED", "")
    except:
        print "stuff exists"

    address = """Int([REFPOST]) &" "& [LRS]"""
    print address
    countynum = 'Left( [LRS_KEY],3)'
    CalculateField_management(cardfcfull, "CountyNum", countynum, "VB")
    CalculateField_management(cardfcfull, "Address", address, "VB")
Esempio n. 16
0
def LaneClass():
    MakeFeatureLayer_management(laneclass, 'LNCL',
                                "LANE_DIRECTION in ( 'EB' , 'NB' )")
    LocateFeaturesAlongRoutes_lr("LNCL", connection1 + "CCL_LRS_ROUTE",
                                 NewRouteKey, "0.1 FEET",
                                 connection1 + "LANECLASS_CCL",
                                 "CCL_LRS LINE CCL_BEGIN CCL_END", "ALL",
                                 "DISTANCE", "ZERO", "FIELDS", "M_DIRECTON")
    AddField_management(connection1 + "LANECLASS_CCL", "Lanes", "LONG")
    MakeTableView_management(laneclass, "LANECLASS_CCL_tbl",
                             "LANE_DIRECTION in ( 'EB' , 'NB' )")
    CalculateField_management(connection1 + "LANECLASS_CCL", "Lanes",
                              'Left([LNCL_CLS_ID_DESC],1)', "VB")
Esempio n. 17
0
def CheckRouteShapeLength():
    print "creating Non_State_Routes by the Shape Length"
    MakeFeatureLayer_management("C:/temp/Nusys_Check.gdb/Non_State_Classified", "BackwardSegs", "LRS_BACKWARDS = -1 AND MILEAGE_COUNTED = -1")
    FlipLine_edit("BackwardSegs") 
    Dissolve_management("Non_State_Classified", "C:/TEMP/Nusys_Check.gdb/TotalRouteShapeLength", "LRS_KEY", "", "MULTI_PART", "DISSOLVE_LINES")
    AddField_management("TotalRouteShapeLength", "Mileage", "DOUBLE", "", "", "", "", "NULLABLE", "NON_REQUIRED", "")
    CalculateField_management("TotalRouteShapeLength", "Mileage", "Round([LINEARGEOMETRY_Length] /5280, 3)", "VB", "")
    AddField_management("TotalRouteShapeLength", "Zero", "DOUBLE", "", "", "", "", "NULLABLE", "NON_REQUIRED", "")
    CalculateField_management("TotalRouteShapeLength", "Zero", "0", "VB", "")

    #MakeFeatureLayer_management(in_features="C:/temp/Nusys_Check.gdb/TotalRouteShapeLength", out_layer="ForwardRoutes", where_clause="LRS_BACKWARDS = 0")

    CreateRoutes_lr("TotalRouteShapeLength", "LRS_KEY", destdb+"\ShapeLengthRoute", "TWO_FIELDS", "Zero", "Mileage", "UPPER_LEFT", "1", "0", "IGNORE", "INDEX")
    #Flip them back to the original direction
    FlipLine_edit(in_features="BackwardSegs") 
    LocateFeaturesAlongRoutes_lr("Non_State_Classified", "ShapeLengthRoute", "LRS_KEY", "0 Feet", "C:/temp/Nusys_Check.gdb/NON_STATE_EVENTS", "RID LINE FMEAS TMEAS", "FIRST", "DISTANCE", "ZERO", "FIELDS", "M_DIRECTON")
    AddField_management("NON_STATE_EVENTS", "CheckBegin", "DOUBLE", "", "", "", "", "NULLABLE", "NON_REQUIRED", "")
    AddField_management("NON_STATE_EVENTS", "CheckEnd", "DOUBLE", "", "", "", "", "NULLABLE", "NON_REQUIRED", "")
    
    CalculateField_management("NON_STATE_EVENTS", "CheckBegin", "abs(!LRS_BEG_CNTY_LOGMILE!- !FMEAS!)", "PYTHON_9.3", "")
    CalculateField_management("NON_STATE_EVENTS", "CheckEnd", "abs(!LRS_END_CNTY_LOGMILE!- !TMEAS!)", "PYTHON_9.3", "")
   
    MakeRouteEventLayer_lr("ShapeLengthRoute", "LRS_KEY", "NON_STATE_EVENTS", "rid LINE fmeas tmeas", "LRS_Review_Events", "", "ERROR_FIELD", "NO_ANGLE_FIELD", "NORMAL", "ANGLE", "LEFT", "POINT")
Esempio n. 18
0
def STATE_INT():
    print "add intersect intersection points that are state - state intersections and interchanges"
    MakeFeatureLayer_management(interchange, 'INTR', "ON_STATE_NONSTATE = 'S'")
    LocateFeaturesAlongRoutes_lr("INTR", "CCL_LRS_ROUTE", NewRouteKey,
                                 "5 Feet", connection1 + "INTR_CCL",
                                 "CCL_LRS POINT MEASURE", "ALL", "DISTANCE",
                                 "ZERO", "FIELDS", "M_DIRECTON")
    MakeRouteEventLayer_lr("CCL_LRS_ROUTE", NewRouteKey,
                           connection1 + "INTR_CCL", "CCL_LRS POINT MEASURE",
                           "INTR_CCL_Events", "#", "ERROR_FIELD",
                           "ANGLE_FIELD", "NORMAL", "ANGLE", "LEFT", "POINT")
    AddField_management("INTR_CCL_Events", "CITY", "TEXT", "#", "#", "100")
    AddField_management("INTR_CCL_Events", "CITYNUMBER", "Long", "#", "#", "#")
    CalculateField_management("INTR_CCL_Events", "CITYNUMBER",
                              "int(!CCL_LRS![0:3])", "PYTHON_9.3")
    AddJoin_management("INTR_CCL_Events", "CITYNUMBER", citylimits,
                       "CITYNUMBER")
    #CalculateField_management("INTR_CCL_Events", schema+"INTR_CCL_Features.CITY", "!GIS_DEV.CITY_LIMITS.CITY!", "PYTHON_9.3") #Preupdate
    CalculateField_management("INTR_CCL_Events",
                              schema + "INTR_CCL_Features.CITY",
                              "!GIS.CITY_LIMITS.CITY!", "PYTHON_9.3")
    RemoveJoin_management("INTR_CCL_Events", "#")
    print "State_Int completed successfully."
Esempio n. 19
0
def CheckCRouteShapeLength():
    print "CreateNUSYSLocal() is a prerequisite function to this one "
    print "creating Non_State_Routes by the Shape Length"
    MakeFeatureLayer_management("C:/temp/Nusys_Check.gdb/Non_State_Classified", "BackwardSegs", "LRS_BACKWARDS = -1 AND (MILEAGE_COUNTED = -1 OR SURFACE = 'Propose')")
    FlipLine_edit("BackwardSegs") 
    Dissolve_management("Non_State_Classified", "C:/TEMP/Nusys_Check.gdb/TotalRouteShapeLength", "LRS_KEY", "", "MULTI_PART", "DISSOLVE_LINES")
    AddField_management("TotalRouteShapeLength", "Mileage", "DOUBLE", "", "", "", "", "NULLABLE", "NON_REQUIRED", "")
    CalculateField_management("TotalRouteShapeLength", "Mileage", "Round([Lineargeometry_Length] /5280, 3)", "VB", "")
    AddField_management("TotalRouteShapeLength", "Zero", "DOUBLE", "", "", "", "", "NULLABLE", "NON_REQUIRED", "")
    CalculateField_management("TotalRouteShapeLength", "Zero", "0", "VB", "")

    #MakeFeatureLayer_management(in_features="C:/temp/Nusys_Check.gdb/TotalRouteShapeLength", out_layer="ForwardRoutes", where_clause="LRS_BACKWARDS = 0")

    CreateRoutes_lr("TotalRouteShapeLength", "LRS_KEY", destdb+"\C_ShapeLengthRoute", "TWO_FIELDS", "Zero", "Mileage", "UPPER_LEFT", "1", "0", "IGNORE", "INDEX")
    #Flip them back to the original direction
    FlipLine_edit(in_features="BackwardSegs") 
    LocateFeaturesAlongRoutes_lr("Non_State_Classified", "ShapeLengthRoute", "LRS_KEY", "0 Feet", "C:/temp/Nusys_Check.gdb/C_NON_STATE_EVENTS", "RID LINE FMEAS TMEAS", "FIRST", "DISTANCE", "ZERO", "FIELDS", "M_DIRECTON")
    AddField_management("C_NON_STATE_EVENTS", "AdjBegin", "DOUBLE", "", "", "", "", "NULLABLE", "NON_REQUIRED", "")
    AddField_management("C_NON_STATE_EVENTS", "AdjEnd", "DOUBLE", "", "", "", "", "NULLABLE", "NON_REQUIRED", "")
    AddField_management("C_NON_STATE_EVENTS", "CHG_BEGLOG","DOUBLE", "", "", "", "", "NULLABLE", "NON_REQUIRED", "")
    AddField_management("C_NON_STATE_EVENTS", "CHG_ENDLOG","DOUBLE", "", "", "", "", "NULLABLE", "NON_REQUIRED", "")
    AddField_management("C_NON_STATE_EVENTS", "NEW_BEGLOG","DOUBLE", "", "", "", "", "NULLABLE", "NON_REQUIRED", "")
    AddField_management("C_NON_STATE_EVENTS", "NEW_ENDLOG","DOUBLE", "", "", "", "", "NULLABLE", "NON_REQUIRED", "")
    AddField_management("C_NON_STATE_EVENTS", "AdjLength","DOUBLE", "", "", "", "", "NULLABLE", "NON_REQUIRED", "")
    AddField_management("C_NON_STATE_EVENTS", "CHANGE","DOUBLE", "", "", "", "", "NULLABLE", "NON_REQUIRED", "")
    
    CalculateField_management(in_table="C_NON_STATE_EVENTS", field="AdjBegin", expression="round( !FMEAS! , 3 )", expression_type="PYTHON_9.3", code_block="")
    CalculateField_management(in_table="C_NON_STATE_EVENTS", field="AdjEnd", expression="round( !TMEAS! , 3 )", expression_type="PYTHON_9.3", code_block="")
    CalculateField_management(in_table="C_NON_STATE_EVENTS", field="CHG_BEGLOG", expression="[AdjBegin] - [LRS_BEG_CNTY_LOGMILE]", expression_type="VB", code_block="")
    CalculateField_management(in_table="C_NON_STATE_EVENTS", field="CHG_ENDLOG", expression="[AdjEnd] - [LRS_END_CNTY_LOGMILE]", expression_type="VB", code_block="")
    CalculateField_management(in_table="C_NON_STATE_EVENTS", field="NEW_BEGLOG", expression="[AdjBegin]", expression_type="VB", code_block="")
    CalculateField_management(in_table="C_NON_STATE_EVENTS", field="NEW_ENDLOG", expression="[AdjEnd]", expression_type="VB", code_block="")
    CalculateField_management(in_table="C_NON_STATE_EVENTS", field="AdjLength", expression="[AdjEnd] - [AdjBegin]", expression_type="VB", code_block="")
    CalculateField_management(in_table="C_NON_STATE_EVENTS", field="CHANGE", expression="abs([LENGTH] - [AdjLength])", expression_type="VB", code_block="")
       
    MakeRouteEventLayer_lr("C_ShapeLengthRoute", "LRS_KEY", "C_NON_STATE_EVENTS", "rid LINE fmeas tmeas", "C_LRS_Review_Events", "", "ERROR_FIELD", "NO_ANGLE_FIELD", "NORMAL", "ANGLE", "LEFT", "POINT")
Esempio n. 20
0
def UAB():
    itemname = "UAB"
    cantbl = itemname+"_ln_1"
    domname = "UABR"
    
    MakeTableView_management("Database Connections/ATLASPROD.odc/V_NM_UABR",domname)
    
    TableToTable_conversion(domname, wsouttbl, domname+"R", "#")
    MakeTableView_management(wsouttbl+"//"+cantbl,itemname+"PD",""""NE_OWNER" IN ( 'EB' , 'NB' )""","#")
    DissolveRouteEvents_lr(itemname+"PD","LRS_ROUTE LINE Beg_State_Logmile End_State_Logmile", "CITY_NBR", wsouttbl+"//"+itemname+"_SD","LRS_ROUTE LINE Beg_State_Logmile End_State_Logmile","CONCATENATE","INDEX")
    AddIndex_management(wsouttbl+"//"+itemname+"_SD","CITY_NBR","CITY_NBR","NON_UNIQUE","NON_ASCENDING")
    AddField_management(wsouttbl+"//"+domname+"R", "CITY_NBR", "FLOAT", "#", "#", "#")
    CalculateField_management(wsouttbl+"//"+domname+"R", "CITY_NBR", "[CITY_NUMBER]", "VB")
    MakeTableView_management(wsouttbl+"//"+itemname+"_SD", itemname+"_view", "#")
    AddJoin_management(itemname+"_view", "CITY_NBR", wsouttbl+"//"+domname+"R", "CITY_NBR", "KEEP_ALL")
    TableToTable_conversion(itemname+"_view", wsouttbl, domname+"J", "#")
    MakeRouteEventLayer_lr(wsouttbl+"//SMLRS","LRS_ROUTE",wsouttbl+"//"+domname+"J","LRS_ROUTE LINE Beg_State_Logmile End_State_Logmile",itemname+"_ITEM","#","ERROR_FIELD","NO_ANGLE_FIELD","NORMAL","ANGLE","LEFT","POINT")
    FeatureClassToFeatureClass_conversion(itemname+"_ITEM", wsouttbl, itemname)
    print "we have UABs"
Esempio n. 21
0
def AnnualStats(ShapeFileDate):
    env.overwriteOutput = 1
    #SourceFileTxt = str(ShapeFileDate[12:-4].replace("-", ""))
    #infileMonthly = yeardb+r"\Kansas\LRS"+SourceFileTxt
    qyear = ShapeFileDate[16:20]
    #try:
    #    Delete_management(yeardb+"/KTRIPS_MonthlySum_Statistics")
    #    Delete_management(yeardb+"/RunningTotal")
    #except:
    #    print "nothing deleted"
    #sumfile = gdb+"\INTERMODAL.DBO.KTRIPS_MonthlySum"
    sumfile = gdb + "\KTRIPS.SDE.KTRIPS_MonthlySum"
    whereclause = str(BuildWhereClauseLike(sumfile, "SourceFile", qyear))
    if Exists("ThisYearMonthly"):
        Delete_management("ThisYearMonthly")
    MakeFeatureLayer_management(sumfile, "ThisYearMonthly", whereclause, "#",
                                "#")
    Statistics_analysis("ThisYearMonthly",
                        "in_memory/KTRIPS_MonthlySum_Statistics",
                        "Join_Count SUM;Tonnage SUM",
                        "LRS_KEY;BEG_CNTY_LOGMILE;END_CNTY_LOGMILE")
    AddField_management("in_memory/KTRIPS_MonthlySum_Statistics", "TonMiles",
                        "DOUBLE", "#", "#", "#", "#", "NULLABLE",
                        "NON_REQUIRED", "#")
    CalculateField_management(
        "in_memory/KTRIPS_MonthlySum_Statistics", "TonMiles",
        "!SUM_Tonnage! /(!END_CNTY_LOGMILE! - !BEG_CNTY_LOGMILE!)",
        "PYTHON_9.3", "#")
    if Exists("KTRIPS_RunningTotal_CurentYear"):
        Delete_management("KTRIPS_RunningTotal_CurentYear")
    MakeRouteEventLayer_lr(cansys, "LRS_KEY",
                           "in_memory/KTRIPS_MonthlySum_Statistics",
                           "LRS_KEY LINE BEG_CNTY_LOGMILE END_CNTY_LOGMILE",
                           "KTRIPS_RunningTotal_CurentYear", "#",
                           "ERROR_FIELD", "NO_ANGLE_FIELD", "NORMAL", "ANGLE",
                           "LEFT", "POINT")
    CurrentYrStat = gdb + "\KTRIPS.SDE.Ktrips_CurrentYear"
    TruncateTable_management(CurrentYrStat)
    Append_management("KTRIPS_RunningTotal_CurentYear", CurrentYrStat,
                      "NO_TEST", "#", "")
    print "annual Stats have been recalculated from the latest Monthly Statistics"
    Delete_management("in_memory/KTRIPS_MonthlySum_Statistics")
Esempio n. 22
0
def polygon_to_point(input_fc, output_fc):
    """
    copies the centroid of polygon geometry to
    a point feature class
    """

    oid_field = Describe(input_fc).OIDFieldName
    new_field = 'Rel_OID'

    AddField_management(output_fc, new_field, 'Long')

    search_cursor = SearchCursor(input_fc, ['SHAPE@', oid_field])
    insert_cursor = InsertCursor(output_fc, ["SHAPE@", new_field])
    spatial_reference = Describe(output_fc).spatialReference

    for row in search_cursor:
        point = row[0].projectAs(spatial_reference).centroid
        oid = row[1]
        insert_cursor.insertRow([point, oid])

    del search_cursor, insert_cursor, spatial_reference
Esempio n. 23
0
def calibrationCCL():
    
    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_BEGIN","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(connection0+"/"+schema+"CCL_LRS_ROUTEbase","CCL_LRS",connection1+"CALIBRATION_POINTS_CCL","CCL_LRS","CCL_MEASURE",connection1+"CCL_LRS_ROUTE","DISTANCE","1 Feet","BETWEEN","NO_BEFORE","NO_AFTER","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)
Esempio n. 24
0
def recreateResultsTable():
    print "\n" + "Recreating the REPORT_INFO table."
    outTableGDB = r'Database Connections\[email protected]'
    outTableName = r'CrashLocation.GEO.REPORT_INFO'
    env.workspace = outTableGDB

    outTableFullPath = os.path.join(outTableGDB, outTableName)

    try:
        Delete_management(outTableFullPath)
    except:
        pass

    CreateTable_management(outTableGDB, outTableName)

    AddField_management(outTableName, "Name", "TEXT", "", "", "25")
    AddField_management(outTableName, "TotalAccidents", "TEXT", "", "", "12")
    # Changed these from 5 to 6 because 100.00 is 6 characters.
    AddField_management(outTableName, "GcPercent", "TEXT", "", "", "6")
    AddField_management(outTableName, "GcNKPercent", "TEXT", "", "", "6")
    AddField_management(outTableName, "OfsPercent", "TEXT", "", "", "6")
    AddField_management(outTableName, "OfsNKPercent", "TEXT", "", "", "6")

    return outTableFullPath
Esempio n. 25
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.")
Esempio n. 26
0
def compute_adjacency_list(input_points, input_network, id_attribute,
                           impedance_attribute, accumulator_attributes,
                           search_radius, output_location, adj_dbf_name):
    """
  |input_points|: point shape file marking entity (e.g. building) locations
  |input_network|: street network in which |input_points| is located
  |id_attribute|: the name of attribute that distinguishes between input points
  |impedance_attribute|: distance between neighboring nodes will be based on
      this attribute
  |accumulator_attributes|: distance between neighboring nodes will also be
      recorded for these attributes
  |search_radius|: the maximum extent for centrality computation
  |output_location|: adjacency list dbf will be saved here
  |adj_dbf_name|: the name of the adjacency list dbf
  """

    # Number of points in |input_points|
    input_point_count = int(GetCount_management(input_points).getOutput(0))

    # Make a directory to store all auxiliary files
    auxiliary_dir = join(output_location, AUXILIARY_DIR_NAME)
    if not Exists(auxiliary_dir):
        mkdir(auxiliary_dir)

    # Record the edge and junction source names of |input_network|
    junction_feature, edge_feature = network_features(input_network)

    # Calculate network locations if not already calculated
    test_input_point = UpdateCursor(input_points).next()
    locations_calculated = all(
        row_has_field(test_input_point, field)
        for field in NETWORK_LOCATION_FIELDS)
    if not locations_calculated:
        calculate_network_locations(input_points, input_network)

    # Calculate barrier cost per input point if not already calculated
    barrier_costs_calculated = row_has_field(test_input_point,
                                             trim(BARRIER_COST_FIELD))
    if not barrier_costs_calculated:
        AddMessage(BARRIER_COST_COMPUTATION_STARTED)
        # Add |BARRIER_COST_FIELD| column in |input_points|
        AddField_management(in_table=input_points,
                            field_name=trim(BARRIER_COST_FIELD),
                            field_type="DOUBLE",
                            field_is_nullable="NON_NULLABLE")

        # Initialize a dictionary to store the frequencies of (SnapX, SnapY) values
        xy_count = {}
        # A method to retrieve a (SnapX, SnapY) pair for a row in |input_points|
        get_xy = lambda row: (row.getValue(trim("SnapX")),
                              row.getValue(trim("SnapY")))

        barrier_pre_progress = Progress_Bar(input_point_count, 1,
                                            BARRIER_COST_PRE_PROCESSING)
        rows = UpdateCursor(input_points)
        for row in rows:
            snap_xy = get_xy(row)
            if snap_xy in xy_count:
                xy_count[snap_xy] += 1
            else:
                xy_count[snap_xy] = 1
            barrier_pre_progress.step()

        # Populate |BARRIER_COST_FIELD|, this will be used in OD matrix computation
        barrier_progress = Progress_Bar(input_point_count, 1,
                                        BARRIER_COST_COMPUTATION)
        rows = UpdateCursor(input_points)
        for row in rows:
            barrier_cost = BARRIER_COST / xy_count[get_xy(row)]
            row.setValue(trim(BARRIER_COST_FIELD), barrier_cost)
            rows.updateRow(row)
            barrier_progress.step()
        AddMessage(BARRIER_COST_COMPUTATION_FINISHED)

    # Necessary files
    od_cost_matrix_layer = join(auxiliary_dir, OD_COST_MATRIX_LAYER_NAME)
    od_cost_matrix_lines = join(od_cost_matrix_layer, OD_COST_MATRIX_LINES)
    temp_adj_dbf_name = TEMP_ADJACENCY_DBF_NAME(adj_dbf_name)
    temp_adj_dbf = join(output_location, temp_adj_dbf_name)
    adj_dbf = join(output_location, adj_dbf_name)
    partial_adj_dbf = join(auxiliary_dir, PARTIAL_ADJACENCY_LIST_NAME)
    polygons = join(auxiliary_dir, POLYGONS_SHAPEFILE_NAME)
    raster = join(auxiliary_dir, RASTER_NAME)
    polygons_layer = join(auxiliary_dir, POLYGONS_LAYER_NAME)
    input_points_layer = join(auxiliary_dir, INPUT_POINTS_LAYER_NAME)

    # Make sure none of these files already exists
    for path in [
            od_cost_matrix_layer, temp_adj_dbf, adj_dbf, partial_adj_dbf,
            polygons, raster, polygons_layer, input_points_layer,
            od_cost_matrix_lines
    ]:
        delete(path)

    # Cutoff radius for OD matrix computation
    cutoff_radius = 2 * BARRIER_COST + min(search_radius, BARRIER_COST / 2)

    # Compute OD matrix
    MakeODCostMatrixLayer_na(in_network_dataset=input_network,
                             out_network_analysis_layer=od_cost_matrix_layer,
                             impedance_attribute=impedance_attribute,
                             default_cutoff=str(cutoff_radius),
                             accumulate_attribute_name=accumulator_attributes,
                             UTurn_policy="ALLOW_UTURNS",
                             hierarchy="NO_HIERARCHY",
                             output_path_shape="NO_LINES")

    # Determine raster cell size
    points_per_raster_cell = OD_MATRIX_ENTRIES / input_point_count
    raster_cell_count = max(1, input_point_count / points_per_raster_cell)
    input_points_extent = Describe(input_points).Extent
    raster_cell_area = (input_points_extent.width *
                        input_points_extent.height / raster_cell_count)
    raster_cell_size = int(sqrt(raster_cell_area))

    # Construct |raster| from |input_points|
    PointToRaster_conversion(in_features=input_points,
                             value_field=id_attribute,
                             out_rasterdataset=raster,
                             cell_assignment="MOST_FREQUENT",
                             priority_field="NONE",
                             cellsize=str(raster_cell_size))

    # Construct |polygons| from |raster|
    RasterToPolygon_conversion(in_raster=raster,
                               out_polygon_features=polygons,
                               simplify="NO_SIMPLIFY",
                               raster_field="VALUE")

    # Export empty |od_cost_matrix_lines| to |temp_dbf| to start adjacency list
    TableToTable_conversion(in_rows=od_cost_matrix_lines,
                            out_path=output_location,
                            out_name=temp_adj_dbf_name)

    # Construct |polygons_layer| and |input_points_layer|
    for (feature, layer) in [(polygons, polygons_layer),
                             (input_points, input_points_layer)]:
        MakeFeatureLayer_management(in_features=feature, out_layer=layer)

    def add_locations(sub_layer, field_mappings=""):
        """
    |sub_layer|: one of "Origins", "Destinations", "Barrier Points"
    |field_mappings|: field mappings in addition to those for "Name" and
        "CurbApproach"
    """
        AddLocations_na(in_network_analysis_layer=od_cost_matrix_layer,
                        sub_layer=sub_layer,
                        in_table=input_points_layer,
                        field_mappings=("Name %s #; CurbApproach # 0; %s" %
                                        (id_attribute, field_mappings)),
                        search_tolerance=SEARCH_TOLERANCE,
                        search_criteria=("%s SHAPE; %s SHAPE;" %
                                         (junction_feature, edge_feature)),
                        append="CLEAR",
                        snap_to_position_along_network="SNAP",
                        snap_offset=SNAP_OFFSET)

    # OD cost matrix destinations
    AddMessage(ADDING_DESTINATIONS_STARTED)
    SelectLayerByLocation_management(in_layer=input_points_layer)
    add_locations("Destinations")
    AddMessage(ADDING_DESTINATIONS_FINISHED)

    # OD cost matrix point barriers
    AddMessage(ADDING_BARRIERS_STARTED)
    add_locations("Point Barriers",
                  ("FullEdge # 0; BarrierType # 2;"
                   "Attr_%s %s #;" %
                   (impedance_attribute, trim(BARRIER_COST_FIELD))))
    AddMessage(ADDING_BARRIERS_FINISHED)

    # Compute adjacency list, one raster cell at a time
    progress = Progress_Bar(raster_cell_count, 1, STEP_1)
    rows = UpdateCursor(polygons)
    for row in rows:
        # Select the current polygon
        SelectLayerByAttribute_management(in_layer_or_view=polygons_layer,
                                          selection_type="NEW_SELECTION",
                                          where_clause="FID = %s" %
                                          str(row.FID))

        # Origins
        SelectLayerByLocation_management(in_layer=input_points_layer,
                                         select_features=polygons_layer)
        add_locations("Origins")

        # Solve OD Cost matrix
        Solve_na(in_network_analysis_layer=od_cost_matrix_layer,
                 ignore_invalids="SKIP")

        # Add origin and destination fields to the adjacency list dbf
        for (index, field) in [(0, ORIGIN_ID_FIELD_NAME),
                               (1, DESTINATION_ID_FIELD_NAME)]:
            CalculateField_management(in_table=od_cost_matrix_lines,
                                      field=field,
                                      expression="!Name!.split(' - ')[%d]" %
                                      index,
                                      expression_type="PYTHON")

        # Record actual distance between neighboring nodes
        distance_field = "Total_%s" % impedance_attribute
        CalculateField_management(in_table=od_cost_matrix_lines,
                                  field=distance_field,
                                  expression="!%s! - 2 * %d" %
                                  (distance_field, BARRIER_COST),
                                  expression_type="PYTHON")

        # Append result to |temp_adj_dbf|
        TableToTable_conversion(in_rows=od_cost_matrix_lines,
                                out_path=auxiliary_dir,
                                out_name=PARTIAL_ADJACENCY_LIST_NAME)
        Append_management(inputs=partial_adj_dbf,
                          target=temp_adj_dbf,
                          schema_type="TEST")

        progress.step()

    # Copy data from |temp_adj_dbf| to |adj_dbf|
    Rename_management(in_data=temp_adj_dbf, out_data=adj_dbf)

    # Clean up
    for path in [
            od_cost_matrix_layer, partial_adj_dbf, polygons, raster,
            polygons_layer, input_points_layer, auxiliary_dir
    ]:
        delete(path)
Esempio n. 27
0
                    "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"

print "deriving CCL LRS starting points and calibrations"
CCLEnd = "!CCL.DBO.CITY_CONNECTING_LINK_STATE.MAX_END_STATE_LOGMILE!- !CCL.DBO.CITY_CONNECTING_LINK_STATE_D.MIN_BEG_STATE_LOGMILE!"
CCLBeg = "!CCL.DBO.CITY_CONNECTING_LINK_STATE.MIN_BEG_STATE_LOGMILE! - !CCL.DBO.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"
FeatureVerticesToPoints_management(LineFeatureClass,
                                   connection1 + "CALIBRATION_POINTS", "ALL")
LocateFeaturesAlongRoutes_lr(connection1 + "CALIBRATION_POINTS",
                             ReferenceRoute, ReferenceRouteKey, "1 Feet",
                             connection1 + "CP_MEAS", "RefKey POINT MEASURE",
Esempio n. 28
0
    """CDRS_ALERT_ROUTE_ID "CDRS_ALERT_ROUTE_ID" true false false 8 Double 10 38 ,First,#,KANROAD.CDRS_ALERT_ROUTE,CDRS_ALERT_ROUTE_ID,-1,-1;AlertID "AlertID" true true false 8 Double 10 38 ,First,#,KANROAD.CDRS_ALERT_ROUTE,ALERT_ID,-1,-1;AlertDate "AlertDate" true true false 36 Date 0 0 ,First,#,KANROAD.CDRS_ALERT_ROUTE,ALERT_DATE,-1,-1;AlertStatus "AlertStatus" true true false 8 Double 10 38 ,First,#,KANROAD.CDRS_ALERT_ROUTE,ALERT_STATUS,-1,-1;FeaClosed "FeaClosed" true true false 8 Double 10 38 ,First,#,KANROAD.CDRS_ALERT_ROUTE,FEA_CLOSED,-1,-1;District "District" true true false 8 Double 10 38 ,First,#,KANROAD.CDRS_ALERT_ROUTE,DISTRICT,-1,-1;Area "Area" true true false 8 Double 10 38 ,First,#,KANROAD.CDRS_ALERT_ROUTE,AREA,-1,-1;LRSKey "LRSKey" true true false 19 Text 0 0 ,First,#,KANROAD.CDRS_ALERT_ROUTE,BEG_LRS_KEY,-1,-1;LRSRoute "LRSRoute" true true false 12 Text 0 0 ,First,#,KANROAD.CDRS_ALERT_ROUTE,BEG_LRS_ROUTE,-1,-1;County "County" true true false 20 Text 0 0 ,First,#,KANROAD.CDRS_ALERT_ROUTE,BEG_COUNTY_NAME,-1,-1;CountyNumber "CountyNumber" true true false 8 Double 10 38 ,First,#,KANROAD.CDRS_ALERT_ROUTE,BEG_COUNTY_NUMBER,-1,-1;AlertType "AlertType" true true false 50 Text 0 0 ,First,#,KANROAD.CDRS_ALERT_ROUTE,ALERT_TYPE_TXT,-1,-1;AlertDescription "AlertDescription" true true false 50 Text 0 0 ,First,#,KANROAD.CDRS_ALERT_ROUTE,ALERT_DESC_TXT,-1,-1;BeginMP "BeginMP" true true false 8 Double 0 38 ,First,#,KANROAD.CDRS_ALERT_ROUTE,BEG_STATE_LOGMILE,-1,-1;BegRP "BegRP" true true false 8 Double 0 38 ,First,#,KANROAD.CDRS_ALERT_ROUTE,BEG_REF_POST,-1,-1;EndMP "EndMP" true true false 8 Double 0 38 ,First,#,KANROAD.CDRS_ALERT_ROUTE,END_STATE_LOGMILE,-1,-1;EndRP "EndRP" true true false 8 Double 10 38 ,First,#,KANROAD.CDRS_ALERT_ROUTE,END_REF_POST,-1,-1;Direction "Direction" true true false 12 Text 0 0 ,First,#,KANROAD.CDRS_ALERT_ROUTE,ALERT_DIREC_TXT,-1,-1;StartDate "StartDate" true true false 36 Date 0 0 ,First,#,KANROAD.CDRS_ALERT_ROUTE,START_DATE,-1,-1;CompDate "CompDate" true true false 36 Date 0 0 ,First,#,KANROAD.CDRS_ALERT_ROUTE,COMP_DATE,-1,-1;ExpireDate "ExpireDate" true true false 36 Date 0 0 ,First,#,KANROAD.CDRS_ALERT_ROUTE,EXPIRE_DATE,-1,-1;TimeDelay "TimeDelay" true true false 30 Text 0 0 ,First,#,KANROAD.CDRS_ALERT_ROUTE,TIME_DELAY_TXT,-1,-1;WZDetailId "WZDetailId" true true false 8 Double 10 38 ,First,#,KANROAD.CDRS_ALERT_ROUTE,CDRS_WZ_DETAIL_ID,-1,-1;WidthLimit "WidthLimit" true true false 8 Double 0 38 ,First,#,KANROAD.CDRS_ALERT_ROUTE,WIDTH_RESTRICTION,-1,-1;HeightLimit "HeightLimit" true true false 8 Double 0 38 ,First,#,KANROAD.CDRS_ALERT_ROUTE,VERT_RESTRICTION,-1,-1;WeightLimit "WeightLimit" true true false 8 Double 0 38 ,First,#,KANROAD.CDRS_ALERT_ROUTE,WEIGHT_RESTRICTION,-1,-1;SpeedLimit "SpeedLimit" true true false 8 Double 0 38 ,First,#,KANROAD.CDRS_ALERT_ROUTE,SPEED_RESTRICTION,-1,-1;INTERNAL_COMMENT "INTERNAL_COMMENT" true true false 4000 Text 0 0 ,First,#,KANROAD.CDRS_ALERT_ROUTE,INTERNAL_COMMENT,-1,-1;Comments "Comments" true true false 4000 Text 0 0 ,First,#,KANROAD.CDRS_ALERT_ROUTE,PUBLIC_COMMENT,-1,-1;PUBLIC_VIEW "PUBLIC_VIEW" true true false 8 Double 10 38 ,First,#,KANROAD.CDRS_ALERT_ROUTE,PUBLIC_VIEW,-1,-1;RPT_BY_NAME "RPT_BY_NAME" true true false 50 Text 0 0 ,First,#,KANROAD.CDRS_ALERT_ROUTE,RPT_BY_NAME,-1,-1;RPT_BY_PHONE "RPT_BY_PHONE" true true false 15 Text 0 0 ,First,#,KANROAD.CDRS_ALERT_ROUTE,RPT_BY_PHONE,-1,-1;RPT_BY_EMAIL "RPT_BY_EMAIL" true true false 40 Text 0 0 ,First,#,KANROAD.CDRS_ALERT_ROUTE,RPT_BY_EMAIL,-1,-1;ContactName "ContactName" true true false 50 Text 0 0 ,First,#,KANROAD.CDRS_ALERT_ROUTE,CONTACT_NAME,-1,-1;ContactPhone "ContactPhone" true true false 15 Text 0 0 ,First,#,KANROAD.CDRS_ALERT_ROUTE,CONTACT_PHONE,-1,-1;ContactEmail "ContactEmail" true true false 30 Text 0 0 ,First,#,KANROAD.CDRS_ALERT_ROUTE,CONTACT_EMAIL,-1,-1;OfficeName "OfficeName" true true false 30 Text 0 0 ,First,#,KANROAD.CDRS_ALERT_ROUTE,OFFICE_NAME,-1,-1;NEW_NOTIFICATION "NEW_NOTIFICATION" true true false 8 Double 10 38 ,First,#,KANROAD.CDRS_ALERT_ROUTE,NEW_NOTIFICATION,-1,-1;ALERT_INSERT_DT "ALERT_INSERT_DT" true true false 36 Date 0 0 ,First,#,KANROAD.CDRS_ALERT_ROUTE,ALERT_INSERT_DT,-1,-1;WebLink "WebLink" true true false 500 Text 0 0 ,First,#,KANROAD.CDRS_ALERT_ROUTE,ALERT_HYPERLINK,-1,-1;SITE_CR "SITE_CR" true true false 18 Text 0 0 ,First,#,KANROAD.CDRS_ALERT_ROUTE,SITE_CR,-1,-1;LINE_COLOR "LINE_COLOR" true true false 8 Double 0 32 ,First,#,KANROAD.CDRS_ALERT_ROUTE,LINE_COLOR,-1,-1;GIS_VIEW "GIS_VIEW" true true false 2 Short 0 2 ,First,#,KANROAD.CDRS_ALERT_ROUTE,GIS_VIEW,-1,-1;DCAM_COMMENT "DCAM_COMMENT" true true false 1024 Text 0 0 ,First,#,KANROAD.CDRS_ALERT_ROUTE,DCAM_COMMENT,-1,-1;DCAM_DATE "DCAM_DATE" true true false 12 Text 0 0 ,First,#,KANROAD.CDRS_ALERT_ROUTE,DCAM_DATE,-1,-1;DISPLAY_MAP "DISPLAY_MAP" true true false 2 Short 0 1 ,First,#,KANROAD.CDRS_ALERT_ROUTE,DISPLAY_MAP,-1,-1;OBJECTID "OBJECTID" true false false 4 Long 0 38 ,First,#,KANROAD.CDRS_ALERT_ROUTE,OBJECTID,-1,-1;ROUTE "ROUTE" true true false 10 Text 0 0 ,First,#,KANROAD.CDRS_ALERT_ROUTE,ROUTE,-1,-1""",
    "DEFAULTS")
MakeTableView_management(sdeCDRSWZ, "detail", "#", "#")
MakeFeatureLayer_management(stagews + "//CDRS_RAW", "ConstructionJoin")

print str(datetime.datetime.now()) + " Joining the Oracle CDRS WZ table"

AddJoin_management("ConstructionJoin", "CDRS_WZ_DETAIL_ID", "detail",
                   "CDRS_WZ_DETAIL_ID", "KEEP_ALL")
FeatureClassToFeatureClass_conversion(
    "ConstructionJoin", stagews, "CDRS_DETAIL", "CDRS_RAW.ALERT_STATUS <>  3"
)  #EDIT to remove Alert Status = 3 to remove suspended projects from CDRS 2013/11/13 - has to be here to be queryable

print str(
    datetime.datetime.now()) + " reformatting the Route name for US routes"
AddField_management("CDRS_DETAIL", "RouteName", "TEXT", "#", "10")
routenamed = '!BEG_LRS_ROUTE![0:1] +str(!BEG_LRS_ROUTE![3:6]).lstrip("0")'  # calculation expression
CalculateField_management("CDRS_DETAIL", "RouteName", routenamed, "PYTHON_9.3",
                          "#")
AddField_management("CDRS_DETAIL", "STATUS", "TEXT", "#", "10")
AddField_management("CDRS_DETAIL", "Alert_Status_I", "LONG", "#", "#")
CalculateField_management("CDRS_DETAIL", "Alert_Status_I", '!ALERT_STATUS!',
                          "PYTHON_9.3", "#")

print str(datetime.datetime.now()) + " reprojection processing"
DefineProjection_management("CDRS_DETAIL", labmertCC)
Project_management(
    "CDRS_DETAIL", "CDRS_Project",
    "PROJCS['WGS_1984_Web_Mercator_Auxiliary_Sphere',GEOGCS['GCS_WGS_1984',DATUM['D_WGS_1984',SPHEROID['WGS_1984',6378137.0,298.257223563]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]],PROJECTION['Mercator_Auxiliary_Sphere'],PARAMETER['False_Easting',0.0],PARAMETER['False_Northing',0.0],PARAMETER['Central_Meridian',0.0],PARAMETER['Standard_Parallel_1',0.0],PARAMETER['Auxiliary_Sphere_Type',0.0],UNIT['Meter',1.0]]",
    "WGS_1984_(ITRF00)_To_NAD_1983",
    "PROJCS['NAD_83_Kansas_Lambert_Conformal_Conic_Meters',GEOGCS['GCS_North_American_1983',DATUM['D_North_American_1983',SPHEROID['GRS_1980',6378137.0,298.257222101]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]],PROJECTION['Lambert_Conformal_Conic'],PARAMETER['false_easting',0.0],PARAMETER['false_northing',0.0],PARAMETER['central_meridian',-98.0],PARAMETER['standard_parallel_1',38.0],PARAMETER['standard_parallel_2',39.0],PARAMETER['scale_factor',1.0],PARAMETER['latitude_of_origin',38.5],UNIT['Meter',1.0]]"
Esempio n. 29
0
def main():
    tempDesc = Describe(fcToCalculateTargetKeysIn)
    print("Parsing the LRS values in " +
          returnFeatureClass(tempDesc.catalogPath) +
          " to figure out what the LRS_ROUTE_PREFIX should be.")
    currentFieldObjects = tempDesc.fields
    try:
        del tempDesc
    except:
        pass

    currentFieldNames = [x.name for x in currentFieldObjects]

    if targetRouteNumChanged not in currentFieldNames:
        AddField_management(fcToCalculateTargetKeysIn, targetRouteNumChanged,
                            "TEXT", "", "", 10, targetRouteNumChanged,
                            nullable)
        print("The " + str(targetRouteNumChanged) +
              " field was added to the " + str(fcToCalculateTargetKeysIn) +
              " layer.")
    else:
        print("The " + str(targetRouteNumChanged) +
              " field will not be added to the " +
              str(fcToCalculateTargetKeysIn) +
              " layer, because it already exists.")

    if targetCountyLRSKey not in currentFieldNames:
        AddField_management(fcToCalculateTargetKeysIn, targetCountyLRSKey,
                            "TEXT", "", "", 13, targetCountyLRSKey, nullable)
        print("The " + str(targetCountyLRSKey) + " field was added to the " +
              str(fcToCalculateTargetKeysIn) + " layer.")
    else:
        print("The " + str(targetCountyLRSKey) +
              " field will not be added to the " +
              str(fcToCalculateTargetKeysIn) +
              " layer, because it already exists.")

    if targetStateLRSKey not in currentFieldNames:
        AddField_management(fcToCalculateTargetKeysIn, targetStateLRSKey,
                            "TEXT", "", "", 9, targetStateLRSKey, nullable)
        print("The " + str(targetStateLRSKey) + " field was added to the " +
              str(fcToCalculateTargetKeysIn) + " layer.")
    else:
        print("The " + str(targetStateLRSKey) +
              " field will not be added to the " +
              str(fcToCalculateTargetKeysIn) +
              " layer, because it already exists.")

    MakeFeatureLayer_management(fcToCalculateTargetKeysIn,
                                targetKeyCalculationLayer)

    routePrefixTarget = "ROUTE_PREFIX_TARGET"
    lrsRouteNumSource = "LRS_ROUTE_NUM"
    lrsRouteNumTarget = "LRS_ROUTE_NUM_TARGET"
    lrsUniqueSource = "LRS_UNIQUE_IDENT"
    ##lrsUniqueSource2 = "LRS_UNIQUE_IDENT1"
    lrsUniqueTarget = "LRS_UNIQUE_TARGET"

    # County source to county target
    selectionQuery = """ SourceRouteId LIKE '___I%' OR LRS_ROUTE_PREFIX = 'I' """
    SelectLayerByAttribute_management(targetKeyCalculationLayer,
                                      "NEW_SELECTION", selectionQuery)
    CalculateField_management(targetKeyCalculationLayer, routePrefixTarget,
                              "'1'", "PYTHON_9.3")

    selectionQuery = """ SourceRouteId LIKE '___U%' OR LRS_ROUTE_PREFIX = 'U' """
    SelectLayerByAttribute_management(targetKeyCalculationLayer,
                                      "NEW_SELECTION", selectionQuery)
    CalculateField_management(targetKeyCalculationLayer, routePrefixTarget,
                              "'2'", "PYTHON_9.3")

    selectionQuery = """ SourceRouteId LIKE '___K%' OR LRS_ROUTE_PREFIX = 'K' """
    SelectLayerByAttribute_management(targetKeyCalculationLayer,
                                      "NEW_SELECTION", selectionQuery)
    CalculateField_management(targetKeyCalculationLayer, routePrefixTarget,
                              "'3'", "PYTHON_9.3")

    selectionQuery = """ SourceRouteId LIKE '___X%' OR LRS_ROUTE_PREFIX = 'X' """
    SelectLayerByAttribute_management(targetKeyCalculationLayer,
                                      "NEW_SELECTION", selectionQuery)
    CalculateField_management(targetKeyCalculationLayer, routePrefixTarget,
                              "'4'", "PYTHON_9.3")

    selectionQuery = """ SourceRouteId LIKE '___R%' OR LRS_ROUTE_PREFIX = 'R' """
    SelectLayerByAttribute_management(targetKeyCalculationLayer,
                                      "NEW_SELECTION", selectionQuery)
    CalculateField_management(targetKeyCalculationLayer, routePrefixTarget,
                              "'5'", "PYTHON_9.3")

    selectionQuery = """ SourceRouteId LIKE '___M%' OR LRS_ROUTE_PREFIX = 'M' """
    SelectLayerByAttribute_management(targetKeyCalculationLayer,
                                      "NEW_SELECTION", selectionQuery)
    CalculateField_management(targetKeyCalculationLayer, routePrefixTarget,
                              "'5'", "PYTHON_9.3")

    selectionQuery = """ SourceRouteId LIKE '___C%' OR LRS_ROUTE_PREFIX = 'C' """
    SelectLayerByAttribute_management(targetKeyCalculationLayer,
                                      "NEW_SELECTION", selectionQuery)
    CalculateField_management(targetKeyCalculationLayer, routePrefixTarget,
                              "'5'", "PYTHON_9.3")

    selectionQuery = """ SourceRouteId LIKE '___L%' OR LRS_ROUTE_PREFIX = 'L' """
    SelectLayerByAttribute_management(targetKeyCalculationLayer,
                                      "NEW_SELECTION", selectionQuery)
    CalculateField_management(targetKeyCalculationLayer, routePrefixTarget,
                              "'6'", "PYTHON_9.3")

    selectionQuery = """ SourceRouteId LIKE '___P%' OR LRS_ROUTE_PREFIX = 'P' """
    SelectLayerByAttribute_management(targetKeyCalculationLayer,
                                      "NEW_SELECTION", selectionQuery)
    CalculateField_management(targetKeyCalculationLayer, routePrefixTarget,
                              "'7'", "PYTHON_9.3")

    selectionQuery = """ SourceRouteId LIKE '___A%' OR LRS_ROUTE_PREFIX = 'A' """
    SelectLayerByAttribute_management(targetKeyCalculationLayer,
                                      "NEW_SELECTION", selectionQuery)
    CalculateField_management(targetKeyCalculationLayer, routePrefixTarget,
                              "'8'", "PYTHON_9.3")

    selectionQuery = """ SourceRouteId LIKE '___O%' OR LRS_ROUTE_PREFIX = 'O' """
    SelectLayerByAttribute_management(targetKeyCalculationLayer,
                                      "NEW_SELECTION", selectionQuery)
    CalculateField_management(targetKeyCalculationLayer, routePrefixTarget,
                              "'8'", "PYTHON_9.3")

    selectionQuery = """ SourceRouteId LIKE '___Q%' OR LRS_ROUTE_PREFIX = 'Q' """
    SelectLayerByAttribute_management(targetKeyCalculationLayer,
                                      "NEW_SELECTION", selectionQuery)
    CalculateField_management(targetKeyCalculationLayer, routePrefixTarget,
                              "'8'", "PYTHON_9.3")

    # For every Prefix:
    SelectLayerByAttribute_management(targetKeyCalculationLayer,
                                      "CLEAR_SELECTION", selectionQuery)
    SelectLayerByAttribute_management(targetKeyCalculationLayer,
                                      "SWITCH_SELECTION", selectionQuery)
    CalculateField_management(targetKeyCalculationLayer, lrsRouteNumTarget,
                              "!" + str(lrsRouteNumSource) + "!", "PYTHON_9.3")
    # Using the 2 characters for unique id. Local routes with more than 2 characters in unique id are probably errors.
    CalculateField_management(targetKeyCalculationLayer, lrsUniqueSource,
                              "!" + str(uniqueIdTarget) + "!", "PYTHON_9.3")

    # Since the above calculation might not be accurate for ramps, use this one instead.
    calculateRampUniqueIdValues()

    # Function that looks at the M and C routes and renumbers them if there are conflicts between
    # an M route and an R route, or between a C route and an R/M route.
    duplicateCheckForMAndC()

    # Calculate the full target route keys from their pieces.
    concatFullTargetKeys()
Esempio n. 30
0
Sort_management(env.workspace + "\\" + geographicData + ".shp",
                geographicDataOrder, [["ID", "ASCENDING"]])

# Id census tract
idField = "CD_GEOCODI"

# Position variable of demographic data
valueEt = 2

# New fields to gographich data
newFields = ["white", "black", "yellow", "parda", "indig"]

for field in newFields:

    # Add a new field in table of order geographic data
    AddField_management(geographicDataTable, field, "SHORT", 5)
    valueEt += 1
    print "Creating the field: " + field

    # Upadate the value of demographic data in geographic data
    with UpdateCursor(geographicDataOrder + ".shp",
                      (idField, field)) as geographicRows:

        for geographicRow in geographicRows:

            for demographicRow in demographicSorted:

                if str(geographicRow[0]) == str(demographicRow[0]):

                    try:
                        valueDemographicRow = int(demographicRow[valueEt])