def _array_to_poly_(arr, SR=None, as_type="Polygon"):
    """Convert array-like objects to arcpy geometry.

    This can include an `ndarray`, an `object array` or a `list of lists`
    which represent polygon or polyline geometry.

    Parameters
    ----------
    arr : list-like
        A list of arrays representing the poly parts, or an object array.
    SR : spatial reference
        Leave as None if not known.  Enclose in quotes. eg. "4326"
    as_type : text
        Polygon or Polyline.

    Notes
    -----
    Polygon geometries require a duplicate first and last point.
    Outer rings are ordered clockwise with inner rings (holes)
    counterclockwise.
    No check are made to the integrety of the geometry in this function.
    """
    subs = np.asarray(arr, dtype='O')
    aa = []
    for sub in subs:
        aa.append([Point(*pairs) for pairs in sub])
    if as_type.upper() == 'POLYGON':
        poly = Polygon(Array(aa), SR)
    elif as_type.upper() == 'POLYLINE':
        poly = Polyline(Array(aa), SR)
    return poly
示例#2
0
def calc_linha_ret(li_pla1, li_pla2, distancia, proj_geo, proj_plana):
    array = Array()
    ponto1 = li_pla1.positionAlongLine(distancia).projectAs(proj_geo)
    ponto2 = li_pla2.positionAlongLine(distancia).projectAs(proj_geo)
    pt_label1 = ponto1.labelPoint
    pt_label2 = ponto2.labelPoint
    array.add(pt_label1)
    array.add(pt_label2)
    linha_ret = Polyline(array, proj_geo)
    del array
    return linha_ret
示例#3
0
def calc_linhas_largura(dict_circ_desc, ponto):
    """criar linhas de largura"""
    if dict_circ_desc["tipo_circulo"] == "meio":
        linha_nao_intersecta_ponto = None
        point_circ = Point()
        point_circ.X = dict_circ_desc["pt_medios_circ"]["x_ptm"]
        point_circ.Y = dict_circ_desc["pt_medios_circ"]["y_ptm"]
        array = Array([point_circ, ponto.getPart(0)])
        linha_circulo = Polyline(array, projecao_geo)
        for parte_linha in dict_circ_desc["partes"]:
            if not dict_circ_desc["partes"][parte_linha]["cruza_ponto"]:
                linha_nao_intersecta_ponto = dict_circ_desc["partes"][parte_linha]["linha_geometria"]
        if linha_circulo.disjoint(linha_nao_intersecta_ponto):
            array.removeAll()
            point_circ = Point()
            point_circ.X = dict_circ_desc["pt_medios_circ"]["x_ptm_inv"]
            point_circ.Y = dict_circ_desc["pt_medios_circ"]["y_ptm_inv"]
            array = Array([point_circ, ponto.getPart(0)])
            linha_circulo = Polyline(array, projecao_geo)
            linha_largura = linha_circulo.intersect(poligono_ma, 2)
            array.removeAll()
        else:
            linha_largura = linha_circulo.intersect(poligono_ma, 2)
            array.removeAll()
        return linha_largura, linha_circulo
示例#4
0
def rotacionar_poligono(polygon, anchor_point, ang, proj_geo):
    array = Array()
    anchor_x = anchor_point.X
    anchor_y = anchor_point.Y
    for part in polygon:
        for point in part:
            x = point.X - anchor_x
            y = point.Y - anchor_y
            resultx = (x * math.cos(ang)) - (y * math.sin(ang)) + anchor_x
            resulty = (x * math.sin(ang)) + (y * math.cos(ang)) + anchor_y
            array.add(Point(resultx, resulty))
    result_polygon = Polygon(array, proj_geo)
    del array
    return result_polygon
    def arr2poly(a, SR):
        """Construct the poly feature from lists or arrays.

        The inputs may be nested and mixed in content.
        """
        aa = []
        for pairs in a:
            sub = pairs[0]
            oid = pairs[1]
            aa.append([Point(*pairs) for pairs in sub])
        if p_type.upper() == 'POLYGON':
            poly = Polygon(Array(aa), SR)
        elif p_type.upper() == 'POLYLINE':
            poly = Polyline(Array(aa), SR)
        return (poly, oid)
