Exemplo n.º 1
0
    def __init__(self, path, layer_type=None):
        """Initialize the class.

        Required:  path -
        """
        try:
            desc = Describe(path)
        except IOError as e:
            raise LayerError(e)

        workspace, name = os.path.split(desc.catalogPath)
        dataset = ""
        workspace_desc = Describe(workspace)

        if hasattr(workspace_desc, "datasetType") and \
                workspace_desc.datasetType == DATASET_TYPECODE:
            workspace, dataset = os.path.split(workspace)

        self.workspace = workspace
        self.dataset = dataset
        self.name = name

        if not layer_type:
            try:
                layer_type = desc.dataType
            except AttributeError:
                raise LayerError("Could not determine layer type.")

        self.type = layer_type

        print name, layer_type
def get_images_and_stats(in_mosaic):
    images = get_image_paths(in_mosaic)
    s_list = []
    if isinstance(images, str):  # If input is single image set as list
        images = [images]
    # Obtain Extent Coords of each image
    for i in images:
        if i.lower().endswith('.jpg'):
            desc = Describe(i + "/Band_1")
            s_list.append([
                i, desc.extent.XMin, desc.extent.XMax, desc.extent.YMin,
                desc.extent.YMax, desc.height, desc.width
            ])
        else:
            if ".Overviews" not in i:
                desc = Describe(i)
                from arcpy import RasterToNumPyArray
                arr = RasterToNumPyArray(i + "/Blue", nodata_to_value=0)
                height, width = arr.shape
                s_list.append([
                    i, desc.extent.XMin, desc.extent.XMax, desc.extent.YMin,
                    desc.extent.YMax, height, width
                ])
                del arr
    # Determine Maximum and Minimum coord values from list
    # -- Note: The extent values from the mosaic differ from the actual tiles... esri bug on mosaics probably.
    XMin = min(s_list, key=lambda x: x[1])[1]
    XMax = max(s_list, key=lambda x: x[2])[2]
    YMin = min(s_list, key=lambda x: x[3])[3]
    YMax = max(s_list, key=lambda x: x[4])[4]
    extent = [XMin, XMax, YMin, YMax]
    # Detect of each image within the mosaic dataset
    c = 0
    for i in s_list:
        iXMin = i[1]
        iXMax = i[2]
        iYMin = i[3]
        iYMax = i[4]
        # Check for Corners
        if XMin == iXMin and YMin == iYMin:
            s_list[c].append("bl")
        elif XMin == iXMin and YMax == iYMax:
            s_list[c].append("tl")
        elif XMax == iXMax and YMax == iYMax:
            s_list[c].append("tr")
        elif XMax == iXMax and YMin == iYMin:
            s_list[c].append("br")
        # Check for Edges
        elif XMin == iXMin:
            s_list[c].append("l")
        elif YMax == iYMax:
            s_list[c].append("t")
        elif XMax == iXMax:
            s_list[c].append("r")
        elif YMin == iYMin:
            s_list[c].append("b")
        else:
            s_list[c].append("i")
        c += 1
    return s_list, extent
Exemplo n.º 3
0
def calculatePointElevationField(points, raster, field_name):

    #monitor progress by counting features
    view = MakeTableView_management(points, 'points')
    count = int(GetCount_management('points').getOutput(0))
    SetProgressor('step', 'Extracting point elevations', 0, count)
    AddMessage('{} features to process'.format(count))

    # Get the object id field
    oid = Describe(points).OIDFieldName

    # make an update cursor and update each row's elevation field
    cursor = UpdateCursor(points, [field_name, 'SHAPE@', oid])

    # make a temporary dict to store our elevation values we extract
    elevations = {}

    for row in cursor:
        row[0] = getElevationAtPoint(raster, row[1])
        cursor.updateRow(row)
        AddMessage('row updated to {}; oid: {}'.format(row[0], row[2]))
        SetProgressorPosition()

    # release the data
    del cursor

    #reset this progressor
    ResetProgressor()
