def create_walk_groups(zones, name, inverse=False):
    """If different walk distances must be used in the creation of
    isochrones for different stops they must be generated by separate
    executions of the service area analysis. This function creates
    separate feature classes for those groups, the zones parameter
    must be a list
    """

    # Create a feature layer so that selections can be made on the data
    stops_layer = 'max_stops'
    MakeFeatureLayer(MAX_STOPS, stops_layer)

    # Assign a variable that will determine if the output is the zones
    # provide or all of the zones that are not provided
    negate = 'NOT' if inverse else ''

    select_type = 'NEW_SELECTION'
    zones_str = ', '.join("'{}'".format(z) for z in zones)
    where_clause = '"{0}" {1} IN ({2})'.format(ZONE_FIELD, negate, zones_str) 
    SelectLayerByAttribute(stops_layer, select_type, where_clause)

    zone_stops = join(TEMP_DIR, '{}.shp'.format(name))
    CopyFeatures(stops_layer, zone_stops)

    return zone_stops
Exemple #2
0
def _tri_tool():
    """Triangulation for tool
    """
    in_fc = sys.argv[1]
    tri_type = sys.argv[2]
    out_fc = sys.argv[3]
    xtent = sys.argv[4]
    desc = Describe(in_fc)
    SR = desc['spatialReference']
    flds = ['SHAPE@X', 'SHAPE@Y']
    allpnts = False
    z = FeatureClassToNumPyArray(in_fc, flds, "", SR, allpnts)
    a = np.zeros((z.shape[0], 2), dtype='<f8')
    a[:, 0] = z['SHAPE@X']
    a[:, 1] = z['SHAPE@Y']
    #
    if tri_type == 'Delaunay':
        tweet("Delaunay... clip extent {}".format(xtent))
        t = tri_pnts(a, True)  # must be a list of list of points
        polys = poly(t, SR)
        if Exists(out_fc):
            Delete(out_fc)
        CopyFeatures(polys, "in_memory/temp")
        MakeFeatureLayer("in_memory/temp", "temp")
        if xtent not in ("", None):
            Clip("temp", xtent, out_fc, None)
        else:
            CopyFeatures("temp", out_fc)
    else:
        tweet("Voronoi... clip extent {}".format(xtent))
        c = infinity_circle(a, fac=10)
        aa = np.vstack((a, c))
        v = vor_pnts(aa, testing=False)
        polys = poly([v], SR)
        if Exists(out_fc):
            Delete(out_fc)
        CopyFeatures(polys, "in_memory/temp")
        MakeFeatureLayer("in_memory/temp", "temp")
        if xtent not in (
                "",
                None,
        ):
            Clip("temp", xtent, out_fc, None)
        else:
            CopyFeatures("temp", out_fc)