def fc_union(in_fc, poly_type="polygon"):
    """Union features in a featureclass.

    The output shape is built from its individual parts.
    Shared boundaries will be dissolved.

    Parameters
    ----------
    in_fc : featureclass
    poly_type : text
        Either `polygon` or `polyline`
    fc = "C:/Git_Dan/npgeom/Project_npg/tests.gdb/sq"
    """
    arr = []
    SR = get_SR(in_fc, verbose=False)
    with SearchCursor(in_fc, ['SHAPE@']) as cursor:
        for row in cursor:
            poly = row[0]
            for cnt in range(poly.partCount):
                part = poly.getPart(cnt)
                arr.append(part)
    a = Array(arr)
    if poly_type == "polygon":
        return Polygon(a, SR)
    elif poly_type == "polyline":
        return Polyline(a, SR)
    else:
        print("Not polygon or polyline")
        return None
 def _arr_poly_(arr, SR, as_type):
     """Slice the array where nan values appear, splitting them off."""
     subs = []
     s = np.isnan(arr[:, 0])
     if np.any(s):
         w = np.where(s)[0]
         ss = np.split(arr, w)
         subs = [ss[0]]
         subs.extend(i[1:] for i in ss[1:])
     else:
         subs.append(arr)
     aa = []
     for sub in subs:
         aa.append([Point(*pairs) for pairs in sub])
     if as_type.upper() == 'POLYGON':
         poly = Polygon(Array(aa), SR)
     elif as_type.upper() == 'POLYLINE':
         poly = Polyline(Array(aa), SR)
     return poly
示例#8
0
def ret_envolvente(polygon, proj_geo):
    array = Array()
    array.add(polygon.extent.lowerLeft)
    array.add(polygon.extent.lowerRight)
    array.add(polygon.extent.upperRight)
    array.add(polygon.extent.upperLeft)
    array.add(polygon.extent.lowerLeft)
    result_polygon = Polygon(array, proj_geo)
    del array
    return result_polygon
def view_poly(geo, id_num=1, view_as=2):
    """View a single poly feature as an SVG in the console.

    Parameters
    ----------
    geo : Geo array
        The Geo array part to view.
    id_num : integer
        The shape in the Geo array to view.
    view_as : integer
        Polygon = 2, Polygon = 1, Multipoint = 0

    Notes
    -----
    These provide information on the content of the svg representation.

    >>> p0.__getSVG__()
    >>> p0._repr_svg_()
    f = [" M {},{} " + "L {},{} "*(len(b) - 1) for b in g0.bits]
    ln = [f[i].format(*b.ravel()) for i, b in enumerate(g0.bits)]
    st = "".join(ln) + "z"
    """
    if id_num not in (geo.IDs):
        msg = "Id ... {} ... not found.\n Use geo.IDs to see their values"
        print(msg.format(id_num))
        return
    shp = geo.get_shapes(id_num)
    z = [Array([Point(*i) for i in b]) for b in shp.bits]
    if view_as == 2:
        return Polygon(Array(z))
    elif view_as == 1:
        return Polyline(Array(z))
    else:
        zz = []
        for i in z:
            zz.extend(i)
        return Multipoint(Array(zz))