Exemplo n.º 4
0
def select_edges_from_network(network, edges, directory, name):
    """
  Selects the edges in the given |network| path whose edge ids are in the given
      |edges| set, and saves a shapefile of the selected edges at the given
      location. Also saves a symbolized layer of the shapefile. Returns a
      mapping from the ids in the created file to ids in the original edges
      file, as recorded in the |edges| set. Also returns the path to the created
      shape file.
  """
    network_edges = getEdgePathFromNetwork(network)
    id_name = ("FID"
               if Describe(network_edges).extension == "shp" else "OBJECTID")
    query = ' OR '.join(
        ['"%s" = %d' % (id_name, edge_id) for edge_id in edges])
    selected_edges = "%s.shp" % join(directory, name)
    Select_analysis(network_edges, selected_edges, query)
    edges_layer = "%s.lyr" % join(directory, name)
    MakeFeatureLayer_management(in_features=selected_edges, out_layer=name)
    SaveToLayerFile_management(name, edges_layer, "ABSOLUTE")
    ApplySymbologyFromLayer_management(
        edges_layer,
        join(path[0], "Symbology_Layers\sample_edges_symbology.lyr"))
    add_layer_to_display(edges_layer)
    # TODO(mikemeko): this is a bit hacky, relies on the fact that ids appear in
    #     sorted order in tables, and that ids for shape files start from 0
    id_mapping = dict(zip(range(len(edges)), sorted(edges)))
    return id_mapping, selected_edges
Exemplo n.º 5
0
    def restrictDomain(self, object, operation):
        """
        Restricts current instance's domain based on object's domain
        @param object: extent to which the field is restricted
        @param operation: valid options: "inside", "outside"
        """

        if operation == 'inside':

            name = "restDom_in_" + str(self.sObj)
            outputLocation = "in_memory\\" + name + ".tif"

            # extract by mask
            outRaster = ExtractByMask(self.filepath, object.filepath)
            CopyRaster_management(outRaster, outputLocation)
            restDom = utils.makeField(outputLocation)

        elif operation == 'outside':
            raise NotImplementedError("restrictDomain 'outside'")

        else:
            raise NotImplementedError(operation)

        # update cc instance's attributes
        desc = Describe(outputLocation)
        restDom.filepath = outputLocation
        restDom.domain = desc.extent
        restDom.filename = os.path.basename(outputLocation)

        return restDom
def determine_domain(filepath):
    """
    :param filepath: data source filepath
    :return: ArcPy domain extent
    """
    desc = Describe(filepath)
    return desc.extent
    def buffer(self, distance, unitType):
        """
        Buffer input object
        @param distance: buffer distance
        @param unitType: unit type
        """

        # determine temporary unique file
        distName = str(distance)
        distName2 = distName.replace(".", "_")
        print("distName2", distName2)
        name = "buf_" + str(self.sObj) + distName2
        outputLocation = "in_memory\\" + name

        # calculate buffer
        concatDistance = str(distance) + " " + unitType
        Buffer_analysis(self.filepath, outputLocation, concatDistance)
        bufObj = utils.makeObject(outputLocation)

        # update cc instance's attributes
        desc = Describe(outputLocation)
        bufObj.domain = desc.extent
        bufObj.filepath = outputLocation
        bufObj.filename = os.path.basename(outputLocation)

        return bufObj