def execute_ChannelCorrection(demras, boundary, riverbed, rivernet, breachedmnt, messages):

    arcpy.env.outputCoordinateSystem = demras.spatialReference
    env.snapRaster = demras

    ends = CreateScratchName("loob", data_type="FeatureClass", workspace="in_memory")
    CopyFeatures(boundary, ends)

    AddField(ends, "dummy", "LONG", field_alias="dummy", field_is_nullable="NULLABLE")
    CalculateField(ends, "dummy", "1", "PYTHON")

    endsras = CreateScratchName("loras", data_type="RasterDataset", workspace=env.scratchWorkspace)
    PolylineToRaster(ends, "dummy", endsras, "MAXIMUM_LENGTH", cellsize=demras)
    statpts = FocalStatistics(endsras, NbrRectangle(3, 3, "CELL"), "MAXIMUM", "DATA")

    env.extent = demras

    rasterbed = CreateScratchName("loras", data_type="RasterDataset", workspace=env.scratchWorkspace)
    PolygonToRaster(riverbed, arcpy.Describe(riverbed).OIDFieldName, rasterbed, "CELL_CENTER", cellsize=demras)
    rasterline = CreateScratchName("loras", data_type="RasterDataset", workspace=env.scratchWorkspace)
    PolylineToRaster(rivernet, arcpy.Describe(rivernet).OIDFieldName, rasterline, cellsize=demras)

    streambed = Con(IsNull(rasterline), Con(IsNull(rasterbed) == 0, 1), 1)

    bedwalls = FocalStatistics(streambed, NbrRectangle(3, 3, "CELL"), "MAXIMUM", "DATA")

    env.extent = bedwalls

    chanelev = Con(streambed, demras)
    chanmax = chanelev.maximum
    chanwalls = chanelev.minimum - 100
    switchtemp = CreateScratchName("loras", data_type="RasterDataset", workspace=env.scratchWorkspace)
    switchelev = -1 * (Con(IsNull(streambed), Con(bedwalls, Con(IsNull(statpts), chanwalls)), chanelev) - chanmax)
    switchelev.save(switchtemp)
    Delete(statpts)
    Delete(chanelev)

    switchfilled = Fill(switchtemp)
    Delete(switchtemp)

    env.extent = demras
    breachedtemp = Con(IsNull(streambed), demras, (-1*switchfilled) + chanmax)
    breachedtemp.save(breachedmnt)

    Delete(bedwalls)
    Delete(endsras)
    Delete(rasterline)
    Delete(rasterbed)
    Delete(switchfilled)
    return
Exemple #4
0
def tri_poly(in_fc, gdb, name, out_kind, constrained=True):
    """Return the Delaunay triangulation of the poly* features."""
    tmp = MultipartToSinglepart(in_fc, r"memory\in_fc_temp")  # in_fc = tmp
    g, oids, shp_kind, k, m, SR = _in_(tmp, info="triangulate")
    out = g.triangulate(as_one=False, as_polygon=True)
    x, y = g.LL
    g0 = out.translate(dx=x, dy=y)
    if constrained:
        tmp_name = temp_fc(g0, "tmp", shp_kind, SR)  # make temp featureclass
        tmp_lyr = MakeFeatureLayer(tmp_name)
        SelectLayerByLocation(tmp_lyr, "WITHIN", tmp, None, "NEW_SELECTION",
                              "NOT_INVERT")
        out_name = gdb.replace("\\", "/") + "/" + name
        CopyFeatures(tmp_lyr, out_name)
    else:
        _out_(g0, gdb, name, shp_kind, SR)
    return
def geometry_fc(a, IFT, p_type=None, gdb=None, fname=None, sr=None):
    """Form poly features from the list of arrays created by `fc_geometry`.

    Parameters
    ----------
    a : array or list of arrays
        Some can be object arrays, normally created by ``pnts_arr``
    IFT : list/array
        Identifies which feature each input belongs to.  This enables one to
        account for multipart shapes
    p_type : string
        Uppercase geometry type eg POLYGON.
    gdb : text
        Geodatabase path and name.
    fname : text
        Featureclass name.
    sr : spatial reference
        name or object

    Returns
    -------
    Singlepart and/or multipart featureclasses.

    Notes
    -----
    The work is done by ``array_poly``.
    """
    if p_type is None:
        p_type = "POLYGON"
    out = array_poly(a, p_type.upper(), sr=sr, IFT=IFT)  # call array_poly
    name = gdb + "/" + fname
    wkspace = env.workspace = 'memory'  # legacy is in_memory
    CreateFeatureclass(wkspace, fname, p_type, spatial_reference=sr)
    AddField(fname, 'ID_arr', 'LONG')
    with InsertCursor(fname, ['SHAPE@', 'ID_arr']) as cur:
        for row in out:
            cur.insertRow(row)
    CopyFeatures(fname, name)
    return