def generate_squares(in_polygon, in_raster):
    from arcpy import Describe, Array, Point, Polygon, da
    desc = Describe(in_raster)
    eXMin = desc.extent.XMin
    eYMin = desc.extent.YMin
    eXMax = desc.extent.XMax
    eYMax = desc.extent.YMax

    offset = 1
    sqLen = 1
    # Store extent values as list of coordinate
    blX = eXMin - offset
    blY = eYMin - offset
    bottom_left_square = Array([
        Point(blX - sqLen, blY - sqLen),
        Point(blX - sqLen, blY),
        Point(blX, blY),
        Point(blX, blY - sqLen)
    ])
    trX = eXMax + offset
    trY = eYMax + offset
    top_right_square = Array([
        Point(trX, trY),
        Point(trX, trY + sqLen),
        Point(trX + sqLen, trY + sqLen),
        Point(trX + sqLen, trY)
    ])
    # Get coordinate system
    # Open an InsertCursor and insert the new geometry
    cursor = da.InsertCursor(in_polygon, ['SHAPE@'])
    for sq in [bottom_left_square, top_right_square]:
        # Create a polygon geometry
        polygon = Polygon(sq)
        cursor.insertRow([polygon])
    # Delete cursor object
    del cursor
def raster_extent_polygon(in_raster):
    from arcpy import Array, Point, Polygon, Describe
    desc = Describe(in_raster)
    XMin = desc.extent.XMin
    XMax = desc.extent.XMax
    YMin = desc.extent.YMin
    YMax = desc.extent.YMax
    # Create a polygon geometry
    array = Array([
        Point(XMin, YMin),
        Point(XMin, YMax),
        Point(XMax, YMax),
        Point(XMax, YMin)
    ])
    return Polygon(array)
示例#12
0
 def linha_de_largura(self, dict_descricao, ponto):
     if dict_descricao["tipo"] == "meio":
         linha_nao_intersecta_ponto = None
         point_circ = Point()
         point_circ.X = dict_descricao["ptc_x"]
         point_circ.Y = dict_descricao["ptc_y"]
         array = Array([point_circ, ponto.getPart(0)])
         linha_circulo = Polyline(array,self.spatial_geo_sirgas_2000)
         for parte_linha in self.dict_partes:
             if self.dict_partes[parte_linha]["cruza_ponto"] == False:
                 linha_nao_intersecta_ponto = self.dict_partes[parte_linha]["linha_geometria"]
         if linha_circulo.disjoint(linha_nao_intersecta_ponto):
             array.removeAll()
             point_circ = Point()
             point_circ.X = self.ptc_x_inv
             point_circ.Y = self.ptc_y_inv
             array = Array([point_circ, ponto.getPart(0)])
             linha_circulo = Polyline(array,self.spatial_geo_sirgas_2000)
             linha_largura = linha_circulo.intersect(self.poligono_ma_geo, 2)
             array.removeAll()
         else:
             linha_largura = linha_circulo.intersect(self.poligono_ma_geo, 2)
             array.removeAll()
         return linha_largura, linha_circulo
示例#13
0
def _trim_shoreline(islands):
    """
    Trim the shoreline of micro-islands. This makes 
    permanent changes to the Shapefile.
    """
    for island in islands:
        path = path_to_shoreline(island)
        pair = max(TableToNumPyArray(path, ["OID@", "SHAPE@AREA"]),
                   key=lambda p: p[1])
        with UpdateCursor(path, ["OID@", "SHAPE@"]) as cursor:
            for row in cursor:
                if row[0] != pair[0]:
                    cursor.deleteRow()
                else:
                    row_new = Array()
                    for part in row[1]:
                        part_new = Array()
                        for point in part:
                            if point is None:
                                break
                            part_new.add(point)
                        row_new.add(part_new)
                    row[1] = Polygon(row_new)
                    cursor.updateRow(row)