Exemplo n.º 8
0
def preparingSourceCountyData():
    print("Starting the preparingSourceCountyData function!")

    if Exists(preRouteSourceCRML):
        try:
            Delete_management(preRouteSourceCRML)
        except:
            print("Could not delete the features located at: " +
                  str(preRouteSourceCRML) + ".")
    else:
        pass

    # Make a copy
    CopyFeatures_management(routesSourceCountyLRSArnold, preRouteSourceCRML)

    # Remove unnecessary fields
    preRouteSourceCRMLDescription = Describe(preRouteSourceCRML)
    preRouteSourceCRMLOIDFieldName = preRouteSourceCRMLDescription.OIDFieldName
    preRouteSourceCRMLShapeFieldName = preRouteSourceCRMLDescription.shapeFieldName
    preRouteSourceCRMLShapeAndOIDFieldNames = [
        preRouteSourceCRMLOIDFieldName, preRouteSourceCRMLShapeFieldName
    ]
    preRouteSourceCRMLFieldObjectsList = ListFields(preRouteSourceCRML)
    preRouteSourceFieldNames = [
        x.name for x in preRouteSourceCRMLFieldObjectsList
    ]
    fieldNamesToKeep = [
        y for y in preRouteSourceFieldNames if y in preRouteSourceCRMLFields
        or y in preRouteSourceCRMLShapeAndOIDFieldNames
    ]

    fieldNamesToRemove = [
        z for z in preRouteSourceFieldNames if z not in fieldNamesToKeep
    ]

    for fieldNameItem in fieldNamesToRemove:
        DeleteField_management(preRouteSourceCRML, fieldNameItem)

    print("Done deleting unnecessary fields.")

    MakeFeatureLayer_management(preRouteSourceCRML, fcAsFeatureLayerLG)
    selectionQueryL1 = """ SourceRouteId IS NULL OR LRS_ROUTE_PREFIX IN ('I', 'U', 'K') """
    SelectLayerByAttribute(fcAsFeatureLayerLG, NEW_SELECTION_CONST,
                           selectionQueryL1)
    CopyFeatures_management(fcAsFeatureLayerLG, stateRoutesAndNullRouteIDs)
    DeleteRows_management(fcAsFeatureLayerLG)
    selectionQueryL2 = """ SourceFromMeasure IS NULL OR SourceToMeasure IS NULL """
    SelectLayerByAttribute(fcAsFeatureLayerLG, NEW_SELECTION_CONST,
                           selectionQueryL2)
    CopyFeatures_management(fcAsFeatureLayerLG, preRouteSourceNoMeasures)
    selectionQueryL3 = """ SourceFromMeasure IS NULL """
    SelectLayerByAttribute(fcAsFeatureLayerLG, NEW_SELECTION_CONST,
                           selectionQueryL3)
    CalculateField_management(fcAsFeatureLayerLG, "SourceFromMeasure", "0",
                              PYTHON_9_3_CONST)
    selectionQueryL4 = """ SourceToMeasure IS NULL """
    SelectLayerByAttribute(fcAsFeatureLayerLG, NEW_SELECTION_CONST,
                           selectionQueryL4)
    CalculateField_management(fcAsFeatureLayerLG, "SourceToMeasure",
                              "!SHAPE.LENGTH@MILES!", PYTHON_9_3_CONST)
Exemplo n.º 9
0
def ReturnStreetstoTopology():
    from arcpy import (AddFeatureClassToTopology_management, ListDatasets,
                       AddRuleToTopology_management, Delete_management,
                       Describe)
    env.workspace = currentPathSettings.gdbPath
    fd = ListDatasets("*", "Feature")
    gdbw = os.path.join(currentPathSettings.gdbPath, fd[0])
    env.workspace = gdbw
    topoDatasetList = ListDatasets("*", "TOPOLOGY")
    geonetDatasetList = ListDatasets("*", "GeometricNetwork")
    authbnd = os.path.join(gdbw, "AuthoritativeBoundary")
    ESZBnd = os.path.join(gdbw, "ESZ")
    if geonetDatasetList == []:
        print "no geometric network created yet"
    else:
        Delete_management(geonetDatasetList[0])
    desc = Describe(topoDatasetList[0])
    print "%-27s %s" % ("FeatureClassNames:", desc.featureClassNames)
    if lyr in desc.featureClassNames:
        print "Road Centerlines already exist in topology dataset"
    else:
        print "adding road centerlines to topology"
        inputTopology = os.path.join(gdbw, topoDatasetList[0])
        inputRoadCenterline = os.path.join(gdbw, "RoadCenterline")
        AddFeatureClassToTopology_management(inputTopology,
                                             inputRoadCenterline, "1", "1")
        AddRuleToTopology_management(inputTopology, "Must Not Overlap (line)",
                                     inputRoadCenterline, "", "", "")
        AddRuleToTopology_management(inputTopology,
                                     "Must Not Intersect (line)",
                                     inputRoadCenterline, "", "", "")
        AddRuleToTopology_management(inputTopology,
                                     "Must Not Have Dangles (Line)",
                                     inputRoadCenterline, "", "", "")
        AddRuleToTopology_management(inputTopology,
                                     "Must Not Self-Overlap (Line)",
                                     inputRoadCenterline, "", "", "")
        AddRuleToTopology_management(inputTopology,
                                     "Must Not Self-Intersect (Line)",
                                     inputRoadCenterline, "", "", "")
        AddRuleToTopology_management(inputTopology,
                                     "Must Be Single Part (Line)",
                                     inputRoadCenterline, "", "", "")
        AddRuleToTopology_management(
            inputTopology, "Must Not Intersect Or Touch Interior (Line)",
            inputRoadCenterline, "", "", "")
        AddRuleToTopology_management(
            inputTopology, "Must Not Intersect Or Touch Interior (Line)",
            inputRoadCenterline, "", "", "")
        AddRuleToTopology_management(inputTopology,
                                     "Must Be Inside (Line-Area)",
                                     inputRoadCenterline, "", authbnd, "")
        #write for loop - must be inside ESZ boundaries
        AddRuleToTopology_management(
            inputTopology, "Boundary Must Be Covered By (Area-Line)", authbnd,
            "", inputRoadCenterline, "")
        AddRuleToTopology_management(
            inputTopology, "Boundary Must Be Covered By (Area-Line)", ESZBnd,
            "", inputRoadCenterline, "")