def Geo_to_fc(geo, gdb=None, name=None, kind=None, SR=None):
    """Return a FeatureClass from a Geo array."""
    SR = SR
    if kind in (None, 0, 1, 2):
        print("\n ``kind`` must be one of Polygon, Polyline or Point.")
        return None
    #
    # dx, dy = geo.LL
    # geo = geo.shift(dx, dy)
    polys = Geo_to_arc_shapes(geo, as_singlepart=True)
    out_name = gdb.replace("\\", "/") + "/" + name
    wkspace = env.workspace = 'memory'  # legacy is in_memory
    tmp_name = "{}\\{}".format(wkspace, "tmp")
    if Exists(tmp_name):
        Delete(tmp_name)
    CreateFeatureclass(wkspace, "tmp", kind, spatial_reference=SR)
    AddField("tmp", 'ID_arr', 'LONG')
    with InsertCursor("tmp", ['SHAPE@', 'ID_arr']) as cur:
        for row in polys:
            cur.insertRow(row)
    CopyFeatures("tmp", out_name)
    return
Exemple #7
0
def process():
    class LicenseError(Exception):
        pass

    try:
        if CheckExtension("ImageAnalyst") == "Available":
            CheckOutExtension("ImageAnalyst")
        else:
            # raise a custom exception
            raise LicenseError

        # System Parameters
        tile_name = "FileName"

        # Begin Script
        temp_fc = join("in_memory", "temp_fc")
        CopyFeatures(in_fc, temp_fc)
        for f in file_names:
            AddField(temp_fc, f, "TEXT")

        df = pd.read_excel(in_xlsx, index_col=0)

        def attribute_tile(in_feature_class,
                           in_tile_name,
                           in_df,
                           in_name,
                           xlsx_row_name=xlsx_row_name):
            with da.UpdateCursor(in_feature_class,
                                 [in_tile_name, in_name]) as cursor:
                for fc_r in cursor:
                    for df_i, df_r in in_df.iterrows():
                        url = df_r[xlsx_row_name]
                        n = Path(url).stem
                        t_name = fc_r[0]
                        t_n = Path(t_name).stem
                        if n.startswith(in_name) and t_n in n:
                            fc_r[1] = url
                    cursor.updateRow(fc_r)

        # Attribute the LiDAR Derivatives
        for n in file_names:
            attribute_tile(temp_fc, tile_name, df, n)

        def attribute_tile_lidar(in_feature_class,
                                 in_tile_name,
                                 in_df,
                                 in_name,
                                 xlsx_row_name=xlsx_row_name):
            with da.UpdateCursor(in_feature_class,
                                 [in_tile_name, in_name]) as cursor:
                for fc_r in cursor:
                    for df_i, df_r in in_df.iterrows():
                        url = df_r[xlsx_row_name]
                        n = split(url)[1]
                        t_name = fc_r[0]
                        if n == t_name:
                            fc_r[1] = url
                    cursor.updateRow(fc_r)

        # Attribute the LiDAR tile now
        AddField(temp_fc, in_lidar_format, "TEXT")
        attribute_tile_lidar(temp_fc,
                             tile_name,
                             df,
                             in_lidar_format,
                             xlsx_row_name=xlsx_row_name)
        '''
        # Print Fields for debugging/assessing results of above operations
        file_names.append(in_lidar_format)
        print(file_names)
        with da.SearchCursor(temp_fc, file_names) as cursor:
            for fc_r in cursor:
                print(fc_r)
        '''

        # Delete Pandas Dataframe from Memory
        del df

        # Copy in_memory temporary feature class to output location
        CopyFeatures(temp_fc, out_fc)

        # Delete Temporary Feature Class
        Delete(temp_fc)

        # Check back in Image Analyst license
        CheckInExtension("ImageAnalyst")
    except LicenseError:
        AddError("ImageAnalyst license is unavailable")
        print("ImageAnalyst license is unavailable")
    except ExecuteError:
        AddError(GetMessages(2))
        print(GetMessages(2))