示例#14
0
def bases_larguras(polygon, proj_geo):
    array1 = Array()
    array2 = Array()
    array3 = Array()
    array4 = Array()
    point1 = None
    point2 = None
    point3 = None
    point4 = None
    for part in polygon:
        point1 = part[0]
        point2 = part[1]
        point3 = part[2]
        point4 = part[3]
    array1.add(point1); array1.add(point2)
    array2.add(point2); array2.add(point3)
    array3.add(point4); array3.add(point3)
    array4.add(point1); array4.add(point4)
    li1 = Polyline(array1, proj_geo)
    li2 = Polyline(array2, proj_geo)
    li3 = Polyline(array3, proj_geo)
    li4 = Polyline(array4, proj_geo)
    if li1.length > li2.length:
        lista_base = [li1, li3]
        lista_largura = [li2, li4]
    else:
        lista_base = [li2, li4]
        lista_largura = [li1, li3]
    del array1
    del array2
    del array3
    del array4
    return lista_base, lista_largura
shp_out = GetParameterAsText(1)


### Variables utiles

chp_x = "xCentroid"
chp_y = "yCentroid"

expr_centrX = "!SHAPE.CENTROID!.split()[0]"
expr_centrY = "!SHAPE.CENTROID!.split()[1]"

new_shp(path.dirname(shp_out), path.basename(shp_out), "Point", spatial_reference = shp_in)

add = curs_ins(shp_out)

ptArray = Array()
pt = Point()

### Préalables
new_chp(shp_in, chp_x, "DOUBLE", 18, 11)
new_chp(shp_in, chp_y, "DOUBLE", 18, 11)


### Calcul des centroids
calc_chp(shp_in, chp_x, expr_centrX, "PYTHON")
calc_chp(shp_in, chp_y, expr_centrY, "PYTHON")

rows = curs_rec(shp_in)