Exemplo n.º 10
0
def network_cost_attributes(network):
    """
  Returns a set of the cost attributes for the given |network|.
  """
    return set([
        attribute.name for attribute in Describe(network).attributes
        if attribute.usageType == "Cost"
    ])
Exemplo n.º 11
0
 def __get_domain_codes(self, domain_name):
     env.workspace = self.in_db
     db_described = Describe(self.in_db)
     if domain_name in db_described.domains:
         domain_table = DomainToTable_management(self.in_db, domain_name, r"in_memory\domain", "code", "desc")
         return domain_table
     else:
         return False
Exemplo n.º 12
0
 def get_describe(self):
     """Returns a describe object if the table exists, otherwise returns None. Gets around an OSError if the table
     is corrupted."""
     try:
         desc = Describe(self.full_path)
         return desc
     except OSError:
         return None
Exemplo n.º 13
0
 def __init__(self, tuple_path):
     self.tuple_path = tuple_path
     self.full_path = path.join(*self.tuple_path)
     self.connection = tuple_path[0]
     self._desc = self.get_describe()
     self.database = Describe(self.connection).connectionProperties.instance.split(":")[-1].upper()
     self.dataset = self.tuple_path[1] if len(self.tuple_path) == 3 else None
     self.owner, self.name = self.tuple_path[-1].split(".")
     self.unique_name = ".".join([self.database, self.owner, self.name]).upper()
Exemplo n.º 14
0
def subset_image(in_raster, area, out_raster):
    from arcpy import Describe
    from math import sqrt
    desc = Describe(in_raster)
    XMin = desc.extent.XMin
    YMin = desc.extent.YMin
    len = sqrt(area)
    clipping_extent = '{0} {1} {2} {3}'.format(XMin, YMin, XMin+len, YMin+len)
    ClipRaster(in_raster, clipping_extent, out_raster, "#", "#", "NONE")
Exemplo n.º 15
0
def getEdgePathFromNetwork(NETWORK_FILE_PATH):
    desc = Describe(NETWORK_FILE_PATH)
    assert desc.dataType in ("NetworkDataset", "NetworkDatasetLayer")
    assert len(desc.edgeSources) > 0
    featureClassPath = join(desc.path, desc.edgeSources[0].name)
    if len(desc.extension) > 0:
        # it is file
        featureClassPath = featureClassPath + ".shp"
    return featureClassPath
    def addProperty(self, in_raster):
        """
        get value of a field and write it to a column named RASTERVALU in the object
        @param in_raster: raster where the value is taken from
        """

        desc = Describe(self.filepath)
        name = "addProperty" + str(self.sObj)
        outputLocation = "in_memory\\" + name

        if desc.shapeType == "Point":
            ExtractValuesToPoints(self.filepath, in_raster.filepath,
                                  outputLocation)
            addProperty = utils.makeObject(outputLocation)

        elif desc.shapeType == "Line":
            raise NotImplementedError(desc.shapeType)

        elif desc.shapeType == "Polygon":
            polyToPoint = "in_memory\\polyToPoint_" + str(self.sObj)
            FeatureToPoint_management(self.filepath, polyToPoint, "CENTROID")
            valueToPoint = "in_memory\\valueToPoint_" + str(self.sObj)
            ExtractValuesToPoints(polyToPoint, in_raster.filepath,
                                  valueToPoint)
            CopyFeatures_management(self.filepath, outputLocation)
            JoinField_management(outputLocation, "FID", valueToPoint, "FID",
                                 "RASTERVALU")
            addProperty = utils.makeObject(outputLocation)
            Delete_management(polyToPoint)
            Delete_management(valueToPoint)
            #TODO implement method that the parameters "CENTROID" or "INSIDE" for FeatureToPoint_management() can be selected

        else:
            raise NotImplementedError("unknown shapeType:", desc.shapeType)

        # update cc instance's attributes
        desc = Describe(outputLocation)
        addProperty.domain = desc.extent
        addProperty.filepath = outputLocation
        addProperty.filename = os.path.basename(outputLocation)

        return addProperty
 def __init__(self,
              helper,
              iter_layer='Industrial Development Sites',
              expand_extent=25):
     from arcpy.da import SearchCursor
     from arcpy import Describe
     layer = helper.map.map.listLayers(iter_layer)[0]
     fields = ['SHAPE@'] + [f.name for f in Describe(layer).fields]
     self.helper = helper
     self.cursor = SearchCursor(layer, fields)
     self.expand_extent = expand_extent
