コード例 #1
0
ファイル: concurrent_util.py プロジェクト: UGAROY/py-util
def find_overlap_segments_from_centerline(centerline, centerline_sequence, network_id_field, centerline_rid_field, network_id, overlap_segments):
    arcpy.MakeTableView_management(centerline_sequence, active_centerline_sequence_view, "%s = %s" % (network_id_field, network_id))
    roadway__count_dict = {}
    with arcpy.da.SearchCursor(active_centerline_sequence_view, "RoadwayIdGuid") as sCursor:
        for sRow in sCursor:
            roadway_guid = sRow[0]
            roadway__count_dict[roadway_guid] = roadway__count_dict.get(roadway_guid, 0) + 1
    concurrent_roadway_guids = [roadway_guid for roadway_guid, count in roadway__count_dict.items() if count >= 2]
    concurrent_roadway_guid_where_clause = build_string_in_sql_expression("RoadwayIdGuid", concurrent_roadway_guids)
    route__roadway_guids_dict = {}
    with arcpy.da.SearchCursor(active_centerline_sequence_view, [centerline_rid_field, "RoadwayIdGuid"],
                               concurrent_roadway_guid_where_clause) as sCursor:
        for sRow in sCursor:
            route_id = sRow[0]
            roadway_guid = sRow[1]
            if route_id not in route__roadway_guids_dict:
                route__roadway_guids_dict[route_id] = [roadway_guid]
            else:
                route__roadway_guids_dict[route_id].append(roadway_guid)
    arcpy.Delete_management(overlap_segments)
    index = 0
    for route_id, roadway_guids in route__roadway_guids_dict.items():
        roadway_guid_where_clause = build_string_in_sql_expression("RoadwayIdGuid", roadway_guids)
        arcpy.MakeFeatureLayer_management(centerline, centerline_layer, roadway_guid_where_clause)
        if index == 0:
            arcpy.UnsplitLine_management(centerline_layer, overlap_segments)
            index += 1
        else:
            arcpy.UnsplitLine_management(centerline_layer, unsplit_centerline)
            arcpy.Append_management(unsplit_centerline, overlap_segments)
コード例 #2
0
def calculatePerpendicularAngles(inputFeatureClass, outputFCLines, angleField,
                                 maxDistance, fieldID):

    #tempPoints = "in_memory\\TempPoints" #C:\\GIS\\StreamNetworkConfinementOutputGeodatabase01.gdb
    fcAngleLines0 = "in_memory\\Angle0"
    fcAngleLines180 = "in_memory\\Angle180"
    fcAngleMerge = "in_memory\\AngleMerge"

    #resetData(tempPoints)
    #arcpy.CopyFeatures_management(inputFeatureClass,tempPoints)
    arcpy.AddField_management(inputFeatureClass, "Angle0", "Double")
    arcpy.AddField_management(inputFeatureClass, "Angle180", "Double")
    arcpy.AddField_management(inputFeatureClass, "AngleDistance", "Double")

    arcpy.CalculateField_management(inputFeatureClass, "Angle0",
                                    "( !" + angleField + "! - 90 )*(-1)",
                                    "PYTHON")
    arcpy.CalculateField_management(inputFeatureClass, "Angle180",
                                    "!Angle0!+180", "PYTHON")
    arcpy.CalculateField_management(inputFeatureClass, "AngleDistance",
                                    str(maxDistance / 2), "PYTHON")

    #arcpy.AddXY_management(inputFeatureClass)

    resetData(fcAngleLines0)
    resetData(fcAngleLines180)
    arcpy.BearingDistanceToLine_management(inputFeatureClass, fcAngleLines0,
                                           "POINT_X", "POINT_Y",
                                           "AngleDistance", "#", "Angle0",
                                           "DEGREES", "GEODESIC", fieldID)
    arcpy.BearingDistanceToLine_management(inputFeatureClass, fcAngleLines180,
                                           "POINT_X", "POINT_Y",
                                           "AngleDistance", "#", "Angle180",
                                           "DEGREES", "GEODESIC", fieldID)

    resetData(fcAngleMerge)
    arcpy.Merge_management([fcAngleLines180, fcAngleLines0], fcAngleMerge)

    resetData(outputFCLines)
    arcpy.UnsplitLine_management(fcAngleMerge, outputFCLines, fieldID)

    return
コード例 #3
0
## now, need to add mergeNumber field
addMsgAndPrint('Updating arcs with MergeNumber values')
arcpy.AddField_management(tempCaf, 'MergeNumber','LONG')
# open update cursor
with arcpy.da.UpdateCursor(tempCaf, ['OBJECTID','MergeNumber']) as cursor:
    for row in cursor:
        if row[0] in arc2MergeNumberDict.keys():
            row[1] = arc2MergeNumberDict[row[0]]
        else:
            mergeNumber += 1
            row[1] = mergeNumber
            addMsgAndPrint('  OBJECTID = '+str(row[0])+' not in arc2MergeNumberDict')
        cursor.updateRow(row)
## merge tempCaf to CAF (and keep other fields!)
addMsgAndPrint('Unsplitting '+tempCaf+' to ContactsAndFaults')
arcpy.UnsplitLine_management(tempCaf,inCaf,compareFields,statFields)
## drop mergeNumber field
arcpy.DeleteField_management(inCaf,'MergeNumber')

addMsgAndPrint(str(numberOfRows(tempCaf))+' rows in old CAF, '+str(numberOfRows(inCaf))+' rows in new CAF')

addMsgAndPrint('Cleaning up')
addMsgAndPrint('  but not deleting tempCaf = '+tempCaf)
for fc in copyCaf,copy2Caf:   #,tempCaf:
    testAndDelete(fc)