i = 0
for objet in rows:
def extendAndIntersectRoadFeatures(
    quarterOrHalf
):  # Place the operations that extend each road line segment by a certain distance here.
    # Should extend all the features that exist in the post-erase dataset. Might be more difficult
    # to calculate the angle of these lines accurately, but it should be easier to figure out
    # than trying to get the lines to split correctly with the buggy SplitLineAtPoint tool.

    if quarterOrHalf.lower() == "quarter":
        extensionLinesTextName = "createdExtensionLines_Q"
        createdExtensionLines = createdExtensionLines_Q
        # 9000 ft increase for _Q version.
        # Must be larger than the county bufferDistance (20000)
        extensionDistance = 31176
        extensionLinesTextName = "createdExtensionLines_Q"
        countyRoadNameRosette = countyRoadNameRosette_Q
        rosetteTextName = "countyRoadNameRosette_Q"
        tempRoadNameRosette = tempRoadNameRosette_Q
        tempRosetteTextName = "tempRoadNameRosette_Q"
        tempRoadNameRosetteSP = tempRoadNameRosetteSinglePoint_Q
        tempRosetteSPTextName = "tempRoadNameRosetteSinglePoint_Q"
        countyBorderFeature = countyBorderFeature_Q
    elif quarterOrHalf.lower() == "half":
        extensionLinesTextName = "createdExtensionLines_H"
        createdExtensionLines = createdExtensionLines_H
        # Must be larger than the county bufferDistance (11000)
        extensionDistance = 22176
        extensionLinesTextName = "createdExtensionLines_H"
        countyRoadNameRosette = countyRoadNameRosette_H
        rosetteTextName = "countyRoadNameRosette_H"
        tempRoadNameRosette = tempRoadNameRosette_H
        tempRosetteTextName = "tempRoadNameRosette_H"
        tempRoadNameRosetteSP = tempRoadNameRosetteSinglePoint_H
        tempRosetteSPTextName = "tempRoadNameRosetteSinglePoint_H"
        countyBorderFeature = countyBorderFeature_H
    else:
        print "quarterOrHalf variable not correctly defined."
        raise (Exception("quarterOrHalf value error."))

    print "Starting to extend and intersect road features."

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

    CreateFeatureclass_management(inMemGDB, extensionLinesTextName, "POLYLINE",
                                  "", "", "", spatialReferenceProjection)

    # Add a column for roadname called roadNameForSplit.
    AddField_management(createdExtensionLines, "roadNameForSplit", "TEXT", "",
                        "", "55")

    # Add a column which stores the angle to display a label called called LabelAngle.
    AddField_management(createdExtensionLines, "LabelAngle", "DOUBLE", "", "",
                        "")  # Change to double.

    # Add a column which stores the County Number.
    AddField_management(createdExtensionLines, "County_Number", "DOUBLE", "",
                        "", "")

    roadLinesToInsertList = list()

    roadLinesList = getRoadLinesList()

    for roadLinesItem in roadLinesList:

        roadNameToUse = roadLinesItem[2]
        countyNumber = roadLinesItem[3]

        linePointsArray = ArcgisArray()

        firstPointTuple = (roadLinesItem[1].firstPoint.X,
                           roadLinesItem[1].firstPoint.Y)
        lastPointTuple = (roadLinesItem[1].lastPoint.X,
                          roadLinesItem[1].lastPoint.Y)

        # Make this a two-step process.
        # Might be as simple as
        # adding _1 to the end of the first set of variables,
        # adding _2 to the end of the second set of variables,
        # then making the extensions in both directions
        # and creating a new line that has the endpoints
        # from both sides as it's first and last point.
        # if necessary, could add the other points in between
        # but probably not necessary just for generating
        # an intersection point.

        yValue_1 = -(lastPointTuple[1] - firstPointTuple[1]
                     )  # made y value negative
        xValue_1 = lastPointTuple[0] - firstPointTuple[0]

        lineDirectionAngle_1 = math.degrees(math.atan2(
            xValue_1, yValue_1))  # reversed x and y

        lineDirectionAngle_1 = -(((lineDirectionAngle_1 + 180) % 360) - 180
                                 )  # correction for certain quadrants
        #print "lineDirectionAngle: " + str(lineDirectionAngle_1)

        origin_x_1 = firstPointTuple[0]
        origin_y_1 = firstPointTuple[1]

        yValue_2 = -(firstPointTuple[1] - lastPointTuple[1]
                     )  # made y value negative
        xValue_2 = firstPointTuple[0] - lastPointTuple[0]

        lineDirectionAngle_2 = math.degrees(math.atan2(
            xValue_2, yValue_2))  # reversed x and y

        lineDirectionAngle_2 = -(((lineDirectionAngle_2 + 180) % 360) - 180
                                 )  # correction for certain quadrants
        #print "lineDirectionAngle: " + str(lineDirectionAngle_2)

        origin_x_2 = lastPointTuple[0]
        origin_y_2 = lastPointTuple[1]

        (disp_x_1, disp_y_1) = (extensionDistance *
                                math.sin(math.radians(lineDirectionAngle_1)),
                                extensionDistance *
                                math.cos(math.radians(lineDirectionAngle_1)))

        (end_x_1, end_y_1) = (origin_x_1 + disp_x_1, origin_y_1 + disp_y_1)

        (disp_x_2, disp_y_2) = (extensionDistance *
                                math.sin(math.radians(lineDirectionAngle_2)),
                                extensionDistance *
                                math.cos(math.radians(lineDirectionAngle_2)))

        (end_x_2, end_y_2) = (origin_x_2 + disp_x_2, origin_y_2 + disp_y_2)

        startPoint = ArcgisPoint()
        endPoint = ArcgisPoint()

        startPoint.ID = 0
        startPoint.X = end_x_1
        startPoint.Y = end_y_1

        endPoint.ID = 1
        endPoint.X = end_x_2
        endPoint.Y = end_y_2

        linePointsArray.add(startPoint)
        linePointsArray.add(endPoint)

        newLineFeature = ArcgisPolyLine(linePointsArray)

        # Need to create an extension for both ends of the line and add them
        # to the array.

        #newLineFeature = createdExtensionLinesCursor.newRow()

        #newLineFeature.SHAPE = linePointsArray

        lineDirectionOutput = "0"

        if lineDirectionAngle_1 > 0:
            lineDirectionOutput = lineDirectionAngle_1
        elif lineDirectionAngle_2 > 0:
            lineDirectionOutput = lineDirectionAngle_2
        else:
            pass

        roadLinesToInsertList.append(
            [newLineFeature, roadNameToUse, lineDirectionOutput, countyNumber])

        #createdExtensionLinesCursor.insertRow([newLineFeature, roadNameToUse, lineDirectionOutput])

        if "newLineFeature" in locals():
            del newLineFeature
        else:
            pass

    # Consider building this as a separate list and then just looping
    # through the list to put it into the cursor instead
    # of doing logic and inserting into the cursor at the same place.

    #start editing session
    #newEditingSession = daEditor(sqlGdbLocation)
    #newEditingSession.startEditing()
    #newEditingSession.startOperation()

    createdExtensionLinesCursor = daInsertCursor(
        createdExtensionLines,
        ["SHAPE@", "roadNameForSplit", "LabelAngle", "County_Number"])

    for roadLinesToInsertItem in roadLinesToInsertList:
        createdExtensionLinesCursor.insertRow(roadLinesToInsertItem)

    # End editing session
    #newEditingSession.stopOperation()
    #newEditingSession.stopEditing(True)

    if "createdExtensionLinesCursor" in locals():
        del createdExtensionLinesCursor
    else:
        pass

    # Remove the previous countyRoadNameRosette so that it can be recreated.
    if Exists(rosetteTextName):
        Delete_management(rosetteTextName)
    else:
        pass

    CreateFeatureclass_management(sqlGdbLocation, rosetteTextName, "POINT", "",
                                  "", "", spatialReferenceProjection)

    AddField_management(countyRoadNameRosette, "roadNameForSplit", "TEXT", "",
                        "", "55")

    AddField_management(countyRoadNameRosette, "LabelAngle", "DOUBLE", "", "",
                        "")  # Change to double.

    AddField_management(countyRoadNameRosette, "County_Number", "DOUBLE", "",
                        "", "")

    AddField_management(countyRoadNameRosette, "COUNTY_NAME", "TEXT", "", "",
                        "55")

    # Now then, need to check for the existence
    # of and delete the point intersection layer
    # if it exists.

    # Then, recreate it and the proper fields.

    inMemoryCountyBorderExtension = "aCountyBorderExtensionBuffer"
    inMemoryExtensionLines = "aLoadedExtensionLines"

    try:
        Delete_management(inMemoryCountyBorderExtension)
    except:
        pass

    try:
        Delete_management(inMemoryExtensionLines)
    except:
        pass

    # Temporary layer, use CopyFeatures_management to persist to disk.
    MakeFeatureLayer_management(
        countyBorderFeature,
        inMemoryCountyBorderExtension)  # County Border extension feature

    # Temporary layer, use CopyFeatures_management to persist to disk.
    MakeFeatureLayer_management(
        createdExtensionLines,
        inMemoryExtensionLines)  # Line extension feature

    borderFeatureList = getBorderFeatureList(quarterOrHalf)

    borderFeatureList = sorted(borderFeatureList,
                               key=lambda feature: feature[3])

    for borderFeature in borderFeatureList:
        borderFeatureName = borderFeature[2]
        borderFeatureNumber = borderFeature[3]
        print "borderFeatureName: " + str(
            borderFeatureName) + " & borderFeatureNumber: " + str(
                int(borderFeatureNumber))

        countyBorderWhereClause = ' "COUNTY_NUMBER" = ' + str(
            int(borderFeatureNumber)) + ' '

        SelectLayerByAttribute_management(inMemoryCountyBorderExtension,
                                          "NEW_SELECTION",
                                          countyBorderWhereClause)

        countyBorderSelectionCount = GetCount_management(
            inMemoryCountyBorderExtension)

        print "County Borders Selected: " + str(countyBorderSelectionCount)

        # Had to single-quote the borderFeatureNumber because it is stored as a string in the table.
        # Unsingle quoted because it was changed to a float.
        extensionLinesWhereClause = ' "COUNTY_NUMBER" = ' + str(
            int(borderFeatureNumber)) + ' '

        SelectLayerByAttribute_management(inMemoryExtensionLines,
                                          "NEW_SELECTION",
                                          extensionLinesWhereClause)

        extensionLineSelectionCount = GetCount_management(
            inMemoryExtensionLines)

        print "Extension Lines Selected: " + str(extensionLineSelectionCount)

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

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

        Intersect_analysis(
            [inMemoryCountyBorderExtension, inMemoryExtensionLines],
            tempRoadNameRosette, "ALL", "", "POINT")

        # Intersect to an output temp layer.

        # Next, need to loop through all of the counties.

        # Get the county number and use it to select
        # a county extension buffer in the county
        # extension buffers layer.

        # Then, use the county number to select
        # all of the lines for that county
        # in the extension lines layer.

        # Then, export those to a temp layer in the fgdb.

        # Change multipoint to singlepoint.

        # Was working until I moved from gisprod to sdedev for the data source.
        # not sure why. Check to make sure projections match.
        # ^ Fixed.

        try:

            # Run the tool to create a new fc with only singlepart features
            MultipartToSinglepart_management(tempRoadNameRosette,
                                             tempRoadNameRosetteSP)

            # Check if there is a different number of features in the output
            #   than there was in the input
            inCount = int(
                GetCount_management(tempRoadNameRosette).getOutput(0))
            outCount = int(
                GetCount_management(tempRoadNameRosetteSP).getOutput(0))

            if inCount != outCount:
                print "Found " + str(outCount -
                                     inCount) + " multipart features."
                #print "inCount, including multipart = " + str(inCount)
                #print "outCount, singlepart only = " + str(outCount)

            else:
                print "No multipart features were found"

        except ExecuteError:
            print GetMessages()
        except Exception as e:
            print e

        print "Appending the temp point layer to the county point intersection layer."

        Append_management([tempRoadNameRosetteSP], countyRoadNameRosette,
                          "NO_TEST")

        # K, worked correctly. Just need to change LabelAngle to a float and it might be what
        # I want.

        print "Done adding points to the countyRoadNameRosette feature class."