Exemplo n.º 18
0
 def validate_geodatabase(path):
     """
     """
     try:
         desc = Describe(path)
         assert desc.DataType == 'Workspace'
         assert desc.workspacetype == 'LocalDatabase'
     except IOError as e:
         raise GeodatabaseError(e)
     except AssertionError:
         raise GeodatabaseError(
             "{} is not a valid geodatabase.".format(path))
Exemplo n.º 19
0
def getElevationAtPoint(raster, point):
    """
    retrieves the elevation at a point
    """

    # project the point
    sr = Describe(raster).spatialReference
    projected_point = point.projectAs(sr).getPart(0)

    # Get the first cell that starts at the point
    result = RasterToNumPyArray(raster, projected_point, 1, 1, -999)
    return result[0][0]
Exemplo n.º 20
0
def polygon_to_point(input_fc, output_fc):
    """
    copies the centroid of polygon geometry to
    a point feature class
    """

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

    AddField_management(output_fc, new_field, 'Long')

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

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

    del search_cursor, insert_cursor, spatial_reference
Exemplo n.º 21
0
def line_to_endpoints(input_fc, output_fc, id_field=None):
    """
    copies the endpoints of a feature class into a point
    feature class
    """

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

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


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

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

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

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

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

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

    del search_cursor, insert_cursor, spatial_reference
Exemplo n.º 22
0
def KDOTKeyCalculation_Modified():
    # Until the KDOT process is included here,
    # this defaults to the Transcend process.
    #FieldPopulation with selections and FieldCalculate:
    MakeFeatureLayer_management(routesSourceCenterlines, featureLayer)

    tempDesc = Describe(featureLayer)
    print("Calculating values for new LRS and measure fields in " +
          returnFeatureClass(tempDesc.catalogPath) + ".")
    try:
        del tempDesc
    except:
        pass
    # Select LRS_ROUTE_PREFIX IN ('I', 'U', 'K')
    selectionQuery = """ "LRS_ROUTE_PREFIX" IN ('I', 'U', 'K') """
    SelectLayerByAttribute_management(featureLayer, "NEW_SELECTION",
                                      selectionQuery)
    # SourceRouteId = StateKey1
    CalculateField_management(featureLayer, "SourceRouteId", "!StateKey1!",
                              "PYTHON_9.3")
    # SourceFromMeasure = STATE_BEGIN_MP
    CalculateField_management(featureLayer, "SourceFromMeasure",
                              "!STATE_BEGIN_MP!", "PYTHON_9.3")
    # SourceToMeasure = STATE_END_MP
    CalculateField_management(featureLayer, "SourceToMeasure",
                              "!STATE_END_MP!", "PYTHON_9.3")

    # Select LRS_ROUTE_PREFIX NOT IN ('I', 'U', 'K') AND LRSKEY IS NOT NULL
    selectionQuery = """ "LRS_ROUTE_PREFIX" NOT IN ('I', 'U', 'K') AND "LRSKEY" IS NOT NULL """
    SelectLayerByAttribute_management(featureLayer, "NEW_SELECTION",
                                      selectionQuery)
    # SourceRouteId = LRSKEY
    CalculateField_management(featureLayer, "SourceRouteId", "!LRSKEY!",
                              "PYTHON_9.3")
    # SourceFromMeasure = NON_STATE_BEGIN_MP
    CalculateField_management(featureLayer, "SourceFromMeasure",
                              "!NON_STATE_BEGIN_MP!", "PYTHON_9.3")
    # SourceToMeasure = NON_STATE_END_MP
    CalculateField_management(featureLayer, "SourceToMeasure",
                              "!NON_STATE_END_MP!", "PYTHON_9.3")

    # Select LRS_ROUTE_PREFIX IN ('C') AND LRSKEY NOT LIKE '%W0'
    selectionQuery = """ "LRS_ROUTE_PREFIX" IN ('C') AND "LRSKEY" NOT LIKE '%W0' """
    SelectLayerByAttribute_management(featureLayer, "NEW_SELECTION",
                                      selectionQuery)
    # SourceRouteID = left([LRSKEY], 11) & "W0"
    # This is the VB version.
    # Python version would be calcExpression1 = "!LRSKEY![0:11] + 'W0'"
    calcExpression1 = 'Left([LRSKEY] ,11 ) & "W0"'
    CalculateField_management(featureLayer, "SourceRouteID", calcExpression1,
                              "VB")
