Пример #1
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
Пример #2
0
 def calcular_distancia_oposta(self,linha_circulo, ponto_1, poligono_ma_sirgas, diretorio_saida):
     linha_circulo_buffer = linha_circulo.projectAs(self.spatial_proj_lambert).buffer(1).projectAs(self.spatial_geo_sirgas_2000)
     linha_ma_cortado = poligono_ma_sirgas.difference(linha_circulo_buffer)
     if  linha_ma_cortado.isMultipart:
         for n in range(linha_ma_cortado.partCount):
             parte = linha_ma_cortado.getPart(n)
             linha_ma_parte = Polyline(parte, self.spatial_geo_sirgas_2000)
             if linha_ma_parte.disjoint(ponto_1):
                 pass
             else:
                 linha_ma_distancia = linha_ma_parte.projectAs(self.spatial_proj_lambert).length + 1
     return linha_ma_distancia
Пример #3
0
def calc_distancia_oposta(dict_circ_desc, ponto_1):
    linha_circulo = dict_circ_desc["linha_circulo"]
    linha_circulo_buffer = linha_circulo.projectAs(projecao_plana).buffer(1).projectAs(projecao_geo)
    linha_ma_cortado = poligono_ma.difference(linha_circulo_buffer)
    if  linha_ma_cortado.isMultipart:
        for n in range(linha_ma_cortado.partCount):
            parte = linha_ma_cortado.getPart(n)
            linha_ma_parte = Polyline(parte, projecao_geo)
            if linha_ma_parte.disjoint(ponto_1):
                pass
            else:
                linha_ma_distancia = linha_ma_parte.projectAs(projecao_plana).length + 1
    return linha_ma_distancia
Пример #4
0
def funcao_multipart(linha, ponto):
    dict_partes = {}
    if linha.isMultipart:
        for n in range(linha.partCount):
            parte = linha.getPart(n)
            linha_parte = Polyline(parte, projecao_geo)
            linha_parte_lambert = linha_parte.projectAs(projecao_plana)
            if linha_parte_lambert.length > 0.8:
                if linha_parte.disjoint(ponto):
                    dict_partes["parte" + str(n)] = {"linha_array":parte, "cruza_ponto":False, "linha_geometria":linha_parte}
                else:
                    dict_partes["parte" + str(n)] = {"linha_array":parte, "cruza_ponto":True, "linha_geometria":linha_parte}
    return dict_partes
Пример #5
0
 def ponto_meio(self, list_partes, ponto):
     self.ptc_x = None
     self.ptc_y = None
     for parte in list_partes:
         parte_linha = Polyline(parte, self.spatial_geo_sirgas_2000)
         if parte_linha.disjoint(ponto):
             pontos_inte_linha_poligono = self.buffer_poligono_borda.intersect(parte_linha,1)
             self.pt1_x = pontos_inte_linha_poligono.getPart(0).X
             self.pt1_y = pontos_inte_linha_poligono.getPart(0).Y
             self.pt2_x = pontos_inte_linha_poligono.getPart(1).X
             self.pt2_y = pontos_inte_linha_poligono.getPart(1).Y
             self.ptc_x, self.ptc_y, self.ptc_x_inv, self.ptc_y_inv = PtCircBorda(self.x_b,self.y_b,self.pt1_x,self.pt1_y,self.pt2_x,self.pt2_y).ponto_circ_borda()
     return self.ptc_x, self.ptc_y
Пример #6
0
 def funcao_multipart(self, linha, ponto):
     list_partes = []
     if linha.isMultipart:
         for n in range(linha.partCount):
             parte = linha.getPart(n)
             linha_parte = Polyline(parte,self.spatial_geo_sirgas_2000)
             linha_parte_lambert = linha_parte.projectAs(self.spatial_proj_lambert)
             if linha_parte_lambert.length > 0.8:
                 list_partes.append(parte)
                 if linha_parte.disjoint(ponto):
                     self.dict_partes["parte" + str(n)] = {"linha_array":parte, "cruza_ponto":False, "linha_geometria":linha_parte}
                 else:
                     self.dict_partes["parte" + str(n)] = {"linha_array":parte, "cruza_ponto":True, "linha_geometria":linha_parte}
     return list_partes
Пример #7
0
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
Пример #8
0
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
Пример #9
0
def ponto_meio(ponto, dict_circulo, circ_borda):
    """funcao para gerar o ponto metade"""

    x_ptc = dict_circulo["pt_centro_circ"]["x_ptc"]
    y_ptc = dict_circulo["pt_centro_circ"]["y_ptc"]

    for parte_n in dict_circulo["partes"]:
        parte_linha = Polyline(dict_circulo["partes"][parte_n]["linha_array"], projecao_geo)
        if parte_linha.disjoint(ponto):
            pontos_inte_linha_poligono = circ_borda.intersect(parte_linha,1)
            x_pt1 = pontos_inte_linha_poligono.getPart(0).X
            y_pt1 = pontos_inte_linha_poligono.getPart(0).Y
            x_pt2 = pontos_inte_linha_poligono.getPart(1).X
            y_pt2 = pontos_inte_linha_poligono.getPart(1).Y
            x_ptm, y_ptm, x_ptm_inv, y_ptm_inv = PtCircBorda(x_ptc,y_ptc,x_pt1, y_pt1, x_pt2, y_pt2).ponto_circ_borda()
    return x_ptm, y_ptm, x_ptm_inv, y_ptm_inv
def testPolylineStartEndPointsMatchFunction(spatialReferenceToUse):
    testLineList = list()
    print('Trying testLine1')
    testLine1 = Polyline(
        arcpyArray(
            [Point(10000.38476, 22347.18506),
             Point(235021.997, 14251.778)]), spatialReferenceToUse)
    testLineList.append(testLine1)

    print('Trying testLine2')
    testLine2 = Polyline(
        arcpyArray(
            [Point(235021.997, 14251.778),
             Point(779221.8686, 925361.04623)]), spatialReferenceToUse)
    testLineList.append(testLine2)

    print('Trying testLine3')
    testLine3 = Polyline(
        arcpyArray([
            Point(227386.14822, 816234.4438),
            Point(226001.4771, 22347.18506)
        ]), spatialReferenceToUse)
    testLineList.append(testLine3)

    print('Trying testLine4')
    testLine4 = Polyline(
        arcpyArray(
            [Point(18245.9122, 44579.8436),
             Point(10000.38476, 22347.18506)]), spatialReferenceToUse)
    testLineList.append(testLine4)

    print('Trying testLine5')
    testLine5 = Polyline(
        arcpyArray(
            [Point(18245.9122, 44579.8436),
             Point(226001.4771, 22347.18506)]), spatialReferenceToUse)
    testLineList.append(testLine5)

    print('Trying testLine6')
    testLine6 = Polyline(
        arcpyArray([
            Point(847224.7665, 241233.9876),
            Point(779221.8686, 925361.04623)
        ]), spatialReferenceToUse)
    testLineList.append(testLine6)

    mockXYTolerance = 0.00328083333333

    for x1 in xrange(len(testLineList)):
        currentTestLineP1 = testLineList[x1]
        for y1 in xrange(x1 + 1, len(testLineList)):
            currentTestLineP2 = testLineList[y1]
            print("Testing: " + str(x1) + " and " + str(y1) + ".")
            print(
                polylineStartEndPointsMatch(currentTestLineP1,
                                            currentTestLineP2,
                                            mockXYTolerance))
Пример #11
0
    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)
Пример #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 _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
Пример #14
0
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))
Пример #15
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.")