"""
Possibilities:
1 arc at a node: Do nothing
コード例 #4
0
ファイル: common.py プロジェクト: mahdirajabi96/hsmpy3
def AddSegFromAddresses(AddressList, SegInput, RouteID, Output):
    import requests
    APIKey = 'AIzaSyCs80htAI4UAHHuF5m9IclsbMqg1FKxoEQ'

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

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

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

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

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

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

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

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

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

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

    arcpy.Delete_management(PntLayer)
    arcpy.Delete_management(SPJ)
    arcpy.Delete_management(SPJ2)
    arcpy.Delete_management(EventTable)
    arcpy.Delete_management(SegTable)
    arcpy.Delete_management(Overlay_Event_Layer)
    arcpy.Delete_management(Sort)
    arcpy.Delete_management(Final_Layer)
    arcpy.Delete_management(UnSplt)
コード例 #5
0
ファイル: SARN_method.py プロジェクト: njuRS/SARN-Method
layer3 = "delete_length" + RS_Polygon
arcpy.MakeFeatureLayer_management(RS_Polygon, layer3)
arcpy.SelectLayerByAttribute_management(
    layer3, "NEW_SELECTION",
    '"Shape_Area"<3000')  # you can modify this threshold
if int(arcpy.GetCount_management(layer3).getOutput(0)) > 0:
    arcpy.DeleteFeatures_management(layer3)
print "Get Raster to Polygon"

##Get Snapped DEM-modeled drainage network which coincided with RS-mapped river network
DEM_coincidewith_RS = "coincide_" + DEM
arcpy.Clip_analysis(DEM, RS_Polygon, DEM_coincidewith_RS)
split_DEM_coincidewith_RS = "split_" + DEM_coincidewith_RS
arcpy.SplitLine_management(DEM_coincidewith_RS, split_DEM_coincidewith_RS)
unsplit_DEM_coincidewith_RS = "unsplit_" + split_DEM_coincidewith_RS
arcpy.UnsplitLine_management(split_DEM_coincidewith_RS,
                             unsplit_DEM_coincidewith_RS)

##Get Snapped DEM-modeled drainage network which not coincided with RS-mapped river network
DEM_connect_RS = "connect_" + DEM
arcpy.Erase_analysis(DEM, RS_Polygon, DEM_connect_RS)
split_DEM_connect_RS = "split_" + DEM_connect_RS
arcpy.SplitLine_management(DEM_connect_RS, split_DEM_connect_RS)
unsplit_DEM_connect_RS = "unsplit_" + split_DEM_connect_RS
arcpy.UnsplitLine_management(split_DEM_connect_RS, unsplit_DEM_connect_RS)
print "Get coincided and connect line"

##Get dangle point of RS
RS_Point = "RS_Point_" + RS
arcpy.FeatureVerticesToPoints_management(unsplit_DEM_coincidewith_RS, RS_Point,
                                         "BOTH_ENDS")
print "Get RS_Point"
コード例 #6
0
def proclines(OID, currentreach, pointpath, reachfeaturefile, upreaches,
              downreaches, centerlinepath):
    arcpy.MakeFeatureLayer_management(reachfeaturefile, "reach_lyr")
    upreaches = list(filter(None, upreaches))
    downreaches = list(filter(None, downreaches))
    upreaches.extend(downreaches)
    upreaches.append(currentreach)
    field = arcpy.AddFieldDelimiters("reach_lyr", "NOID")
    unsplitfile = os.path.join(
        "in_memory",
        "unsplit_" + os.path.basename(reachfeaturefile) + str(OID).zfill(4))
    outpointfile_unsort = os.path.join(
        "in_memory",
        "unsort_" + os.path.basename(reachfeaturefile) + str(OID).zfill(4))
    outpointfile_sort = os.path.join(
        pointpath,
        os.path.basename(reachfeaturefile) + str(OID).zfill(4) + ".shp")
    centerlinefile = "centerline_" + os.path.basename(reachfeaturefile) + str(
        OID).zfill(4)
    bufferfile = "in_memory/buffer"
    for i in upreaches:
        selection = '{field} = {val}'.format(field=field, val=i)
        updown = arcpy.SelectLayerByAttribute_management(
            "reach_lyr", "ADD_TO_SELECTION", selection)

    arcpy.FeatureClassToFeatureClass_conversion(updown, "in_memory",
                                                centerlinefile)

    arcpy.UnsplitLine_management(in_features=os.path.join(
        "in_memory", centerlinefile),
                                 out_feature_class=unsplitfile,
                                 dissolve_field="",
                                 statistics_fields="")

    arcpy.GeneratePointsAlongLines_management(
        Input_Features=unsplitfile,
        Output_Feature_Class=outpointfile_unsort,
        Point_Placement="DISTANCE",
        Distance="100 Meters",
        Percentage="",
        Include_End_Points="END_POINTS")
    arcpy.CalculateField_management(in_table=outpointfile_unsort,
                                    field="ORIG_FID",
                                    expression="!OID!",
                                    expression_type="PYTHON_9.3",
                                    code_block="")

    arcpy.MakeFeatureLayer_management(outpointfile_unsort, "unsortedpoints")
    arcpy.MakeFeatureLayer_management(
        os.path.join("in_memory", centerlinefile), "centerline")
    arcpy.SelectLayerByAttribute_management(in_layer_or_view="unsortedpoints",
                                            selection_type="NEW_SELECTION",
                                            where_clause='"ORIG_FID" =1')
    arcpy.Buffer_analysis(in_features="unsortedpoints",
                          out_feature_class=bufferfile,
                          buffer_distance_or_field="10 Meters",
                          line_side="FULL",
                          line_end_type="ROUND",
                          dissolve_option="NONE",
                          dissolve_field="",
                          method="GEODESIC")

    min_value = arcpy.da.SearchCursor(
        os.path.join("in_memory", centerlinefile),
        "UPLAND_SKM",
        "{} IS NOT NULL".format("UPLAND_SKM"),
        sql_clause=(None, "ORDER BY {} ASC".format("UPLAND_SKM"))).next()[0]
    #print (min_value)
    arcpy.SelectLayerByLocation_management(
        in_layer="centerline",
        overlap_type="INTERSECT",
        select_features=bufferfile,
        search_distance="30 Meters",
        selection_type="NEW_SELECTION",
        invert_spatial_relationship="NOT_INVERT")
    selected_value = arcpy.da.SearchCursor(
        "centerline", "UPLAND_SKM",
        "{} IS NOT NULL".format("UPLAND_SKM")).next()[0]
    if min_value == selected_value:
        arcpy.Sort_management(in_dataset=outpointfile_unsort,
                              out_dataset=outpointfile_sort,
                              sort_field=[["ORIG_FID", "ASCENDING"]])
    else:
        arcpy.Sort_management(in_dataset=outpointfile_unsort,
                              out_dataset=outpointfile_sort,
                              sort_field=[["ORIG_FID", "DESCENDING"]])

    arcpy.CopyFeatures_management(
        os.path.join("in_memory", centerlinefile),
        os.path.join(centerlinepath, centerlinefile + ".shp"))
    arcpy.Delete_management("reach_lyr")
    arcpy.Delete_management("unsortedpoints")
    arcpy.Delete_management("centerline")
    arcpy.Delete_management("in_memory/buffer")
    arcpy.Delete_management(outpointfile_unsort)
    arcpy.Delete_management(unsplitfile)
    arcpy.Delete_management(os.path.join("in_memory", centerlinefile))

    return (upreaches)
コード例 #7
0
def IceCliffLocation(workspace,dem,tileDebarea,pixel,skinny,minSlope,n_iterations,L_e,alpha,beta_e,A_min,phi,gamma):
    import sys
    import os
    import arcpy
    from arcpy import env
    from arcpy.sa import Slope, ExtractByMask, Raster, SetNull, Int
    import matplotlib.pyplot as plt
    import numpy as np
    from numpy import array
    from scipy.optimize import curve_fit
    env.overwriteOutput = True

    try:
        import arcinfo
    except:
        sys.exit("ArcInfo license not available")
        arcpy.AddMessage("ArcInfo license not available")
    if arcpy.CheckExtension("spatial") == "Available":
        arcpy.CheckOutExtension("spatial")
    else:
        sys.exit("Spatial Analyst license not available")
        arcpy.AddMessage("Spatial Analyst license not available")
        
    #Parameters that should be stable:
    slopeLimit = 90 # slope detection capped at this value
    
    ## Loop for optimizing slope
    if str(workspace.split("\\")[-1]) == 'Final':
        n = []
        n.append(minSlope)        
    else:
        minSlope = 0
        n = np.arange(minSlope,slopeLimit,(slopeLimit-minSlope)/n_iterations)

    skipIteration = []
    for minSlope in n:
        
        # check for existing iterations if code has previously run but crashed. 
        if arcpy.ListFeatureClasses("*cliffMap*"):
            fcListPrior = arcpy.ListFeatureClasses("*cliffMap*")
            skipIteration = []
            for prior_i in fcListPrior:
                if int(prior_i[14:16]) == int("%02d" % (int(minSlope),)):
                    skipIteration = 1
        if skipIteration == 1:
            continue

        ## Ice Cliff code  
        if skinny == 'false':
            print 'IceCliffLocation script started...'
        if skinny == 'true':
            print 'skinny IceCliffLocation script started...'
            
        # Parameter that probably should be 0
        minProb = 0 # probability associated with minSlope.
        
        arcpy.CopyFeatures_management(tileDebarea, workspace+"\\del_debarea.shp")
        debarea_iteration = workspace+"\\del_debarea.shp"
        arcpy.env.snapRaster = dem
        outExtractSlope = ExtractByMask(dem, debarea_iteration)

        outExtractSlope.save("dem_extract.TIF")
        if int(round(float(str(arcpy.GetRasterProperties_management(dem, "CELLSIZEX"))))) == pixel:
            dem = "dem_extract.TIF"
        else:    
            arcpy.Resample_management("dem_extract.TIF", "dem_extractResample.TIF", pixel, "NEAREST")
            arcpy.env.snapRaster = dem
            print "DEM resampeld from "+str(int(round(float(str(arcpy.GetRasterProperties_management(dem, "CELLSIZEX"))))))+' to '+str(pixel)
            dem = "dem_extractResample.TIF"
        
        # Create slope raster
        outSlope = Slope(dem, "DEGREE", 1)
        outSlope.save("del_slope.TIF")
    
        # Isolate slope values above minSlope 
        outSetNull = SetNull("del_slope.TIF", "del_slope.TIF", "VALUE <= "+ str(minSlope))
        outSetNull.save("del_minSlope.TIF")       
    
        # Exit process if no cliffs exist
        nocliff = arcpy.GetRasterProperties_management(Int("del_minSlope.TIF"), "ALLNODATA")
        if int(str(nocliff)) == 1:
            print "No area with a slope above "+str(minSlope)+"."
        elif float(str(arcpy.GetRasterProperties_management('del_minSlope.TIF',"MAXIMUM"))) - float(str(arcpy.GetRasterProperties_management('del_minSlope.TIF',"MINIMUM"))) == 0:
            print "Only one pixel with a slope above "+str(minSlope)+", iteration skipped."
        else:
            minMean = float(str(arcpy.GetRasterProperties_management("del_minSlope.TIF", "MEAN"))) 
            minSD = float(str(arcpy.GetRasterProperties_management("del_minSlope.TIF", "STD"))) 

            areaSlope = minMean
            
            print 'areaSlope = ' + str(areaSlope)
            
            # Isolate slope values above areaSlope 
            outSetNull = SetNull("del_slope.TIF", "del_slope.TIF", "VALUE <= "+ str(areaSlope))
            outSetNull.save("del_areaSlope.TIF")
            arcpy.env.snapRaster = dem  
                        
            # Exit process if no cliffs exist
            nocliff = arcpy.GetRasterProperties_management(Int("del_areaSlope.TIF"), "ALLNODATA")
            if int(str(nocliff)) == 1:
                print "No area with a slope above "+str(areaSlope)+"."
            elif float(str(arcpy.GetRasterProperties_management("del_areaSlope.TIF","MAXIMUM"))) - float(str(arcpy.GetRasterProperties_management("del_areaSlope.TIF","MINIMUM"))) == 0:
                print "Only one pixel with a slope above "+str(areaSlope)+", iteration skipped."
            else: 
                seedSlope = minMean+minSD 
                print 'seedSlope = ' + str(seedSlope)
                
                # Isolate slope values above areaSlope 
                outSetNull = SetNull("del_slope.TIF", "del_slope.TIF", "VALUE <= "+ str(seedSlope))
                outSetNull.save("del_seedSlope.TIF")

                # Exit process if no cliffs exist
                nocliff = arcpy.GetRasterProperties_management(Int("del_seedSlope.TIF"), "ALLNODATA")
                if int(str(nocliff)) == 1:
                    print "No seed area with a slope above "+str(seedSlope)+"."
                else:                    
                    # to int speeds up computation time
                    outInt = Int("del_areaSlope.TIF")
                    outInt.save("del_minSlopeInt.TIF")
                    outInt = Int("del_seedSlope.TIF")
                    outInt.save("del_seedSlopeInt.TIF")                  
                        
                    arcpy.RasterToPolygon_conversion("del_minSlopeInt.TIF", "del_minCliffSlope.shp", "NO_SIMPLIFY", "VALUE")
                    arcpy.AddField_management("del_minCliffSlope.shp", "value", "SHORT", 1, "", "", "", "", "")
                    arcpy.Dissolve_management("del_minCliffSlope.shp", "del_minCliff_dissolve.shp", "value")
                    arcpy.MultipartToSinglepart_management("del_minCliff_dissolve.shp", "del_minCliff_explode.shp")
                    arcpy.AddField_management("del_minCliff_explode.shp",'Area','FLOAT')
                    rows = arcpy.UpdateCursor("del_minCliff_explode.shp")
                    for row in rows:
                        areacliff = row.shape.area
                        row.Area = areacliff 
                        rows.updateRow(row)
                    del row, rows
                    arcpy.CopyFeatures_management("del_minCliff_explode.shp", "min"+str("%02d" % (minSlope,))+"_CliffArea.shp")
                    
                    # skinny/non-skinny fix for ending iteration. 0 = no skip, 1 = skip
                    skip_iter = 0 
                    
                    # skinny ice cliffs, does not include ice cliff end extension to speed up computations
                    if skinny == 'true':
                        if arcpy.management.GetCount("del_minCliff_explode.shp")[0] == "0":
                            skip_iter = 1
                            print "No area within del_minCliff_explode.shp, skinny iteration skipped."
                        else:
                            # "_FinalCliffShape.shp" and "_cliffArea.shp" are the same if skinny == true
                            arcpy.CopyFeatures_management("del_minCliff_explode.shp", "min"+str("%02d" % (minSlope,))+"area"+str(int(areaSlope))+"_FinalCliffShape.shp")
                            # copy working .shp, used below
                            arcpy.CopyFeatures_management('del_minCliff_explode.shp', 'del_lineAndArea_area.shp')
                            arcpy.CalculateAreas_stats('del_minCliff_explode.shp', 'del_lineAndArea_area.shp')
                            arcpy.MakeFeatureLayer_management('del_lineAndArea_area.shp', 'tempLayer')
                            expression = 'F_AREA <=' + str((pixel**2)*A_min)
                            arcpy.SelectLayerByAttribute_management('tempLayer', 'NEW_SELECTION', expression)
                            arcpy.DeleteFeatures_management('tempLayer')
                            arcpy.Delete_management('tempLayer')

                    if skinny == 'false':    
                        # buffer in/out area to break up attached features
                        arcpy.Buffer_analysis("del_minCliff_explode.shp", "del_extendLineBuffer.shp", (pixel/2)-0.1, "FULL", "ROUND", "NONE")
    
                        # Generate ice cliff centerlines from Voronoi cells
                        if arcpy.management.GetCount("del_extendLineBuffer.shp")[0] == "0":
                            arcpy.CreateFeatureclass_management(workspace, 'del_lineAndArea_area.shp', "POLYGON","del_minCliff_dissolve.shp")
                            skip_iter = 1
                            print "No area within the criteria defined by seed area value "+str(seedSlope)+", iteration stopped before centerlines."
                        else:
                            arcpy.FeatureToLine_management("del_extendLineBuffer.shp","del_line.shp","","ATTRIBUTES")
                            arcpy.Densify_edit("del_line.shp", "","5", "", "")
                            arcpy.FeatureVerticesToPoints_management ("del_line.shp", "del_verti.shp", "ALL")
                            arcpy.CreateThiessenPolygons_analysis("del_verti.shp","del_voronoiCells.shp" ,"ONLY_FID") 
                            arcpy.RepairGeometry_management("del_voronoiCells.shp")
                            
                            #use geodatabase here due to unexpected error: "Invalid Topology [Duplicate segment.]"
                            arcpy.CreateFileGDB_management(workspace, "fGDB.gdb")
                            fgdb = workspace+"\\fGDB.gdb"
                            #arcpy.env.workspace = fgdb
                            arcpy.Clip_analysis(workspace+"\\del_voronoiCells.shp", workspace+"\\del_extendLineBuffer.shp", fgdb+"\\shp","")
                            arcpy.FeatureToLine_management(fgdb+"\\shp", workspace+"\\del_toLine.shp", "", attributes="ATTRIBUTES")
                            arcpy.Delete_management(fgdb)
                            #arcpy.env.workspace = workspace
                            
                            #arcpy.FeatureToLine_management("del_voronoiCellsClip.shp","del_toLine.shp", "", attributes="ATTRIBUTES")
                            arcpy.MakeFeatureLayer_management("del_toLine.shp", "tempLayer", "", "", "")
                            arcpy.SelectLayerByLocation_management("tempLayer", "CROSSED_BY_THE_OUTLINE_OF","del_minCliff_explode.shp","","NEW_SELECTION")
                            arcpy.DeleteFeatures_management("tempLayer")
                            arcpy.Delete_management("tempLayer")
                            arcpy.Intersect_analysis(["del_toLine.shp",'del_minCliff_explode.shp'],"del_lineIntersect.shp")
                            arcpy.Dissolve_management("del_lineIntersect.shp", "del_toLineDis.shp", "", "", "SINGLE_PART", "DISSOLVE_LINES")
                            arcpy.UnsplitLine_management("del_toLineDis.shp","del_unsplit.shp","Id")
                            arcpy.MakeFeatureLayer_management("del_unsplit.shp", "tempLayer2", "", "", "")
                            arcpy.SelectLayerByLocation_management("tempLayer2", "BOUNDARY_TOUCHES","del_minCliff_explode.shp","","NEW_SELECTION")
                            arcpy.DeleteFeatures_management("tempLayer2")
                            arcpy.Delete_management("tempLayer2")
                            arcpy.cartography.SimplifyLine("del_unsplit.shp","del_clineSimpExp.shp","POINT_REMOVE",10)
                            arcpy.AddField_management("del_clineSimpExp.shp", "value", "SHORT", 1, "", "", "", "", "")
                            arcpy.Dissolve_management("del_clineSimpExp.shp", "del_clineSimp.shp", "value")
                            arcpy.TrimLine_edit("del_clineSimp.shp", "8 meters", "KEEP_SHORT")
                            arcpy.CopyFeatures_management("del_unsplit.shp", "min"+str("%02d" % (minSlope,))+"_Centerlines.shp")
                            
                            #refine centerline for final map
                            if arcpy.management.GetCount("del_clineSimp.shp")[0] == "0":
                                arcpy.CreateFeatureclass_management(workspace, 'del_lineAndArea_area.shp', "POLYGON","del_minCliff_dissolve.shp")
                                skip_iter = 1
                                print "No area big enough to generate a centerline, iteration skipped."
                            else:                        
                            
                                # extend lines to capture cliff ends
                                count = 0
                                print "Extend line started..."
                                
                                jlist = [(pixel/2)-0.1] * int(round(L_e/(pixel/2)))
                                for j in jlist:
                                    #create buffer out to set the limit a line will be extended to
                                    arcpy.Buffer_analysis("del_clineSimp.shp", "del_clineSimpBuff1.shp", j, "FULL", "ROUND", "ALL")
                                    arcpy.PolygonToLine_management("del_clineSimpBuff1.shp","del_clineSimpBuff1line.shp")
                                    #merge centerline and bufferline
                                    arcpy.Merge_management(["del_clineSimp.shp","del_clineSimpBuff1line.shp"], "del_clineSimpBuff1merge_dis.shp")
                                    arcpy.Delete_management("del_clineSimp.shp")
                                    print "Extend line "+str(count)+" started..."
                                    arcpy.MultipartToSinglepart_management("del_clineSimpBuff1merge_dis.shp", "del_clineSimpBuff1merge.shp")
                                    arcpy.MakeFeatureLayer_management("del_clineSimpBuff1merge.shp", "lineLayer", "", "", "")
                                    arcpy.SelectLayerByLocation_management("lineLayer", "SHARE_A_LINE_SEGMENT_WITH", "del_clineSimpBuff1.shp", "", "NEW_SELECTION", "INVERT")
                                    arcpy.ExtendLine_edit("del_clineSimpBuff1merge.shp", str(j+1)+" meters", "EXTENSION")
                                    
                                    #select share a line segment with buffer to remove buffer
                                     
                                    arcpy.SelectLayerByLocation_management("lineLayer", "SHARE_A_LINE_SEGMENT_WITH", "del_clineSimpBuff1.shp", "", "NEW_SELECTION") 
                                    arcpy.DeleteFeatures_management("lineLayer")
                                    arcpy.Delete_management("lineLayer")
                                    arcpy.CopyFeatures_management("del_clineSimpBuff1merge.shp", "del_clineSimp.shp")
                                    arcpy.Delete_management("del_clineSimpBuff1.shp")
                                    arcpy.Delete_management("del_clineSimpBuff1line.shp")
                                    arcpy.Delete_management("del_clineSimpBuff1merge.shp")
                                    count = count + j                                
                                del j, jlist
        
                                #remove last short ribs with a lenght threhold then reattach centerlines that may have been split
                                # calculate lenght of each centerline
                                if arcpy.management.GetCount("del_clineSimp.shp")[0] == "0":
                                    arcpy.CreateFeatureclass_management(workspace, 'del_lineAndArea_area.shp', "POLYGON","del_minCliff_explode.shp")
                                    skip_iter = 1
                                    print "Centerline shape empty, iteration skipped."
                                else:
                                    arcpy.AddField_management("del_clineSimp.shp",'L','FLOAT')
                                    rows = arcpy.UpdateCursor("del_clineSimp.shp")
                                    for row in rows:
                                        areacliff = row.shape.length
                                        row.L = areacliff 
                                        rows.updateRow(row)
                                    del row, rows
                                    arcpy.CopyFeatures_management("del_clineSimp.shp", "min"+str("%02d" % (minSlope,))+"_extendedCenterlines.shp")
                                    
                                    # buffer out centerlines to capture end area removed in earlier buffer
                                    arcpy.Buffer_analysis("del_clineSimp.shp", "del_CliffCenterlineOut.shp", ((alpha*pixel*(2**(1/2)))/2), "FULL", "ROUND", "NONE")
            
                                    # define area with a slope less than that which defined "del_minCliff_dissolve.shp"
                                    edgeAreaSlope = areaSlope-beta_e
                                    print "Edge area defined by slope "+str(edgeAreaSlope)
                                    outSetNull = SetNull("del_slope.TIF", "del_slope.TIF", "VALUE <= "+ str(edgeAreaSlope))
                                    outSetNull.save("del_edgeSlope.TIF") 
                                   
                                    outInt = Int("del_edgeSlope.TIF")
                                    outInt.save("del_edgeSlopeInt.TIF")                    
                                    arcpy.RasterToPolygon_conversion("del_edgeSlopeInt.TIF", "del_edgeAreaSlope.shp", "NO_SIMPLIFY", "VALUE")
                                    arcpy.AddField_management("del_edgeAreaSlope.shp", "value", "SHORT", 1, "", "", "", "", "")
                                    arcpy.Dissolve_management("del_edgeAreaSlope.shp", "del_edgeAreaSlope_dissolve.shp", "value")
                                    arcpy.CopyFeatures_management("del_edgeAreaSlope_dissolve.shp", "min"+str("%02d" % (minSlope,))+"_edgeArea.shp")
                                    arcpy.Intersect_analysis (["del_edgeAreaSlope_dissolve.shp", "del_CliffCenterlineOut.shp"], "del_betaF_edgeArea.shp")
                        
                                    # merge buffered lines with buffered area                    
                                    arcpy.Merge_management(["del_betaF_edgeArea.shp", "del_minCliff_explode.shp"], "del_lineAndArea.shp")
                                    arcpy.AddField_management("del_lineAndArea.shp", "valueDis", "SHORT", 1, "", "", "", "", "")                    
                                    arcpy.Dissolve_management("del_lineAndArea.shp", "del_lineAndArea_dissolve1.shp", "valueDis")
                                    arcpy.RepairGeometry_management("del_lineAndArea_dissolve1.shp")
                                    # fill holes and remove shapes less than one pixel to avoid error from buffer tool
                                    arcpy.MultipartToSinglepart_management("del_lineAndArea_dissolve1.shp", "del_lineAndArea_explode1.shp")
                                    arcpy.CalculateAreas_stats("del_lineAndArea_explode1.shp", 'del_lineAndArea_area1.shp')
                                    arcpy.MakeFeatureLayer_management('del_lineAndArea_area1.shp', 'tempLayer')
                                    expression = 'F_AREA <' + str(pixel**2) # m2
                                    arcpy.SelectLayerByAttribute_management('tempLayer', 'NEW_SELECTION', expression)
                                    arcpy.DeleteFeatures_management('tempLayer')
                                    arcpy.Delete_management('tempLayer')
                                    arcpy.cartography.AggregatePolygons('del_lineAndArea_area1.shp', "del_lineAndArea_dissolve.shp", 1, 0, pixel**2, 'NON_ORTHOGONAL') 
                                                       
                                    arcpy.RepairGeometry_management("del_lineAndArea_dissolve.shp")
                                    # buffer in to reomve sliver geometries and out to make a diagonal set of single pixel shapes one feature
                                    arcpy.Buffer_analysis("del_lineAndArea_dissolve.shp", "del_lineAndArea_dissolveSmallBufferIn.shp", -0.5, "FULL", "ROUND", "ALL")
                                    arcpy.Buffer_analysis("del_lineAndArea_dissolveSmallBufferIn.shp", "del_lineAndArea_dissolveSmallBuffer.shp", 1, "FULL", "ROUND", "ALL")
                                    arcpy.MultipartToSinglepart_management("del_lineAndArea_dissolveSmallBuffer.shp", "del_lineAndArea_explode.shp")
                                    arcpy.CalculateAreas_stats('del_lineAndArea_explode.shp', 'del_lineAndArea_area.shp')
                                    arcpy.MakeFeatureLayer_management('del_lineAndArea_area.shp', 'tempLayer')
                                    expression = 'F_AREA <=' + str((pixel**2)*A_min)
                                    arcpy.SelectLayerByAttribute_management('tempLayer', 'NEW_SELECTION', expression)
                                    arcpy.DeleteFeatures_management('tempLayer')
                                    arcpy.Delete_management('tempLayer')
                                    
                                    if arcpy.management.GetCount("del_lineAndArea_area.shp")[0] == "0":
                                        print "del_lineAndArea_area.shp empty, iteration stopped."
                                        skip_iter = 1
                                    else:
                                        arcpy.AddField_management("del_lineAndArea_area.shp", "value", "SHORT", 1, "", "", "", "", "")
                                        arcpy.CopyFeatures_management('del_lineAndArea_area.shp', "min"+str("%02d" % (minSlope,))+"area"+str(int(areaSlope))+"_FinalCliffShape.shp")                         
                    if skip_iter == 0:
                        # CDF for values between minSlope and maxSlope
                        outSetNull = SetNull("del_slope.TIF", "del_slope.TIF", "VALUE >= "+ str(minSlope))
                        outSetNull.save("del_min.TIF")
                        arcpy.RasterToFloat_conversion("del_min.TIF", "del_min.flt")
                        minsl = Raster('del_min.flt')
                        slopemin = minsl*0.0
                        slopemin.save('del_minSl.TIF')            
                            
                        outSetNull = SetNull("del_slope.TIF", "del_slope.TIF", "VALUE > "+ str(seedSlope))
                        outSetNull = SetNull(outSetNull, outSetNull, "VALUE < "+ str(minSlope))
                        outSetNull.save("del_mid.TIF")
                        arcpy.RasterToFloat_conversion("del_mid.TIF", "del_mid.flt")
                        midsl = Raster('del_mid.flt')
                        b = (1-(((1-minProb)/(seedSlope-minSlope))*seedSlope))
                        slopemid = (((1-minProb)/(seedSlope-minSlope))*midsl)+b
                        arcpy.env.snapRaster = dem
                        slopemid.save('del_midSl.TIF')
                        arcpy.env.snapRaster = dem
        
                        outSetNull = SetNull("del_slope.TIF", "del_slope.TIF", "VALUE <= "+ str(seedSlope))
                        outSetNull.save("del_max.TIF")
                        arcpy.RasterToFloat_conversion("del_max.TIF", "del_max.flt")
                        maxsl = Raster('del_max.flt')
                        slopemax = maxsl*0.0+1.0
                        arcpy.env.snapRaster = dem
                        slopemax.save('del_maxSl.TIF')
                        arcpy.env.snapRaster = dem
                                
                        arcpy.MosaicToNewRaster_management("del_minSl.TIF;del_midSl.TIF;del_maxSl.TIF", workspace, "del_cliffProbabilitySlope.TIF", "", "32_BIT_FLOAT", "", "1", "LAST","FIRST")
                        arcpy.env.snapRaster = dem
        
                        # extract cliff probability and apply reduction factor to area outside of buffer.shp
                        if arcpy.management.GetCount("del_lineAndArea_area.shp")[0] == "0":
                            print "del_lineAndArea_area.shp is empty, did not create: CliffProbability_betai" + str("%02d" % (int(minSlope),)) + "betaA"  + str(int(areaSlope))+".TIF"
                        else:  
                            outExtractSlope = ExtractByMask("del_cliffProbabilitySlope.TIF", "del_lineAndArea_area.shp")
                            outExtractSlope.save("del_final_cliffs_found.TIF")
                            
                            arcpy.RasterToFloat_conversion("del_cliffProbabilitySlope.TIF", "del_CliffProbabilitySlope.flt")
                            CliffProbabilitySlope = Raster('del_CliffProbabilitySlope.flt')
                            CliffProbabilitySlopeREDUCED = CliffProbabilitySlope*phi
                            arcpy.env.snapRaster = dem
                            CliffProbabilitySlopeREDUCED.save('del_CliffProbabilitySlopeREDUCED.TIF')
            
                            arcpy.MosaicToNewRaster_management("del_final_cliffs_found.TIF;del_CliffProbabilitySlopeREDUCED.TIF", workspace, "CliffProbability_betai" + str("%02d" % (int(minSlope),)) + "betaA"  + str(int(areaSlope))+".TIF", "", "32_BIT_FLOAT", "", "1", "FIRST","FIRST")
                            arcpy.env.snapRaster = dem
                            
                            del CliffProbabilitySlope
                            del CliffProbabilitySlopeREDUCED
                                                       
                        del minsl
                        del midsl
                        del maxsl


                ## ----------------------------------
                ## Compute percent cliff in total spatial domain

                cliff_area_sum = 0
                debris_area_sum = 0
                Perc_Cliff = 0
                arcpy.CalculateAreas_stats(debarea_iteration, 'del_debris_area.shp')
                with arcpy.da.SearchCursor('del_debris_area.shp', ['F_AREA']) as cursor:
                    for row in cursor:
                        debris_area_sum += row[0]                
                                
                if os.path.isfile(workspace+'\\del_lineAndArea_area.shp') == False:
                    print "'del_lineAndArea_area.shp'does not exist."
                elif arcpy.management.GetCount('del_lineAndArea_area.shp')[0] == "0":
                    print "No area within 'del_lineAndArea_area.shp'."
                else:
                    with arcpy.da.SearchCursor('del_lineAndArea_area.shp', ['F_AREA']) as cursor:
                        for row in cursor:
                            cliff_area_sum += row[0]
                    Perc_Cliff = (cliff_area_sum/debris_area_sum)*100
                    arcpy.Dissolve_management("del_lineAndArea_area.shp", 'cliffMap_betai' + str("%02d" % (int(minSlope),)) + 'betaA' + str(int(areaSlope)) + '.shp', "value")
                    arcpy.AddField_management('cliffMap_betai' + str("%02d" % (int(minSlope),)) + 'betaA' + str(int(areaSlope)) + '.shp','minSlope','FLOAT')
                    arcpy.AddField_management('cliffMap_betai' + str("%02d" % (int(minSlope),)) + 'betaA' + str(int(areaSlope)) + '.shp','Area_Cliff','FLOAT')
                    arcpy.AddField_management('cliffMap_betai' + str("%02d" % (int(minSlope),)) + 'betaA' + str(int(areaSlope)) + '.shp','Area_Deb','FLOAT')
                    
                    arcpy.AddField_management('cliffMap_betai' + str("%02d" % (int(minSlope),)) + 'betaA' + str(int(areaSlope)) + '.shp','Perc_Cliff','FLOAT')
                    rows = arcpy.UpdateCursor('cliffMap_betai' + str("%02d" % (int(minSlope),)) + 'betaA' + str(int(areaSlope)) + '.shp')
                    for row in rows:
                        row.setValue('Area_Cliff', cliff_area_sum)
                        row.setValue('Area_Deb', debris_area_sum)
                        row.setValue('minSlope', minSlope)
                        row.setValue('Perc_Cliff', Perc_Cliff)
                        rows.updateRow(row)
                    del row, rows
                                     
                    print 'IceCliffLocation script [minSlope: ' + str("%02d" % (int(minSlope),)) + ' areaSlope: ' + str(int(areaSlope))+ '] done...'
                                         
        rasterList = arcpy.ListRasters("*del*")
        for raster in rasterList:
            arcpy.Delete_management(raster)
        del raster
        del rasterList

        fcList = arcpy.ListFeatureClasses("*del*")
        for fc in fcList:
            arcpy.Delete_management(fc)
        del fc
        del fcList

        print "intermediate files deleted"
            
    del minSlope
    del n
    
    if str(workspace.split("\\")[-1]) == 'Final':
        print "Script complete"        
    else:
        initialSlope_doubles = []
        percentCliffs_doubles = []
        initialSlope = []
        percentCliffs = []
        xfit = []
        yfit = []
        fcList = []
        arr = []
        fcList = arcpy.ListFeatureClasses("*cliffMap*")
        arcpy.Merge_management(fcList, "mergedSolutions.shp")
        arr = arcpy.da.TableToNumPyArray("mergedSolutions.shp", ('Perc_Cliff','minSlope'))
        arcpy.Delete_management("del_mergedSolutions.shp")
        initialSlope_doubles = [row[1] for row in arr]
        percentCliffs_doubles = [row[0] for row in arr]
        
        #remove rows that are repeated due to (possible) earlier tiled dissolve from insufficient memory 
        for i,j in enumerate(initialSlope_doubles):
            if j != initialSlope_doubles[(i-1) % len(initialSlope_doubles)]:
                initialSlope.append(j)
        del i,j
        for i,j in enumerate(percentCliffs_doubles):
            if j != percentCliffs_doubles[(i-1) % len(percentCliffs_doubles)]:
                percentCliffs.append(j)
        del i,j
                
        def func(x,a,b,c):
            return a*np.exp(-((x-b)/c)**2)
        try:
            popt, pcov = curve_fit(func,initialSlope,percentCliffs, maxfev=1000)
        except RuntimeError:
            fig = plt.figure()
            ax1 = fig.add_subplot(111)
            ax1.plot(initialSlope, percentCliffs, 'ko');plt.draw()
            fig.show()            
            print("Error - curve_fit failed")
        xfit = np.linspace(min(initialSlope), max(initialSlope), 100)
        yfit = popt[0]*np.exp(-((xfit-popt[1])/popt[2])**2)
        
        def secondDer(x):
            return popt[0]*(((4*(x-popt[1])**2*np.exp(-(x-popt[1])**2/popt[2]**2))/popt[2]**4)-((2*np.exp(-(x-popt[1])**2/popt[2]**2))/popt[2]**2))
        a1 = []
        a1 = [i for i in xrange(91)]
        a2 = secondDer(a1)
        #the next 3 for loops and a[x] variables define 1 of the 2 points to derive the optimization line.
        a3 = []
        a4 = []
        # values of second derivative where slope is below 'gamma'
        for i, j in enumerate(a2):
            if j <= gamma:
                a3.append(i) == i
        # find the steepest point (in the middle of the side of the bell)
        for i, j in enumerate(a2):
            if j == max(a2):
                m=i
        # take only values to the right of 'm' in case the curve is flat at 0 slope
        for i in a3:
            if i > m:
                a4.append(i) == i
        del i,j
                
        ax = min(a4) 
        ay = popt[0]*np.exp(-((ax-popt[1])/popt[2])**2)
        
        #find max of bell for first point in optmization line
        yfit_array = array(yfit)        
        ftup = (np.where(yfit_array == max(yfit_array)))
        f = int(ftup[0]) # x,y index of max yfit 
                
        # d = distance from fit Equation 2 (Herreid and Pellicciotti, 2018) to line definded by ((xfit[0],yfit[0]),(ax,yx))
        d = abs((yfit[f]-ay)*xfit-(xfit[f]-ax)*yfit+xfit[f]*ay-yfit[f]*ax)/((yfit[f]-ay)**2+(xfit[f]-ax)**2)**(1/2)
        # crit is the index of the longest d
        crit = np.where(d == max(d))
        m = (yfit[f]-ay)/(xfit[f]-ax)
        b = yfit[f]-m*xfit[f]
        x_crit = (xfit[crit]+m*yfit[crit]-m*b)/(m**2+1)
        y_crit = m*((xfit[crit]+m*yfit[crit]-m*b)/(m**2+1))+b
        
        fig = plt.figure()
        ax1 = fig.add_subplot(111)
        ax1.plot(initialSlope, percentCliffs, 'ko'); plt.plot([xfit[f],ax],[yfit[f],ay]); plt.plot([xfit[crit],x_crit],[yfit[crit],y_crit]); plt.plot(xfit,yfit);plt.xlim(0, 100);plt.ylim(0, 100);plt.gca().set_aspect('equal', adjustable='box');plt.draw()
        ax1.set_xlabel(r'$\mathrm{\beta_i (^\circ)}$')
        ax1.set_ylabel('Ice cliff fraction (%)')
        fig.show()
        #fig.canvas.flush_events()
        import time
        time.sleep(1)
        #plt.pause(0.01)
        #plt.waitforbuttonpress()
        
        #save data used to make figure
        np.save(workspace+'\\figureData', (initialSlope, percentCliffs,[xfit[f],ax],[yfit[f],ay],[xfit[crit],x_crit],[yfit[crit],y_crit],xfit,yfit))

        IceCliffLocation.minSlope = float(xfit[crit])
コード例 #8
0
def IntDen(city, inDir, workFld):
    import traceback, time, arcpy, os
    from arcpy import env
    arcpy.CheckOutExtension('Spatial')

#-------- DIRECTORY SETUP ------------------------------------------------
    """ Working Directory """
    try:
        arcpy.CreateFileGDB_management(str(workFld), str(city) + '_IntDen.gdb')
    except:
        print 'IntDen GDB already exists'

    workDir = str(workFld) + '/' + str(city) + '_IntDen.gdb'

    """ Report File Directory """
    reportfileDir = str(workFld) + '/Logs'
    """ Frequent Directory """
    freqDir = str(workFld) + '/' + city +'_Freq.gdb'
    """ Final Geodatabase """
    finalDir = str(workFld) + '/' + city + '_Final.gdb'

    """ Projection File Directory """
    prjDir = str(inDir) + '/Prj'
    prjfileALB = prjDir + '/USA Contiguous Albers Equal Area Conic USGS.prj'
    prjfileWM = prjDir + '/WGS 1984 Web Mercator (auxiliary sphere).prj'

    if os.path.isdir(str(workFld) + '/' + city + '_Split') == True:
        pass
    else:
        os.makedirs(str(workFld) + '/' + city + '_Split')
    splitDir = str(workFld) + '/' + city + '_Split'

    """ Split Raster Directory """
    if os.path.isdir(str(workFld) + '/' + city + '_Split') == True:
        pass
    else:
        os.makedirs(str(workFld) + '/' + city + '_Split')
    splitDir = str(workFld) + '/' + city + '_Split'

    """ RdsForIntDen Directory """
    rdsIntDen = inDir + '/Input.gdb/RdsForIntDen'

    """ Set Workspace Environments """
    arcpy.env.workspace = workDir
    arcpy.env.scratch = str(inDir) + '/Scratch.gdb'
    arcpy.env.overwriteOutput = True

    #-----------------------------------------------------------------------------
    # BEGIN ANALYSIS
	#-----------------------------------------------------------------------------
    try:
        #-------- LOGFILE CREATION ---------------------------------------------
        """ Create report file for each metric """
        tmpName = city + '_IntDen_' + time.strftime('%Y%m%d_%H-%M')
        reportfileName = reportfileDir + '/' + tmpName  + '.txt'
        reportFile = open(reportfileName, 'w')

        """ Write out first line of report file """
        print 'Intersection Density Start Time: ' + time.asctime()
        reportFile.write("Begin with the 2011 NavTeq Streets layer.--201701" + '--\n')
        reportFile.write("Limit streets to walkable roads: FUNC_CLASS < 2; SPEED_CAT < 3 AND > 7; AR_PEDEST = 'Y'.--201701" + '--\n')
        reportFile.write("Convert multipart roads to single part roads.--201701" + '--\n')
        reportFile.write("Use the 2011 NavTeq LandUseA and LandUseB to identify road segments within airports, amusement parks, beaches, cemeteries, hospitals, industrial complexes, military bases, railyards, shopping centers, and golf course. Remove these roads if they have no street name value (ST_NAME).--201701" + '--\n')
    	reportFile.write("Calculate new variable in the road layer for the direction of travel (0 for two ways, 1 for one way): Clps_Fld (SHORT) = 0 if DIR_TRAVEL=B, otherwise = 1--201701" + '--\n')

        #-------- PROCESSING LAYERS ----------------------------------------------
        """ Set Environments """
        arcpy.env.snapRaster = freqDir + '/LC'
        arcpy.env.extent = freqDir + '/LC'

    	"""-------- Finish Roads Prep ----------------------------- """

    	""" Clip RdsForIntDen """
    	arcpy.Clip_analysis(rdsIntDen, freqDir + '/Bnd_5km', 'RdsForIntDen')
    	reportFile.write("Clip the National Intersection Density Roads layer to the 5km buffer of the EnviroAtlas community.--" + time.strftime('%Y%m%d--%H%M%S') + '--\n')

    	""" Project into Albers """
    	arcpy.Project_management('RdsForIntDen', 'RdsForIntDen_Alb', prjfileALB)
    	reportFile.write("Project the clipped roads into Albers.--" + time.strftime('%Y%m%d--%H%M%S') + '--\n')

    	""" Merge Divided Roads """
        arcpy.MultipartToSinglepart_management('RdsForIntDen_Alb', 'RdsForIntDen_SglPrt')
    	arcpy.MergeDividedRoads_cartography('RdsForIntDen_SglPrt', "Clps_Fld", "30 meters", "PreppedRoads")
    	reportFile.write("Merge divided roads into one centered segment.--" + time.strftime('%Y%m%d--%H%M%S') + '--\n')

        """ Unsplit Lines """
        arcpy.UnsplitLine_management('PreppedRoads', 'UnSplitRds', "ST_NAME")
        reportFile.write("Unsplit roads by street name.--" + time.strftime('%Y%m%d--%H%M%S') + '--\n')

        """ Create Intersections """
        arcpy.Intersect_analysis(['UnSplitRds','UnSplitRds'], 'Intersections', "ONLY_FID",'',"POINT")
        reportFile.write("Create intersection points by intersecting the roads with themselves with output = point.--" + time.strftime('%Y%m%d--%H%M%S') + '--\n')

        """ Delete multiples """
        arcpy.DeleteIdentical_management('Intersections', "Shape")
        reportFile.write("Delete identical points.--" + time.strftime('%Y%m%d--%H%M%S') + '--\n')

        """ Run Density Calculation """
        den = arcpy.sa.KernelDensity('Intersections', "NONE", 10, 750, "SQUARE_KILOMETERS")
        den.save(workDir + "/IntDen_Raw")
        reportFile.write("Use the spatial analyst kernel density tool with a cell size of 10m, search radius of 750m and scale factor of square kilometers.--" + time.strftime('%Y%m%d--%H%M%S') + '--\n')

        """ Clip to the boundary and convert 0 to Null """
        arcpy.Clip_management("IntDen_Raw", '', city + "_IntDen", freqDir + '/Bnd', '0', 'ClippingGeometry', '')
        reportFile.write("Clip the raster to the community boundary and convert 0 values to No Data.--" + time.strftime('%Y%m%d--%H%M%S') + '--\n')

        """ Convert to TIFF for publishing """
        arcpy.RasterToOtherFormat_conversion(city + "_IntDen", splitDir, "TIFF")
        reportFile.write("Convert the raster to TIFF format for use in EnviroAtlas.--" + time.strftime('%Y%m%d--%H%M%S') + '--\n')

        """ Convert to polygons for posting """
        newID = arcpy.sa.Reclassify('IntDen_Raw', 'VALUE', arcpy.sa.RemapRange([[0,20,20], [20,40,40], [40,60,60], [60,80,80], [80,100,100],
                      [100,150,150], [150,200,200], [200,250,250]]), 'NODATA')
        newID.save('IntDen_ReC')
        reportFile.write("Reclassify the Raster into Qualitative Breaks.--" + time.strftime('%Y%m%d--%H%M%S') + '--\n')
        arcpy.RasterToPolygon_conversion('IntDen_ReC', 'IntDen_Poly', 'SIMPLIFY', 'VALUE')
        reportFile.write("Convert the Reclassified Raster into a Polygon.--" + time.strftime('%Y%m%d--%H%M%S') + '--\n')

        """ Clip and Convert to Albers """
        arcpy.Clip_analysis('IntDen_Poly', freqDir + '/Bnd', 'IntDen_Clip')
        reportFile.write("Clip the polygons to the EnviroAtlas Community Boundary--" + time.strftime('%Y%m%d--%H%M%S') + '--\n')
        arcpy.AlterField_management('IntDen_Clip', 'gridcode', 'IntDen')

    	""" Add to Final Directory """
    	try:
            arcpy.Delete_management(finalDir + '/' + city + '_IntDen')
        except:
            pass
        arcpy.FeatureClassToFeatureClass_conversion('IntDen_Clip', finalDir, city + '_IntDen')
        print 'Intersection Density End Time: ' + time.asctime() + '\n'
        reportFile.write("Copy the feature class to the final geodatabase.--" + time.strftime('%Y%m%d--%H%M%S') + '--\n')

        #-------- COMPELETE LOGFILES ---------------------------------------------
        reportFile.close()

	#-----------------------------------------------------------------------------
    # END ANALYSIS
	#-----------------------------------------------------------------------------
    except:
        """ This part of the script executes if anything went wrong in the main script above """
        #-------- PRINT ERRORS ---------------------------------------------------
        print "\nSomething went wrong.\n\n"
        print "Python Traceback Message below:"
        print traceback.format_exc()
        print "\nArcMap Error Messages below:"
        print arcpy.GetMessages(2)
        print "\nArcMap Warning Messages below:"
        print arcpy.GetMessages(1)

        #-------- COMPLETE LOGFILE ------------------------------------------------
        reportFile.write("\nSomething went wrong.\n\n")
        reportFile.write("Pyton Traceback Message below:")
        reportFile.write(traceback.format_exc())
        reportFile.write("\nArcMap Error Messages below:")
        reportFile.write(arcpy.GetMessages(2))
        reportFile.write("\nArcMap Warning Messages below:")
        reportFile.write(arcpy.GetMessages(1))

        reportFile.write( "\n\nEnded at " + time.asctime() + '\n')
        reportFile.write("\n---End of Log File---\n")

        if reportFile:
            reportFile.close()
コード例 #9
0
def rankPaths(source, pField, curSurface, outConnect, minWidth):
    arcpy.AddMessage('Generating ranked cost paths for ' + outConnect + '...')

    cList = []
    zList = []
    rList = []

    ##    # Append core areas to connected regions to connect regions that are bisected by source habitat
    ##
    ##    # Generate Minimum convex hull of connected areas
    ##    arcpy.MinimumBoundingGeometry_management(outConnect, "in_memory\\mcp", "CONVEX_HULL", "ALL")
    ##    arcpy.Clip_analysis(source, "in_memory\\mcp", "in_memory\\src_clp")
    ##
    ##    #Merge connected and source
    ##    arcpy.Merge_management(["in_memory\\src_clp", outConnect], "in_memory\\connect_merge")
    ##
    ##    #Dissolve merged connected patches
    ##    arcpy.Dissolve_management("in_memory\\connect_merge", "in_memory\\out_connect_merge", "", "", "SINGLE_PART", "")
    ##    outConnect = "in_memory\\out_connect_merge"

    # Set intersect tolerance to 3X link layer cell size to prevent Intersect from creating multiple line segments where slivers occur
    interTol = str(3 * int(arcpy.Describe(link).meanCellWidth))
    minWidth = 2 * minWidth
    cstSurface = arcpy.sa.FocalStatistics(curSurface,
                                          arcpy.sa.NbrCircle(minWidth, "Map"),
                                          "MEAN", "DATA")

    # If connected region is not empty, extract cost surface by connected region to limit analysis to connected region
    if len(connectList) > 0:
        cstSurface2 = arcpy.CopyRaster_management(cstSurface, "cstSurface2")
        arcpy.AddMessage('Extracting cost surface by connected area...')
        cstSurface = arcpy.gp.ExtractByMask_sa(cstSurface, outConnect,
                                               "cstSurf")
        cstSurface = arcpy.Describe(cstSurface).name
        cstSurface2 = arcpy.Describe(cstSurface2).name

    # Create line segment where source patches touch connected regions to use as sources for cost paths

    # Make sure inputs are in same projection

    sourceProjName = arcpy.Describe(source).spatialreference.name
    curProjName = arcpy.Describe(cstSurface).spatialreference.name

    if not sourceProjName == curProjName:
        arcpy.AddMessage("\tReprojecting source layer...")
        pSource = arcpy.Project_management(
            source, os.path.join(arcpy.env.scratchWorkspace, "reproj.shp"),
            cstSurface)
    else:
        pSource = source

##    # Add core ares back to current surfaces as zero cost regions
##    arcpy.env.cellSize = '"%s"' % arcpy.Describe(cstSurface).catalogPath
##    CellSize = str(arcpy.env.cellSize)
##    arcpy.PolygonToRaster_conversion(pSource, pField, "in_memory\\rast_source", "", "", CellSize)
##    no_null = arcpy.sa.Con(arcpy.sa.IsNull("in_memory\\rast_source"),0,1)
##    cstSurface = arcpy.sa.Con(no_null, 0, cstSurface, "VALUE = 1")
##    cstSurface2 = arcpy.sa.Con(no_null, 0, cstSurface2, "VALUE = 1")

    arcpy.AddMessage(
        '\tIntersecting source patches with connected area to create source regions...'
    )
    pSource = arcpy.EliminatePolygonPart_management(pSource,
                                                    "in_memory\\eliminate",
                                                    "PERCENT", "", 10,
                                                    "CONTAINED_ONLY")
    try:
        arcpy.Delete_management(
            os.path.join(arcpy.env.scratchWorkspace, "reproj.shp"))
    except:
        pass
    pSource = arcpy.Intersect_analysis([[pSource, 1], [outConnect, 1]],
                                       "in_memory\\intersect", "ALL", interTol,
                                       "LINE")
    pSource = arcpy.MultipartToSinglepart_management(pSource,
                                                     "in_memory\\multipart")
    pSource = arcpy.UnsplitLine_management(pSource, "in_memory\\unsplit",
                                           pField)
    pSource = arcpy.MakeFeatureLayer_management(pSource, "pSource")

    # Calculate least-cost path for each pair-wise combination of source patches
    l = getCombinations(source, pField)
    values = l[0]
    combs = l[1]

    # break combination and not connected lists into unique elements and create list of regions with no connections
    if len(connectList) > 0:
        theList = connectList
    else:
        theList = noConnectList

    c = list(set(chain.from_iterable(theList)))

    # Create patch regions and cost distance rasters for each unique value in source patches
    arcpy.AddMessage(
        '\tCreating patch regions and cost distance rasters for each unique value in source patches...'
    )
    for v in values:
        if v in c:
            v = str(int(v))
            arcpy.AddMessage('\t\tProcessing patch region ' + v + '...')
            arcpy.SelectLayerByAttribute_management(pSource, "NEW_SELECTION",
                                                    pField + " = " + v)
            arcpy.MakeFeatureLayer_management(pSource, "p_" + v)
            cd = arcpy.sa.CostDistance("p_" + v, cstSurface, "",
                                       os.path.join(workspace, "bklnk_" + v))
            arcpy.MakeRasterLayer_management(cd, "CostDist_" + v)

            if len(connectList) > 0:
                rd = arcpy.sa.CostDistance(
                    "p_" + v, cstSurface2, "",
                    os.path.join(workspace, "r_bklnk_" + v))
                arcpy.MakeRasterLayer_management(rd, "r_CostDist_" + v)

    # Create least-cost paths for each region pair in both directions
    arcpy.AddMessage(
        '\tGenerating least-cost path for each patch pair combination...')

    for c in combs:
        c1 = str(int(c[0]))
        c2 = str(int(c[1]))

        if c in theList:
            arcpy.AddMessage('\t\tCalculating least-cost path from region ' +
                             c1 + ' to region ' + c2 + '...')
            cp = arcpy.sa.CostPath("p_" + c1, "CostDist_" + c2, "bklnk_" + c2,
                                   "BEST_SINGLE", "FID")
            cp1 = arcpy.MakeRasterLayer_management(cp, "CP_" + c1 + "_" + c2)
            arcpy.AddMessage('\t\tCalculating least-cost path from region ' +
                             c2 + ' to region ' + c1 + '...')
            cp = arcpy.sa.CostPath("p_" + c2, "CostDist_" + c1, "bklnk_" + c1,
                                   "BEST_SINGLE", "FID")
            cp2 = arcpy.MakeRasterLayer_management(cp, "CP_" + c2 + "_" + c1)

            cList.append(str(cp1))
            cList.append(str(cp2))

        else:
            arcpy.AddWarning(
                '\t\tRegions ' + c1 + ' and ' + c2 +
                ' are not connected.  Skipping cost path for this region pair...'
            )

    # Create combined least-cost path polyline layer
    arcpy.AddMessage('\t\tMosaicing least-cost paths for region pairs...')
    arcpy.MosaicToNewRaster_management(cList, workspace, "lcp_mos", "", "", "",
                                       "1", "MAXIMUM")

    for c in cList:
        try:
            arcpy.Delete_management(c)
        except:
            pass

    arcpy.CalculateStatistics_management(os.path.join(workspace, "lcp_mos"))
    LCP = arcpy.sa.Con(os.path.join(workspace, "lcp_mos"), "1", "",
                       "VALUE > 0")

    arcpy.Delete_management(os.path.join(workspace, "lcp_mos"))

    # Create least-cost paths by zone
    arcpy.AddMessage(
        '\tGenerating least-cost paths  by zones for each patch pair combination...'
    )
    # Create least-cost paths for each region pair in both directions
    for c in combs:
        c1 = str(int(c[0]))
        c2 = str(int(c[1]))
        if c in theList:
            arcpy.AddMessage('\t\tCalculating least-cost path from region ' +
                             c1 + ' to region ' + c2 + '...')
            zp = arcpy.sa.CostPath("p_" + c1, "CostDist_" + c2, "bklnk_" + c2,
                                   "EACH_ZONE", "FID")
            zp1 = arcpy.MakeRasterLayer_management(zp, "ZP_" + c1 + "_" + c2)
            arcpy.AddMessage('\t\tCalculating least-cost path from region ' +
                             c2 + ' to region ' + c1 + '...')
            zp = arcpy.sa.CostPath("p_" + c2, "CostDist_" + c1, "bklnk_" + c1,
                                   "EACH_ZONE", "FID")
            zp2 = arcpy.MakeRasterLayer_management(zp, "ZP_" + c2 + "_" + c1)

            zList.append(str(zp1))
            zList.append(str(zp2))

    # Create combined least-cost path polyline layer
    arcpy.AddMessage('\t\tMosaicing least-cost paths for region zones...')
    if arcpy.Exists(os.path.join(workspace, "zcp_mos")):
        arcpy.Delete_management(os.path.join(workspace, "zcp_mos"))
    arcpy.MosaicToNewRaster_management(zList, workspace, "zcp_mos", "", "", "",
                                       "1", "MAXIMUM")

    for z in zList:
        try:
            arcpy.Delete_management(z)
        except:
            pass

    arcpy.CalculateStatistics_management(os.path.join(workspace, "zcp_mos"))
    ZCP = arcpy.sa.Con(os.path.join(workspace, "zcp_mos"), "2", "",
                       "VALUE > 0")

    # Create least-cost paths through compromised areas

    if len(connectList) > 0:
        # Create patch regions and cost distance rasters for each unique value in source patches
        arcpy.AddMessage('\tCalculating costs through restoration zones...')

        arcpy.AddMessage(
            '\tGenerating potential restoration paths for each patch pair combination...'
        )
        # Create least-cost paths for each region pair in both directions
        for c in combs:
            c1 = str(int(c[0]))
            c2 = str(int(c[1]))
            if c in theList:
                arcpy.AddMessage(
                    '\t\tCalculating least-cost path from region ' + c1 +
                    ' to region ' + c2 + '...')
                rp = arcpy.sa.CostPath("p_" + c1, "r_CostDist_" + c2,
                                       "r_bklnk_" + c2, "EACH_ZONE", "FID")
                rp1 = arcpy.MakeRasterLayer_management(rp,
                                                       "RP_" + c1 + "_" + c2)
                arcpy.AddMessage(
                    '\t\tCalculating least-cost path from region ' + c2 +
                    ' to region ' + c1 + '...')
                rp = arcpy.sa.CostPath("p_" + c2, "r_CostDist_" + c1,
                                       "r_bklnk_" + c1, "EACH_ZONE", "FID")
                rp2 = arcpy.MakeRasterLayer_management(rp,
                                                       "RP_" + c2 + "_" + c1)

                rList.append(str(rp1))
                rList.append(str(rp2))

        # Create combined least-cost path polyline layer
        arcpy.AddMessage('\t\tMosaicing least-cost paths for region zones...')
        if arcpy.Exists(os.path.join(workspace, "rcp_mos")):
            arcpy.Delete_management(os.path.join(workspace, "rcp_mos"))
        arcpy.MosaicToNewRaster_management(rList, workspace, "rcp_mos", "", "",
                                           "", "1", "MAXIMUM")

        for r in rList:
            try:
                arcpy.Delete_management(r)
            except:
                pass

        arcpy.CalculateStatistics_management(os.path.join(
            workspace, "rcp_mos"))
        RCP = arcpy.sa.Con(os.path.join(workspace, "rcp_mos"), "3", "",
                           "VALUE > 0")
        mList = [LCP, ZCP, RCP]

    else:
        mList = [LCP, ZCP]

    arcpy.AddMessage(
        '\tCombining least-cost paths by region and least-cost paths by region zones...'
    )
    arcpy.MosaicToNewRaster_management(mList, workspace, "lcp_mos", "", "", "",
                                       "1", "MINIMUM")
    LCP = arcpy.RasterToPolyline_conversion(os.path.join(workspace, "lcp_mos"),
                                            "LCP", "", "", "NO_SIMPLIFY")

    # Create a fieldinfo object to rename grid_code field
    fieldinfo = arcpy.FieldInfo()
    fieldinfo.addField("GRID_CODE", "PATH_RNK", "VISIBLE", "")
    outLCP = arcpy.MakeFeatureLayer_management(str(LCP), "outLCP", "", "",
                                               fieldinfo)
    # arcpy.CopyFeatures_management(outLCP, os.path.join(workspace, outLCP.shp))

    try:
        arcpy.Delete_management(os.path.join(workspace, "lcp_mos"))
        arcpy.Delete_management(os.path.join(workspace, "zcp_mos"))
        arcpy.Delete_management(os.path.join(workspace, "rcp_mos"))
        #arcpy.Delete_management("in_memory")
    except:
        pass
    return (outLCP)
コード例 #10
0
ファイル: MapMergerSimp.py プロジェクト: rcrow/MapMerger
#                           unsplit_lines="DISSOLVE_LINES")

arcpy.env.overwriteOutput = True
arcpy.dissolveAndConcatenate_MergerTools(
    polysToDissolve=exportMergedFDSFullPath + "\\" + "MapUnitPolys_temp",
    gdb=exportGDBFullPath,
    output=exportMergedFDSFullPath + "\\" + "MapUnitPolys")

print("Finished the dissolving...")
#arcpy.Delete_management(exportMergedFDSFullPath + "\\" + "MapUnitPolys_temp")
##Delete the contacts and faults that are no longer needed
#Can't remember exactly why I added the unsplit - no required but would fix pseudonodes
arcpy.UnsplitLine_management(
    in_features=exportMergedFDSFullPath + "\\" + "ContactsAndFaults_temp",
    out_feature_class=exportMergedFDSFullPath + "\\" +
    "ContactsAndFaults_temp2",
    dissolve_field=
    "Type;IsConcealed;LocationConfidenceMeters;ExistenceConfidence;IdentityConfidence;Symbol;Label;DataSourceID;Notes",
    statistics_fields="")
# 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: "Merged\ContactsAndFaults_temp"
print("Finished the unsplitting the lines...")
#This intersects all the feature with themselves
arcpy.FeatureToLine_management(
    in_features=exportMergedFDSFullPath + "\\" + "ContactsAndFaults_temp2",
    out_feature_class=exportMergedFDSFullPath + "\\" + "ContactsAndFaults",
    cluster_tolerance="",
    attributes="ATTRIBUTES")
#arcpy.Delete_management(exportMergedFDSFullPath + "\\" + "ContactsAndFaults_temp")
#arcpy.Delete_management(exportMergedFDSFullPath + "\\" + "ContactsAndFaults_temp2")
print("Finished the feature to line...")
コード例 #11
0
ファイル: GSTCnWR.py プロジェクト: waternk/EnviroAtlas_JSApp
def GSTCnWR(city, inDir, workFld):
    import traceback, time, arcpy, os
    from arcpy import env
    arcpy.CheckOutExtension('Spatial')

    #-------- DIRECTORY SETUP ------------------------------------------------
    """ Working Directory """
    try:
        arcpy.CreateFileGDB_management(str(workFld),
                                       str(city) + '_GSTCnWR.gdb')
    except:
        pass
    workGDB = str(workFld) + '/' + str(city) + '_GSTCnWR.gdb'
    """ Report File Directory """
    reportfileDir = str(workFld) + '/Logs'
    """ Frequent Directory """
    freqDir = str(workFld) + '/' + city + '_Freq.gdb'
    """ Final Geodatabase """
    finalDir = str(workFld) + '/' + city + '_Final.gdb'
    """ Projection File Directory """
    prjDir = str(inDir) + '/Prj'
    prjfileALB = prjDir + '/USA Contiguous Albers Equal Area Conic USGS.prj'
    prjfileWM = prjDir + '/WGS 1984 Web Mercator (auxiliary sphere).prj'
    """ Input Walkable Roads Data """
    walkroads = str(inDir) + '/' + 'Parks.gdb/' + str(city) + '_Walk_Road_Alb'
    """ Split Raster Directory """
    if os.path.isdir(str(workFld) + '/' + city + '_Split') == True:
        pass
    else:
        os.makedirs(str(workFld) + '/' + city + '_Split')
    splitDir = str(workFld) + '/' + city + '_Split'
    """ Set Workspace Environments """
    arcpy.env.workspace = workGDB
    arcpy.env.scratch = str(inDir) + '/Scratch.gdb'
    arcpy.env.overwriteOutput = True

    #-----------------------------------------------------------------------------
    # BEGIN ANALYSIS
    #-----------------------------------------------------------------------------
    try:
        #-------- LOGFILE CREATION ---------------------------------------------
        """ Create report file for each metric """
        tmpName = city + '_PctStGS_' + time.strftime('%Y%m%d_%H-%M')
        reportfileName = reportfileDir + '/' + tmpName + '.txt'
        gsRF = open(reportfileName, 'w')

        tmpName = city + '_PctStTC_' + time.strftime('%Y%m%d_%H-%M')
        reportfileName = reportfileDir + '/' + tmpName + '.txt'
        tcRF = open(reportfileName, 'w')

        try:
            loglist = sorted(f for f in os.listdir(reportfileDir)
                             if f.startswith(str(city) + '_Reuse'))
            tmpName = loglist[-1]
        except:
            tmpName = city + '_Reuse_' + time.strftime('%Y%m%d_%H-%M') + '.txt'
        reportfileName = reportfileDir + '/' + tmpName

        try:
            ReuseRF = open(reportfileName, 'a')
        except:
            ReuseRF = open(reportfileName, 'w')
            print 'Creating Reuse Log'
        """ Write out first lines of report file """
        print 'Green Space and Tree Cover Along Walkable Roads Start Time: ' + time.asctime(
        )
        gsRF.write(
            "Begin with the 2011 Walkable Roads and the 1-M Land Cover for the EnviroAtlas community, created by the US EPA EnviroAtlas Team.--"
            + time.strftime('%Y%m%d--%H%M%S') + '--\n')
        tcRF.write(
            "Begin with the 2011 Walkable Roads Layer and the 1-M Land Cover for the EnviroAtlas community, created by the US EPA EnviroAtlas Team.--"
            + time.strftime('%Y%m%d--%H%M%S') + '--\n')

        gsRF.write(
            "The walkable roads layer was created from 2011 NavTeq Streets by removing roads with multiple entrance/exit ramps, roads with speed limits above 54 mph, roads with functional class less than 3, and roads where pedestrians are not allowed.--201611--\n"
        )
        tcRF.write(
            "The walkable roads layer was created from 2011 NavTeq Streets by removing roads with multiple entrance/exit ramps, roads with speed limits above 54 mph, roads with functional class less than 3, and roads where pedestrians are not allowed.--201611--\n"
        )

        #-------- PROCESSING LAYERS ----------------------------------------------
        """ Set Environments """
        arcpy.env.extent = str(freqDir) + '/LC'
        arcpy.env.snapRaster = str(freqDir) + '/LC'

        #-------- PREPARE LAND COVER --------------------------------------
        """-------- Reclassify LC into Binary Green Space with Water ----------------------------- """
        if arcpy.Exists(str(freqDir) + '/GBS_Ionly') == False:
            outReclass = arcpy.sa.Reclassify(
                str(freqDir) + '/LC', 'Value',
                arcpy.sa.RemapValue([[0, "NODATA"], [10, 1], [20, "NODATA"],
                                     [21, "NODATA"], [22, "NODATA"],
                                     [30, "NODATA"], [40, 1], [52, 1], [70, 1],
                                     [80, 1], [82, 1], [91, 1], [92, 1]]))
            outReclass.save(str(freqDir) + '/GBS_Ionly')
            gsRF.write("Reclassify into green space + water. REPLACE-GSBE--" +
                       time.strftime('%Y%m%d--%H%M%S') + '--\n')
            ReuseRF.write('GBSI--' + time.strftime('%Y%m%d--%H%M%S') + '--\n')
        else:
            gsRF.write(
                "Reclassify into green space + water. REPLACE-GSBE--GBSI" +
                '--\n')
        """-------- Reclassify LC into Binary Forest ----------------------------- """
        if arcpy.Exists(str(freqDir) + '/Forest_Ionly') == False:
            outReclass = arcpy.sa.Reclassify(
                str(freqDir) + '/LC', 'Value',
                arcpy.sa.RemapValue([[0, "NODATA"], [10, "NODATA"],
                                     [20, "NODATA"], [21, "NODATA"],
                                     [22, "NODATA"], [30, "NODATA"], [40, 1],
                                     [52, "NODATA"], [70, "NODATA"],
                                     [80, "NODATA"], [82, 1], [91, 1],
                                     [92, "NODATA"]]))
            outReclass.save(str(freqDir) + '/Forest_Ionly')
            tcRF.write(
                "Reclassify the Land Cover into Binary Forest. REPLACE-MFIE--"
                + time.strftime('%Y%m%d--%H%M%S') + '--\n')
            ReuseRF.write("ForI--" + time.strftime('%Y%m%d--%H%M%S') + '--\n')
        else:
            tcRF.write(
                "Reclassify the Land Cover into Binary Forest. REPLACE-MFIE--ForI"
                + '--\n')
        """ Convert rasters to TIFF """
        try:
            arcpy.Delete_management(splitDir + '/gbs_ionly')
        except:
            pass
        arcpy.RasterToOtherFormat_conversion(
            str(freqDir) + '/GBS_Ionly', splitDir, 'GRID')
        gsRF.write(
            "Convert the reclassified raster into GeoTIFF for partial processing.--"
            + time.strftime('%Y%m%d--%H%M%S') + '--\n')

        try:
            arcpy.Delete_management(splitDir + '/forest_ionly')
        except:
            pass
        arcpy.RasterToOtherFormat_conversion(
            str(freqDir) + '/Forest_Ionly', splitDir, 'GRID')
        tcRF.write(
            "Convert the reclassified raster into GeoTIFF for partial processing.--"
            + time.strftime('%Y%m%d--%H%M%S') + '--\n')
        """-------- Split the Raster As Needs, Process Each Piece ----------------- """
        """ Check if the raster should be split """
        columns = arcpy.GetRasterProperties_management(
            str(freqDir) + '/Forest_Ionly', 'COLUMNCOUNT').getOutput(0)
        xsplit = int(float(columns) / 40000) + 1
        rows = arcpy.GetRasterProperties_management(
            str(freqDir) + '/Forest_Ionly', 'ROWCOUNT').getOutput(0)
        ysplit = int(float(rows) / 40000) + 1
        """-------- If no split, run the analysis --------------------------------- """
        if xsplit * ysplit == 1:
            """ Convert Rasters to Polygons """
            arcpy.RasterToPolygon_conversion(
                str(freqDir) + '/GBS_Ionly', workGDB + '/GBSPoly', 'SIMPLIFY')
            gsRF.write("Convert the TIFF into Polygons.--" +
                       time.strftime('%Y%m%d--%H%M%S') + '--\n')
            arcpy.RasterToPolygon_conversion(
                str(freqDir) + '/Forest_Ionly', workGDB + '/ForPoly',
                'SIMPLIFY')
            tcRF.write("Convert the TIFF into Polygons.--" +
                       time.strftime('%Y%m%d--%H%M%S') + '--\n')
            """-------- If split, run the analysis on each piece and recombine --------- """
        else:
            """ Delete the raster, if necessary """
            xy = (xsplit * ysplit)
            for rast in range(xy):
                try:
                    arcpy.Delete_management(splitDir + '/gbsp_' + str(rast))
                    arcpy.Delete_management(splitDir + '/forp_' + str(rast))
                except:
                    pass
            """ Split the Raster """
            arcpy.SplitRaster_management(splitDir + '/gbs_ionly', splitDir,
                                         'gbsp_', 'NUMBER_OF_TILES', 'GRID',
                                         '',
                                         str(xsplit) + ' ' + str(ysplit))
            gsRF.write(
                "Split the reclassified raster into pieces of no more than 40,000x40,000 pixels, if necessary.--"
                + time.strftime('%Y%m%d--%H%M%S') + '--\n')

            arcpy.SplitRaster_management(splitDir + '/forest_ionly', splitDir,
                                         'forp_', 'NUMBER_OF_TILES', 'GRID',
                                         '',
                                         str(xsplit) + ' ' + str(ysplit))
            tcRF.write(
                "Split the reclassified raster into pieces of no more than 40,000x40,000 pixels, if necessary.--"
                + time.strftime('%Y%m%d--%H%M%S') + '--\n')
            """ Set Environments """
            arcpy.env.snapRaster = str(freqDir) + '/GBS_Ionly'
            arcpy.env.extent = str(freqDir) + '/GBS_Ionly'
            """ Convert Raster to Polygon for Green Space"""
            for Chunk in range(0, xy):
                try:
                    result = float(
                        arcpy.GetRasterProperties_management(
                            splitDir + '/gbsp_' + str(Chunk),
                            'MEAN').getOutput(0))
                    if (result <> 0):
                        arcpy.RasterToOtherFormat_conversion(
                            splitDir + '/gbsp_' + str(Chunk), workGDB)
                        arcpy.RasterToPolygon_conversion(
                            'gbsp_' + str(Chunk), 'GBSPoly_' + str(Chunk),
                            'SIMPLIFY')
                        arcpy.RepairGeometry_management('GBSPoly_' +
                                                        str(Chunk))
                    else:
                        pass
                except:
                    pass
            """ Convert Raster to Polygon for Tree Cover"""
            for Chunk in range(0, xy):
                try:
                    result = float(
                        arcpy.GetRasterProperties_management(
                            splitDir + '/forp_' + str(Chunk),
                            'MEAN').getOutput(0))
                    if (result <> 0):
                        arcpy.RasterToOtherFormat_conversion(
                            splitDir + '/forp_' + str(Chunk), workGDB)
                        arcpy.RasterToPolygon_conversion(
                            'forp_' + str(Chunk), 'ForPoly_' + str(Chunk),
                            'SIMPLIFY')
                        arcpy.RepairGeometry_management('ForPoly_' +
                                                        str(Chunk))
                    else:
                        pass
                except:
                    pass

            gsRF.write("Convert each raster into polygons.--" +
                       time.strftime('%Y%m%d--%H%M%S') + '--\n')
            tcRF.write("Convert each raster into polygons.--" +
                       time.strftime('%Y%m%d--%H%M%S') + '--\n')
            """ Merge the polygons back together"""
            fcList = arcpy.ListFeatureClasses('GBSPoly_*')
            arcpy.Merge_management(fcList, 'GBSPoly')
            gsRF.write("Merge the polygons into one feature class.--" +
                       time.strftime('%Y%m%d--%H%M%S') + '--\n')

            fcList = arcpy.ListFeatureClasses('ForPoly_*')
            arcpy.Merge_management(fcList, 'ForPoly')
            tcRF.write("Merge the polygons into one feature class.--" +
                       time.strftime('%Y%m%d--%H%M%S') + '--\n')

#-------- PREPARE ROADS DATA --------------------------------------
        """ Copy Walkable Roads to the Working Directory """
        try:
            arcpy.CopyFeatures_management(walkroads, 'Walk_Road_Alb')
            gsRF.write(
                "Clip the EnviroAtlas Walkable Roads layer to the EnviroAtlas community boundary and project into UTM.--ANALYST-TIME--\n"
            )
            tcRF.write(
                "Clip the EnviroAtlas Walkable Roads layer to the EnviroAtlas community boundary and project into UTM.--ANALYST-TIME--\n"
            )
        except:
            arcpy.Clip_analysis(inDir + '/Input.gdb/Walkable_Roads',
                                freqDir + '/Bnd_5km', 'Walk_Road_Alb')
            gsRF.write(
                "Clip the NavTeq Streets layer to the EnviroAtlas community boundary and project into UTM.--"
                + time.strftime('%Y%m%d--%H%M%S') + '--\n')
            tcRF.write(
                "Clip the NavTeq Streets layer to the EnviroAtlas community boundary and project into UTM.--"
                + time.strftime('%Y%m%d--%H%M%S') + '--\n')
        """ Project roads into UTM """
        descLC = arcpy.Describe(str(freqDir) + '/LC')
        arcpy.Project_management('Walk_Road_Alb', 'Walk_Road_UTM',
                                 descLC.spatialReference)
        walkroads = 'Walk_Road_UTM'
        """ Create Intersection Points """
        arcpy.UnsplitLine_management(walkroads, 'WalkRd_Unsplit', "ST_NAME")
        arcpy.Intersect_analysis(['WalkRd_Unsplit', 'WalkRd_Unsplit'],
                                 'Intersections', "ONLY_FID", '', "POINT")
        arcpy.DeleteIdentical_management('Intersections', "shape")
        gsRF.write(
            "Unsplit the Walkable roads and intersecting them with themselves to create a point at each intersection.--"
            + time.strftime('%Y%m%d--%H%M%S') + '--\n')
        tcRF.write(
            "Unsplit the Walkable roads and intersecting them with themselves to create a point at each intersection.--"
            + time.strftime('%Y%m%d--%H%M%S') + '--\n')

        #-------- RUN TREE COVER ANALYSIS --------------------------------------
        """ Make New Road Attributes """
        arcpy.AddField_management(walkroads, "totLanes", "SHORT")
        arcpy.AddField_management(walkroads, "dirTrvl", "SHORT")
        arcpy.AddField_management(walkroads, "numLanes", "SHORT")
        arcpy.CalculateField_management(walkroads, "totLanes",
                                        "!TO_LANES! + !FROM_LANES!",
                                        "PYTHON_9.3")
        codeblock = """def makeBin(x):
                if x == 'B':
                    return 2
                else:
                    return 1"""
        arcpy.CalculateField_management(walkroads, "dirTrvl",
                                        "makeBin(!DIR_TRAVEL!)", "PYTHON_9.3",
                                        codeblock)
        arcpy.CalculateField_management(walkroads, "numLanes", "!totLanes!",
                                        "PYTHON_9.3")
        with arcpy.da.UpdateCursor(walkroads, ('numLanes', ),
                                   "numLanes = 0") as cursor:
            for row in cursor:
                row[0] = 2
                cursor.updateRow(row)

        tcRF.write(
            "Add and calculate new fields: totLanes (short) = TO_LANES + FROM_LANES; dirTrvl (short) = 2 if DIR_TRAVEL='B'; else = 1; numLanes (short) = totLanes if totLanes > 0; else = 2--"
            + time.strftime('%Y%m%d--%H%M%S') + '--\n')
        """ Dissolve Roads """
        arcpy.Dissolve_management(walkroads, 'RdsByLanes_For',
                                  ["numLanes", "dirTrvl"])
        tcRF.write(
            "Dissolve the Walkable Roads by number of lanes (totLanes) and direction of travel (dirTrvl).--"
            + time.strftime('%Y%m%d--%H%M%S') + '--\n')
        """ Split Roads at Intersections """
        arcpy.SplitLineAtPoint_management('RdsByLanes_For', 'Intersections',
                                          'RdsByBlk_For', "3 Meters")
        tcRF.write(
            "Split the dissolved walkable roads at each intersection point to create road blocks.--"
            + time.strftime('%Y%m%d--%H%M%S') + '--\n')
        """-------- Create the Focal Areas --------------------------"""
        """ Create Max Buffer """
        arcpy.AddField_management('RdsByBlk_For', "Max_Buff", "FLOAT")
        arcpy.CalculateField_management(
            'RdsByBlk_For', "Max_Buff",
            "(!numLanes! * 3.5 + 2.5 * !dirTrvl!)/2 + 7.5", "PYTHON_9.3")
        arcpy.Buffer_analysis('RdsByBlk_For', 'Max_Buff', "Max_Buff", "FULL",
                              "FLAT")
        tcRF.write(
            'Calculate the estimated width of the road (number of lanes * 3.5 meters/lane + 2.5 meters of parking lanes per direction of travel) plus the focus area: Mx_Buff (float) = (numLanes*3.5 + 2.5*dirTrvl)/2 + 7.5. Buffer the roads by this value.--'
            + time.strftime('%Y%m%d--%H%M%S') + '--\n')
        """ Create Min Buffer """
        arcpy.AddField_management('RdsByBlk_For', "Min_Buff", "FLOAT")
        arcpy.CalculateField_management(
            'RdsByBlk_For', "Min_Buff",
            "(!numLanes! * 3.5 + 2.5 * !dirTrvl!)/2 - 1", "PYTHON_9.3")
        arcpy.Buffer_analysis('RdsByBlk_For', 'Min_Buff', "Min_Buff", "FULL",
                              "FLAT")
        tcRF.write(
            "Calculate the width of the road less one meter (to account for narrower roads; number of lanes * 3.5 meters/lane + 2.5 meters of parking lanes per direction of travel): Mn_Buff (float)= (numLanes*3.5 + 2.5*dirTrvl)/2 - 1. Buffer the roads by this value.--"
            + time.strftime('%Y%m%d--%H%M%S') + '--\n')
        """ Subtract Buffers to Create Final Buffer """
        arcpy.Erase_analysis("Max_Buff", 'Min_Buff', 'FocalArea_For')
        tcRF.write(
            "Create the focus area feature class by erasing the second, smaller buffer from the first, larger buffer.--"
            + time.strftime('%Y%m%d--%H%M%S') + '--\n')
        """-------- Calculate Percent Forest in Focal Area ----------------"""
        arcpy.AddField_management('FocalArea_For', "road_ID", "FLOAT")
        arcpy.AddField_management('FocalArea_For', "seg_area", "FLOAT")
        arcpy.CalculateField_management('FocalArea_For', "road_ID",
                                        "!ORIG_FID!", "PYTHON_9.3")
        arcpy.CalculateField_management('FocalArea_For', "seg_area",
                                        "!Shape_area!", "PYTHON_9.3")
        """-------- Check that the Analysis Area is covered by the LC -------------- """
        """ Create a Polygon Version of the LC """
        if arcpy.Exists(freqDir + '/LC_Poly') == False:
            arcpy.env.snapRaster = freqDir + '/LC'
            arcpy.env.extent = freqDir + '/LC'
            ReC = arcpy.sa.Reclassify(
                str(freqDir) + '/LC', 'Value',
                arcpy.sa.RemapValue([[0, 0], [10, 1], [20, 1], [21,
                                                                1], [22, 1],
                                     [30, 1], [40, 1], [52, 1], [70, 1],
                                     [80, 1], [82, 1], [91, 1], [92, 1]]))
            ReC.save(str(freqDir) + '/AreaIO')
            arcpy.RasterToPolygon_conversion(
                str(freqDir) + '/AreaIO',
                str(freqDir) + '/LC_Poly', 'SIMPLIFY')
            arcpy.EliminatePolygonPart_management(
                str(freqDir) + '/LC_Poly',
                str(freqDir) + '/LC_Poly_EP', 'PERCENT', '', '5',
                'CONTAINED_ONLY')
            arcpy.Delete_management(str(freqDir) + '/LC_Poly')
            arcpy.Rename_management(
                str(freqDir) + '/LC_Poly_EP',
                str(freqDir) + '/LC_Poly')
            arcpy.env.snapRaster = str(freqDir) + '/GBS_Ionly'
            arcpy.env.extent = str(freqDir) + '/GBS_Ionly'
        """ Buffer the LC Polygon by -500m """
        if arcpy.Exists(freqDir + '/Bnd_Cty_500m') == False:
            arcpy.Buffer_analysis(
                str(freqDir) + '/Bnd_Cty',
                str(freqDir) + '/Bnd_Cty_500m', '500 meters')
            arcpy.EliminatePolygonPart_management(
                str(freqDir) + '/Bnd_Cty_500m',
                str(freqDir) + '/Bnd_Cty_500m_EP', 'PERCENT', '', '30',
                'CONTAINED_ONLY')
            arcpy.Delete_management(str(freqDir) + '/Bnd_Cty_500m')
            arcpy.Rename_management(
                str(freqDir) + '/Bnd_Cty_500m_EP',
                str(freqDir) + '/Bnd_Cty_500m')
        """ Identify whether LC is large enough """
        arcpy.MakeFeatureLayer_management(str(freqDir) + '/LC_Poly', 'LClyr')
        arcpy.MakeFeatureLayer_management(
            str(freqDir) + '/Bnd_Cty_500m', 'BC_500lyr')

        arcpy.SelectLayerByLocation_management('BC_500lyr',
                                               'COMPLETELY_WITHIN', 'LClyr',
                                               '', 'NEW_SELECTION')
        bigEnough = float(arcpy.GetCount_management('BC_500lyr').getOutput(0))
        arcpy.SelectLayerByAttribute_management('BC_500lyr', 'CLEAR_SELECTION')
        """ If the LC isn't large enough, limit the output """
        if bigEnough == 0:
            arcpy.MakeFeatureLayer_management("FocalArea_For", 'FA_For_lyr')
            arcpy.SelectLayerByLocation_management('FA_For_Lyr',
                                                   'COMPLETELY_WITHIN',
                                                   freqDir + '/LC_Poly', '',
                                                   'NEW_SELECTION')
            arcpy.CopyFeatures_management('FA_For_Lyr', 'FocalArea_For_EE')
            arcpy.SelectLayerByAttribute_management('FA_For_lyr',
                                                    'CLEAR_SELECTION')
            tcRF.write(
                "Due to the extent of the Land Cover, the analysis area is smaller than the EnviroAtlas Community Boundary. Remove any features that are not within the analysis area.--"
                + time.strftime('%Y%m%d--%H%M%S') + '--\n')
        """-------- Calculate Percent Forest per Block ------------------------------ """
        """ Intersect the tree cover polygons with the focus areas """
        arcpy.RepairGeometry_management("ForPoly")
        try:
            arcpy.Intersect_analysis(["FocalArea_For_EE", "ForPoly"],
                                     'SideWalk_For', "ALL", "", "INPUT")
        except:
            arcpy.Intersect_analysis(["FocalArea_For", "ForPoly"],
                                     'SideWalk_For', "ALL", "", "INPUT")
        tcRF.write(
            "Intersect the focus areas with the forest polygon layer to generate forest alongside roads.--"
            + time.strftime('%Y%m%d--%H%M%S') + '--\n')
        """ Dissolve the roads by road_ID """
        arcpy.Dissolve_management('SideWalk_For', 'SiWa_For_Blk', ["road_ID"],
                                  [["seg_area", "FIRST"]])
        tcRF.write(
            "Dissolve the forest along roads by the road identifier field: road_ID, maintain the Shape_Area field.--"
            + time.strftime('%Y%m%d--%H%M%S') + '--\n')
        """ Calcualte Percent Tree Cover """
        arcpy.AddField_management('SiWa_For_Blk', "Pct_TC", "FLOAT")
        arcpy.CalculateField_management('SiWa_For_Blk', "Pct_TC",
                                        "(!Shape_Area!*100)/!FIRST_seg_area!",
                                        "PYTHON_9.3")
        tcRF.write(
            "Calculate new variable in the forest grouped by road identifier layer: Pct_TC (float) = Shape_Area*100 / seg_area.--"
            + time.strftime('%Y%m%d--%H%M%S') + '--\n')
        """ Add the Percent Tree Cover back to the Block Segments """
        arcpy.JoinField_management('RdsByBlk_For', "OBJECTID", 'SiWa_For_Blk',
                                   "road_ID", "Pct_TC")
        tcRF.write(
            "Join the Pct_TC field to the road layer based on the road_ID field.--"
            + time.strftime('%Y%m%d--%H%M%S') + '--\n')

        codeblock1 = """def changenull(x):
            if x < 0:
                return 0
            else:
                return x"""
        arcpy.CalculateField_management('RdsByBlk_For', "Pct_TC",
                                        "changenull(!Pct_TC!)", "PYTHON_9.3",
                                        codeblock1)
        arcpy.DeleteField_management(
            'RdsByBlk_For', ['dirTrvl', 'numLanes', 'Mx_buff', 'Mn_buff'])
        tcRF.write("Change null values in the Pct_TC field to 0.--" +
                   time.strftime('%Y%m%d--%H%M%S') + '--\n')
        """ Clip to the Boundary """
        arcpy.Clip_analysis('RdsByBlk_For', freqDir + '/Bnd_Cty',
                            'PctStTC_Bnd')
        tcRF.write("Clip road file to the community boundary.--" +
                   time.strftime('%Y%m%d--%H%M%S') + '--\n')
        """ Project into Albers """
        arcpy.Project_management('PctStTC_Bnd', city + '_PctStTC', prjfileALB)
        tcRF.write("Project the road file into Albers.--" +
                   time.strftime('%Y%m%d--%H%M%S') + '--\n')
        """ Add to Final Directory """
        arcpy.FeatureClassToFeatureClass_conversion(city + '_PctStTC',
                                                    finalDir,
                                                    city + '_PctStTC')
        tcRF.write(
            "Copy the feature class to the final geodatabase for use in EnviroAtlas.--"
            + time.strftime('%Y%m%d--%H%M%S') + '--\n')
        """ Convert to Raster """
        arcpy.PolylineToRaster_conversion(
            'PctStTC_Bnd', 'Pct_TC', splitDir + '/' + city + '_PctStTC.tif',
            '', '', 10)
        tcRF.write(
            "Convert the road file to raster with the Pct_TC as the value field and a cell size of 10m.--"
            + time.strftime('%Y%m%d--%H%M%S') + '--\n')

        #-------- RUN GREEN SPACE ANALYSIS --------------------------------------
        """ Dissolve roads and split at intersections """
        arcpy.Dissolve_management(walkroads, 'GS_WalkRds')
        gsRF.write("Dissolve the Walkable Roads.--" +
                   time.strftime('%Y%m%d--%H%M%S') + '--\n')
        arcpy.SplitLineAtPoint_management('GS_WalkRds', 'Intersections',
                                          'RdsByBlk_GS', "3 Meters")
        gsRF.write(
            "Split the dissolved walkable roads at each intersection point to create road blocks.--"
            + time.strftime('%Y%m%d--%H%M%S') + '--\n')
        """ Create 50m Green Space Buffers """
        arcpy.Buffer_analysis('RdsByBlk_GS', 'FocalArea_GS', "25 Meters",
                              "FULL", "FLAT")
        gsRF.write(
            "Create the focus areas by buffering the road blocks by 25 meters with options FULL, FLAT, and NONE.--"
            + time.strftime('%Y%m%d--%H%M%S') + '--\n')
        """ Create segment IDs and calculate segment areas """
        arcpy.AddField_management('FocalArea_GS', "road_ID", "FLOAT")
        arcpy.AddField_management('FocalArea_GS', "seg_area", "FLOAT")
        arcpy.CalculateField_management('FocalArea_GS', "road_ID",
                                        "!ORIG_FID!", "PYTHON_9.3")
        arcpy.CalculateField_management('FocalArea_GS', "seg_area",
                                        "!Shape_area!", "PYTHON_9.3")
        gsRF.write(
            "Add and calculate fields road_ID (float) = ORIG_FID and seg_area (float) = Shape_area in the focus area feature class.--"
            + time.strftime('%Y%m%d--%H%M%S') + '--\n')
        """ If the LC isn't large enough, limit the output """
        if bigEnough == 0:
            arcpy.MakeFeatureLayer_management("FocalArea_GS", 'FA_GS_lyr')
            arcpy.SelectLayerByLocation_management('FA_GS_Lyr',
                                                   'COMPLETELY_WITHIN',
                                                   freqDir + '/LC_Poly', '',
                                                   'NEW_SELECTION')
            arcpy.CopyFeatures_management('FA_GS_Lyr', 'FocalArea_GS_EE')
            arcpy.SelectLayerByAttribute_management('FA_GS_lyr',
                                                    'CLEAR_SELECTION')
            gsRF.write(
                "Due to the extent of the Land Cover, the analysis area is smaller than the EnviroAtlas Community Boundary. Remove any features that are not within the analysis area.--"
                + time.strftime('%Y%m%d--%H%M%S') + '--\n')
        """ Intersect the Green Space Polygons with the Green Space Focus Area """
        arcpy.RepairGeometry_management("GBSPoly")
        try:
            arcpy.Intersect_analysis(['FocalArea_GS_EE', "GBSPoly"],
                                     'SideWalk_GS', "ALL", "", "INPUT")

        except:
            arcpy.Intersect_analysis(['FocalArea_GS', 'GBSPoly'],
                                     'SideWalk_GS', "ALL", "", "INPUT")
        gsRF.write(
            "Intersect the focus areas with the green space polygon layer to generate green space alongside roads.--"
            + time.strftime('%Y%m%d--%H%M%S') + '--\n')
        """ Dissolve the road segments by segement and maintain the road ID """
        arcpy.Dissolve_management('SideWalk_GS', 'SiWa_GS_Blk', ["road_ID"],
                                  [["seg_area", "FIRST"]])
        gsRF.write(
            "Dissolve the green space along roads by the road identifier field: road_ID, maintain the Shape_Area field.--"
            + time.strftime('%Y%m%d--%H%M%S') + '--\n')
        """ Calculate percent green space by segment """
        arcpy.AddField_management('SiWa_GS_Blk', "Pct_GS", "FLOAT")
        arcpy.CalculateField_management('SiWa_GS_Blk', "Pct_GS",
                                        "(!Shape_Area!*100)/!FIRST_seg_area!",
                                        "PYTHON_9.3")
        gsRF.write(
            "Calculate new variable in the green space grouped by road identifier layer: Pct_GS (float) = Shape_Area*100 / seg_area.--"
            + time.strftime('%Y%m%d--%H%M%S') + '--\n')
        """ Add the percent green space to the road segments """
        arcpy.JoinField_management('RdsByBlk_GS', "OBJECTID", 'SiWa_GS_Blk',
                                   "road_ID", "Pct_GS")
        gsRF.write(
            "Join the Pct_GS field to the road layer based on the road_ID field.--"
            + time.strftime('%Y%m%d--%H%M%S') + '--\n')
        """ Convert Nulls to 0 """
        codeblock2 = """def changenull(x):
            if x < 0:
                return 0
            else:
                return x"""
        arcpy.CalculateField_management('RdsByBlk_GS', "Pct_GS",
                                        "changenull(!Pct_GS!)", "PYTHON_9.3",
                                        codeblock2)
        arcpy.DeleteField_management(
            'RdsByBlk_GS', ['dirTrvl', 'numLanes', 'Mx_buff', 'Mn_buff'])
        gsRF.write("Change null values in the Pct_GS field to 0.--" +
                   time.strftime('%Y%m%d--%H%M%S') + '--\n')
        """ Clip to the Boundary """
        arcpy.Clip_analysis('RdsByBlk_GS', freqDir + '/Bnd_Cty', 'PctStGS_Bnd')
        gsRF.write("Clip road file to the community boundary.--" +
                   time.strftime('%Y%m%d--%H%M%S') + '--\n')
        """ Project into Albers """
        arcpy.Project_management('PctStGS_Bnd', city + '_PctStGS', prjfileALB)
        gsRF.write("Project the road file into Albers.--" +
                   time.strftime('%Y%m%d--%H%M%S') + '--\n')
        """ Add to Final Directory """
        arcpy.FeatureClassToFeatureClass_conversion(city + '_PctStGS',
                                                    finalDir,
                                                    city + '_PctStGS')
        gsRF.write(
            "Copy the feature class to the final geodatabase for use in EnviroAtlas.--"
            + time.strftime('%Y%m%d--%H%M%S') + '--\n')
        """ Convert to Raster """
        arcpy.PolylineToRaster_conversion(
            'PctStGS_Bnd', 'Pct_GS', splitDir + '/' + city + '_PctStGS.tif',
            '', '', 10)
        gsRF.write(
            "Convert the road file to raster with the Pct_GS as the value field and a cell size of 10m.--"
            + time.strftime('%Y%m%d--%H%M%S') + '--\n')

        print 'Green Space and Tree Cover Along Walkable Roads End Time: ' + time.asctime(
        ) + '\n'

        #-------- Block group summarized metrics (Ferdouz Cochran) ---------------
        """ Intersect street data with block groups """
        arcpy.Intersect_analysis([city + '_PctStTC', freqDir + '/' + 'BG_Alb'],
                                 city + '_BG_PctStTC', "ALL", "", "LINE")
        arcpy.Intersect_analysis([city + '_PctStGS', freqDir + '/' + 'BG_Alb'],
                                 city + '_BG_PctStGS', "ALL", "", "LINE")
        """ Calculate percent of total street length GS/TC """
        arcpy.AddField_management(city + '_BG_PctStTC', 'TC_length', "DOUBLE")
        arcpy.CalculateField_management(city + "_BG_PctStTC", 'TC_length',
                                        '(!Pct_TC! / 100.0) * !Shape_Length!',
                                        "PYTHON_9.3")
        arcpy.AddField_management(city + '_BG_PctStGS', 'GS_length', "DOUBLE")
        arcpy.CalculateField_management(city + "_BG_PctStGS", 'GS_length',
                                        '(!Pct_GS! / 100.0) * !Shape_Length!',
                                        "PYTHON_9.3")
        """ Summarize at block group level """
        arcpy.Statistics_analysis(
            city + '_BG_PctStTC', city + '_BG_PctStTC_sumstat',
            [["Shape_Length", "SUM"], ["TC_length", "SUM"]], "bgrp")
        arcpy.Statistics_analysis(
            city + '_BG_PctStGS', city + '_BG_PctStGS_sumstat',
            [["Shape_Length", "SUM"], ["GS_length", "SUM"]], "bgrp")
        """ Calculate percent of block group streets with GS/TC """
        arcpy.AddField_management(city + '_BG_PctStTC_sumstat', 'BG_PctStTC',
                                  "DOUBLE")
        arcpy.CalculateField_management(
            city + "_BG_PctStTC_sumstat", 'BG_PctStTC',
            '(!SUM_TC_length! / !SUM_Shape_Length!) * 100.0', "PYTHON_9.3")
        arcpy.AddField_management(city + '_BG_PctStGS_sumstat', 'BG_PctStGS',
                                  "DOUBLE")
        arcpy.CalculateField_management(
            city + "_BG_PctStGS_sumstat", 'BG_PctStGS',
            '(!SUM_GS_length! / !SUM_Shape_Length!) * 100.0', "PYTHON_9.3")
        """ Copy and join to BG features """
        arcpy.CopyFeatures_management(freqDir + '/' + 'BG_Alb',
                                      city + 'BG_GSTCnWR_summary')
        flds = [f.name for f in arcpy.ListFields(city + 'BG_GSTCnWR_summary')]
        for field in flds:
            if field not in ['bgrp']:
                try:
                    arcpy.DeleteField_management(city + 'BG_GSTCnWR_summary',
                                                 field)
                except:
                    pass
            else:
                pass
        arcpy.JoinField_management(city + 'BG_GSTCnWR_summary', 'bgrp',
                                   city + '_BG_PctStTC_sumstat', 'bgrp',
                                   'BG_PctStTC')
        arcpy.JoinField_management(city + 'BG_GSTCnWR_summary', 'bgrp',
                                   city + '_BG_PctStGS_sumstat', 'bgrp',
                                   'BG_PctStGS')

        #-------- COMPELETE LOGFILES ---------------------------------------------
        gsRF.close()
        tcRF.close()
        ReuseRF.close()

#-----------------------------------------------------------------------------
# END ANALYSIS
#-----------------------------------------------------------------------------
    except:
        """ This part of the script executes if anything went wrong in the main script above """
        #-------- PRINT ERRORS ---------------------------------------------------
        print "\nSomething went wrong.\n\n"
        print "Python Traceback Message below:"
        print traceback.format_exc()
        print "\nArcMap Error Messages below:"
        print arcpy.GetMessages(2)
        print "\nArcMap Warning Messages below:"
        print arcpy.GetMessages(1)

        #-------- COMPLETE LOGFILE ------------------------------------------------
        gsRF.write("\nSomething went wrong.\n\n")
        gsRF.write("Pyton Traceback Message below:")
        gsRF.write(traceback.format_exc())
        gsRF.write("\nArcMap Error Messages below:")
        gsRF.write(arcpy.GetMessages(2))
        gsRF.write("\nArcMap Warning Messages below:")
        gsRF.write(arcpy.GetMessages(1))

        gsRF.write("\n\nEnded at " + time.asctime() + '\n')
        gsRF.write("\n---End of Log File---\n")

        if gsRF:
            gsRF.close()
        if tcRF:
            tcRF.close()