Exemplo n.º 23
0
    def MergeCatchment(self, inbasin):
        dstemp = None
        try:
            catchments = Config()["catchment"]
            env.workspace = self._TempLocation
            resultworkspace = os.path.join(self._WorkspaceDirectory,
                                           self.WorkspaceID + '.gdb', "Layers")
            downstreamcatchment = os.path.join(resultworkspace,
                                               catchments["downstream"])
            dsDesc = Describe(downstreamcatchment)
            if not Exists(downstreamcatchment):
                raise Exception("downstream catchment doesn't exist")
            sr = dsDesc.spatialReference

            wrkingbasin = self.ProjectFeature(inbasin, sr)

            #strip downstream catchment from mask
            dstemp = Erase_analysis(wrkingbasin, downstreamcatchment, "dstemp")
            #remove any weird verticies associated with Erase
            globalbasin = os.path.join(resultworkspace, catchments["global"])
            FeatureToPolygon_management(dstemp,
                                        globalbasin,
                                        cluster_tolerance="50 Meters",
                                        attributes="ATTRIBUTES",
                                        label_features="")
            #Delete multipolys created by Featuretopolygon
            maxOid = max({
                key: value
                for (key, value) in arcpy.da.SearchCursor(
                    globalbasin, ['OID@', 'Shape_Area'])
            }.iteritems(),
                         key=operator.itemgetter(1))[0]
            with arcpy.da.UpdateCursor(globalbasin, 'OID@') as cursor:
                for row in cursor:
                    if row[0] != maxOid:
                        cursor.deleteRow()
            #https://gis.stackexchange.com/questions/152481/how-to-delete-selected-rows-using-arcpy
            if not Exists(globalbasin):
                raise Exception("Failed to create basin " + GetMessages())
            return True
        except:
            tb = traceback.format_exc()
            self._sm("Merge basin Error " + tb, "ERROR")
            return False
        finally:
            #cleanup
            for fs in arcpy.ListFeatureClasses():
                arcpy.Delete_management(fs)
            for rs in arcpy.ListRasters():
                arcpy.Delete_management(rs)
Exemplo n.º 24
0
 def list_transformations(self, in_mosaic_dataset, in_spatial_reference,
                          to_spatial_reference):
     desc_mosaic = Describe(in_mosaic_dataset)
     xmin = desc_mosaic.extent.XMin
     xmax = desc_mosaic.extent.XMax
     ymin = desc_mosaic.extent.YMin
     ymax = desc_mosaic.extent.YMax
     extent = Extent(xmin, xmax, ymin, ymax)
     # in_sr = Describe(in_mosaic_dataset).spatialReference
     in_sr = in_spatial_reference
     out_sr = to_spatial_reference
     # out_sr = arcpy.SpatialReference(to_spatial_reference)
     # out_sr = arcpy.SpatialReference()
     # out_sr = out_sr.loadFromString(to_spatial_reference)
     return ListTransformations(in_sr, out_sr, extent)