示例#17
0
def main():
    # tool inputs
    INPUT_NETWORK = argv[1]
    INPUT_POINTS = argv[2]
    INPUT_ORIGINS_FIELD = argv[3]
    INPUT_DESTINATIONS_FIELD = argv[4]
    INPUT_COEFF = float(argv[5])
    INPUT_SEARCH_RADIUS = float(argv[6]) if is_number(
        argv[6]) else float('inf')
    INPUT_OUTPUT_DIRECTORY = argv[7]
    INPUT_OUTPUT_FEATURE_CLASS_NAME = argv[8]
    INPUT_COMPUTE_WAYFINDING = argv[9] == "true"
    INPUT_VISUALIZATION = argv[10]

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

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

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

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

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

    # setup
    env.overwriteOutput = True

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

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

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

    array.add(linha_app.firstPoint)
    array.add(linha_app.lastPoint)
    if bool_interseccao_entre_linhas(((l1_lastX,l1_lastY),(l2_lastX,l2_lastY)),((l1_firstX,l1_firstY),(l2_firstX,l2_firstY))):
        array.add(linha_app_frente.firstPoint)
        array.add(linha_app_frente.lastPoint)
    else:
        array.add(linha_app_frente.lastPoint)
        array.add(linha_app_frente.firstPoint)
    array.add(linha_app.firstPoint)
    polygon = Polygon(array, projecao_geo)
    array.removeAll()
    del array
    polygon = polygon.buffer(0.000000001)
    return polygon