Exemplo n.º 25
0
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)
def process():
    # Detect Unit of Measurement (Feet -vs- Meter)
    cell_factor = getCellFactor(in_mosaic_dataset)

    # Obatin List of Raster Files in Mosaic Dataset
    temp_table = join("memory", "temp_table")
    ExportMosaicDatasetPaths(in_mosaic_dataset, temp_table, "#", "ALL", "RASTER")
    rasters = set(row[0] for row in da.SearchCursor(temp_table, "Path"))
    Delete(temp_table)

    if not exists(out_directory):
        makedirs(out_directory)

    # Process each raster
    for in_raster in rasters:
        root_dir, file = split(in_raster)
        AddMessage("da filename is: {}".format(file))
        out_raster = join(out_directory, file)

        desc = Describe(in_raster)
        cell_size_height = desc.children[0].meanCellHeight  # Cell size in the Y axis and / or
        cell_size_width = desc.children[0].meanCellWidth  # Cell size in the X axis
        cell_size = "{0} {1}".format(cell_size_height*cell_factor, cell_size_width*cell_factor)

        if unitsCalc(in_mosaic_dataset) == "Foot":
            outTimes = Times(in_raster, 0.3048)
            ProjectRaster(in_raster=outTimes,
                          out_raster=out_raster,
                          out_coor_system=out_spatial_reference,
                          resampling_type=resampling_type,
                          cell_size=cell_size,
                          geographic_transform=geographic_transform,
                          in_coor_system=input_spatial_reference)
        else:
            ProjectRaster(in_raster=in_raster,
                          out_raster=out_raster,
                          out_coor_system=out_spatial_reference,
                          resampling_type=resampling_type,
                          cell_size=cell_size,
                          geographic_transform=geographic_transform,
                          in_coor_system=input_spatial_reference)

    # Delete Intermediate Data
    del rasters
    if out_mosaic_dataset:
        root_dir, file = split(out_mosaic_dataset)
        # TODO: Automatically detect Pixel Type from input Mosaic Dataset Rasters and pass below
        createMosaics(root_dir, file, out_directory, out_spatial_reference, "32_BIT_UNSIGNED")
Exemplo n.º 27
0
def writeAggregateTableToKanDrive():
    try:
        #truncating CDRS segments in KanDrive Spatial
        print str(datetime.datetime.now()) + " truncating RCRS segments in KanDrive Spatial."
        TruncateTable_management(kanDriveSpatialConditions)
        
        featuresToTransfer = list()
        
        # searchCursorFields go to r"in_memory\RCRS". (Input table)(Indirect)
        descObject = Describe(r"in_memory\RCRS")
        searchCursorFields = [field.name for field in descObject.fields if 
                            field.name != descObject.OIDFieldName and field.name != "Shape" and
                            field.name != "ID1"]
        searchCursorFields.append('SHAPE@')
        
        RCRS_SearchCursor = daSearchCursor(aggregateTable, searchCursorFields)
		
        for RCRS_CursorItem in RCRS_SearchCursor:
			featureItem = list(RCRS_CursorItem)
			featuresToTransfer.append(featureItem)
        
        # Make the insertCursor use the same fields as the searchCursor.
        insertCursorFields = searchCursorFields
        
        RCRS_InsertCursor = daInsertCursor(kanDriveSpatialConditions, insertCursorFields)
            
        for RCRS_Feature in featuresToTransfer:
            insertOID = RCRS_InsertCursor.insertRow(RCRS_Feature)
            print "Inserted a row with the OID of: " + str(insertOID)
		
    except:
        print "An error occurred."
        errorItem = sys.exc_info()[1]
        errorStatement = str(errorItem.args[0])
        print errorStatement
        
        if len(errorStatement) > 253:
            errorStatement = errorStatement[0:253]
        else:
            pass
        endTime = datetime.datetime.now()
        ScriptStatusLogging('KanDrive_Spatial_Conditions_Update', 'kandrive_spatial.DBO.Conditions',
            scriptFailure, startTime, endTime, errorItem.args[0], pythonLogTable)
            
        try:
            del errorItem
        except:
            pass
Exemplo n.º 28
0
 def updateParameters(self):
     # Modify parameter values and properties.
     # This gets called each time a parameter is modified, before
     # standard validation.
     if self.params[0].value:
         self.params[1].enabled = True
         self.params[1].value = Describe(self.params[0]).spatialReference
         if self.params[1].value:
             self.params[2].enabled = True
             if self.params[2].value:
                 self.params[3].enabled = True
                 transformations = self.list_transformations(
                     self.params[0].value, self.params[1].value,
                     self.params[2].value)
                 # self.params[3].value = transformations[0]
                 self.params[3].filter.list = transformations
     return
Exemplo n.º 29
0
def PathReSet():
    #use the path from the NG911 config file to create address locators and perform operations that output to the NG911 geodatabase environment
    try:
        from NG911_Config import gdb
    except:
        gdb = r'\\gisdata\arcgis\GISdata\DASC\NG911\Final\Region1_BA_Final.gdb'
    from arcpy import env, Describe
    env.overwriteOutput = 1
    print gdb
    OriginalGDB = gdb
    gdbdesc = Describe(OriginalGDB)
    gdbpath = gdbdesc.Path
    gdbbasename = gdbdesc.Basename
    gdbexts = gdbdesc.Extension
    del gdb
    gdb = gdbpath + "/" + gdbbasename + "_RoadChecks." + gdbexts
    return gdb
Exemplo n.º 30
0
def SetProjection():
    env.workspace = OracleDB
    fclist = ListFeatureClasses()
    for fc in fclist:
        if str(fc)[-2:] == 'MV':
            print "no actions taken on a Materialized View"
            pass
        else:
            spatial_ref = Describe(fc).spatialReference
            # If the spatial reference is unknown
            if spatial_ref.name == "Unknown":
                print("{0} has an unknown spatial reference".format(fc))
                DefineProjection_management(OracleDB + "/" + fc, coor_system)
            # Otherwise, print out the feature class name and
            # spatial reference
            else:
                print("{0} : {1}".format(fc, spatial_ref.name))
Exemplo n.º 31
0
def buildNonstateRoutes(systemToRoute, routedSystemExport):
    print "Building NonstateRoutes..."
    inMemoryNonStateSystem = r'in_memory\nonStateSystem'
    inMemoryNonStateSystemLyr = "featureClassAsALayer"
    
    # Semi-ugly notation to get the all but the last item from the split output.
    gdb = os.path.split(routedSystemExport)[:-1][0]
    
    print gdb
    
    env.workspace = gdb
    env.outputMFlag = "Enabled"
    
    spatialReferenceToUse  = Describe(systemToRoute).spatialReference
    spatialReferenceToUse.setMDomain(0, 500)
    spatialReferenceToUse.MTolerance = 0.001
    spatialReferenceToUse.MResolution = 0.001
    
    env.outputCoordinateSystem = spatialReferenceToUse
    
    
    try:
        Delete_management("in_memory")
    except:
        print "Can't delete in_memory"
    
    mainWhereClause = "FUNCLASS in (4,5,6,7) AND MILEAGE_COUNTED = -1 AND LENGTH <> 0 AND PROPOSED <> SOMETHING"
    
    loadedNonStateSystem = "loadedNonStateSystem"
    
    # Loads the systemToRoute as loadedNonStateSystem
    MakeFeatureLayer_management(systemToRoute, loadedNonStateSystem, mainWhereClause)
    
    debugFeatureCount = GetCount_management(loadedNonStateSystem)
    
    print "Total loaded rows = " + str(debugFeatureCount)
    
    CopyFeatures_management(loadedNonStateSystem, inMemoryNonStateSystem)
    
    del loadedNonStateSystem
    
    debugFeatureCount = GetCount_management(inMemoryNonStateSystem)
    
    print "Total copied rows = " + str(debugFeatureCount)
    
    MakeFeatureLayer_management(inMemoryNonStateSystem, inMemoryNonStateSystemLyr) # Needed to use select by attribute.
    
    lrsBackwardsWhereClause = "LRS_BACKWARDS = -1"
    
    SelectLayerByAttribute_management(inMemoryNonStateSystemLyr, "NEW_SELECTION", lrsBackwardsWhereClause)
    
    debugFeatureCount = GetCount_management(inMemoryNonStateSystemLyr)
    
    print "LRS backwards rows = " + str(debugFeatureCount)
    
    # Reverse line direction for selected lines
    # Used on the loaded (to memory) version of the non state system because it modifies the
    # feature class (not the layer, but the feature class it references) in place without output.
    FlipLine_edit(inMemoryNonStateSystemLyr)
    
    SelectLayerByAttribute_management(inMemoryNonStateSystemLyr, "CLEAR_SELECTION")
    
    debugFeatureCount = GetCount_management(inMemoryNonStateSystemLyr)
    
    print "Total (non)selected rows = " + str(debugFeatureCount)
    
    routeIDField = "LRS_KEY"
    measureSource = "TWO_FIELDS"
    beginField = "LRS_BEG_CNTY_LOGMILE"
    endField = "LRS_END_CNTY_LOGMILE"
    
    CreateRoutes_lr(inMemoryNonStateSystemLyr, routeIDField, routedSystemExport, measureSource, beginField, endField)
    
    debugFeatureCount = GetCount_management(routedSystemExport)
    
    print "Total routes written = " + str(debugFeatureCount)
    
    # Delete the loaded in_memory layer.
    del inMemoryNonStateSystemLyr
    
    # Delete the in_memory feature class.
    try:
        Delete_management(inMemoryNonStateSystem)
    except:
        print "Can't delete in_memory\nonStateSystem"
        
    # Delete the variable that referenced the path to the in_memory\nonStateSystem feature class.
    del inMemoryNonStateSystem