Python arcpy.Describe() Examples

The following are 30 code examples of arcpy.Describe(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module arcpy , or try the search function .
Example #1
Source File: section_cpu.py    From HiSpatialCluster with Apache License 2.0 10 votes vote down vote up
def generate_cls_boundary(cls_input,cntr_id_field,boundary_output,cpu_core):
    arcpy.env.parallelProcessingFactor=cpu_core
    arcpy.SetProgressorLabel('Generating Delaunay Triangle...')
    arrays=arcpy.da.FeatureClassToNumPyArray(cls_input,['SHAPE@XY',cntr_id_field])
   
    cid_field_type=[f.type for f in arcpy.Describe(cls_input).fields if f.name==cntr_id_field][0]
    delaunay=Delaunay(arrays['SHAPE@XY']).simplices.copy()
    arcpy.CreateFeatureclass_management('in_memory','boundary_temp','POLYGON',spatial_reference=arcpy.Describe(cls_input).spatialReference)
    fc=r'in_memory\boundary_temp'
    arcpy.AddField_management(fc,cntr_id_field,cid_field_type)
    cursor = arcpy.da.InsertCursor(fc, [cntr_id_field,"SHAPE@"])
    arcpy.SetProgressor("step", "Copying Delaunay Triangle to Temp Layer...",0, delaunay.shape[0], 1)
    for tri in delaunay:
        arcpy.SetProgressorPosition()
        cid=arrays[cntr_id_field][tri[0]]
        if cid == arrays[cntr_id_field][tri[1]] and cid == arrays[cntr_id_field][tri[2]]:
            cursor.insertRow([cid,arcpy.Polygon(arcpy.Array([arcpy.Point(*arrays['SHAPE@XY'][i]) for i in tri]))])
    arcpy.SetProgressor('default','Merging Delaunay Triangle...')
    if '64 bit' in sys.version:
        arcpy.PairwiseDissolve_analysis(fc,boundary_output,cntr_id_field)
    else:
        arcpy.Dissolve_management(fc,boundary_output,cntr_id_field)
    arcpy.Delete_management(fc)
    
    return 
Example #2
Source File: arcapi.py    From arcapi with GNU Lesser General Public License v3.0 6 votes vote down vote up
def to_points(tbl, out_fc, xcol, ycol, sr, zcol='#', w=''):
    """Convert table to point feature class, return path to the feature class.

    Required:
    tbl -- input table or table view
    out_fc -- path to output feature class
    xcol -- name of a column in tbl that stores x coordinates
    ycol -- name of a column in tbl that stores y coordinates
    sr -- spatial reference for out_fc
        sr can be either arcpy.SpatialReference object or a well known id as int

    Optional:
    zcol -- name of a column in tbl that stores y coordinates, default is '#'
    w -- where clause to limit the rows of tbl considered, default is ''

    Example:
    >>> t = 'c:\\foo\\bar.shp'
    >>> o = 'c:\\foo\\bar_pts.shp'
    >>> table_to_points(t, o, "XC", "YC", 4326, zcol='#', w='"FID" < 10')
    >>> table_to_points(t, o, "XC", "YC", arcpy.SpatialReference(27700))
    >>> table_to_points(t, o, "XC", "YC", arcpy.describe(tbl).spatialReference)
    """
    lrnm = tstamp('lr', '%m%d%H%M%S', '')
    if type(sr) != arcpy.SpatialReference:
        sr = arcpy.SpatialReference(sr)
    lr = arcpy.MakeXYEventLayer_management(tbl, xcol, ycol, lrnm, sr, zcol).getOutput(0)
    if str(w) not in ('', '*'):
        arcpy.SelectLayerByAttribute_management(lr, "NEW_SELECTION", w)
    out_fc = arcpy.CopyFeatures_management(lr, out_fc).getOutput(0)
    dlt(lr)
    return (arcpy.Describe(out_fc).catalogPath) 
Example #3
Source File: BBB_SharedFunctions.py    From public-transit-tools with Apache License 2.0 6 votes vote down vote up
def HandleOIDUniqueID(inPointsLayer, inLocUniqueID):
    '''If ObjectID was selected as the unique ID, copy the values to a new field
    so they don't get messed up when copying the table.'''
    pointsOID = arcpy.Describe(inPointsLayer).OIDFieldName
    if inLocUniqueID.lower() == pointsOID.lower():
        try:
            inLocUniqueID = "BBBUID"
            arcpy.AddMessage("You have selected your input features' ObjectID field as the unique ID to use for this analysis. \
In order to use this field, we have to transfer the ObjectID values to a new field in your input data called '%s' because ObjectID values \
may change when the input data is copied to the output. Adding the '%s' field now, and calculating the values to be the same as the current \
ObjectID values..." % (inLocUniqueID, inLocUniqueID))
            arcpy.management.AddField(inPointsLayer, inLocUniqueID, "LONG")
            arcpy.management.CalculateField(inPointsLayer, inLocUniqueID, "!" + pointsOID + "!", "PYTHON_9.3")
        except:
            arcpy.AddError("Unable to add or calculate new unique ID field. Please fix your data or choose a different unique ID field.")
            raise CustomError
    return inLocUniqueID 
Example #4
Source File: Select_Mapunits_by_Project_NATSYM.py    From geo-pit with GNU General Public License v2.0 6 votes vote down vote up
def GetWorkspace(ssurgoInput):
# Return the workspace of the input
    """ Maybe get rid of this or add it to the main body """

    try:
        desc = arcpy.Describe(ssurgoInput)
        thePath = os.path.dirname(desc.CatalogPath)

        desc = arcpy.Describe(thePath)

        # if path to ssurgoInput is a FD grab the GDB path
        if desc.dataType.upper() == "FEATUREDATASET":
            thePath = os.path.dirname(thePath)

        env.workspace = thePath
        return thePath

    except:
        errorMsg()

## =================================================================================== 
Example #5
Source File: Select_Mapunits_by_Project.py    From geo-pit with GNU General Public License v2.0 6 votes vote down vote up
def GetWorkspace(ssurgoInput):
# Return the workspace of the input
    """ Maybe get rid of this or add it to the main body """

    try:
        desc = arcpy.Describe(ssurgoInput)
        thePath = os.path.dirname(desc.CatalogPath)

        desc = arcpy.Describe(thePath)

        # if path to ssurgoInput is a FD grab the GDB path
        if desc.dataType.upper() == "FEATUREDATASET":
            thePath = os.path.dirname(thePath)

        env.workspace = thePath
        return thePath

    except:
        errorMsg()

## =================================================================================== 
Example #6
Source File: tool_calculatedensity.py    From HiSpatialCluster with Apache License 2.0 6 votes vote down vote up
def updateParameters(self, parameters):
        params=parameters
        
#        if parameters[0].altered and not parameters[1].altered:
#            parameters[1].value=arcpy.Describe(parameters[0].valueAsText).OIDFieldName
                
        if params[4].value=='CUT_OFF':
            params[5].enabled=1
            params[6].enabled=0
        else:
            params[5].enabled=0
            params[6].enabled=1
        
        if params[7].value=='CPU':
            params[8].enabled=1
        else:
            params[8].enabled=0
        
        if parameters[0].altered and not parameters[3].altered:
            in_fe=parameters[0].valueAsText   
            parameters[3].value=in_fe[:len(in_fe)-4]+'_dens'+in_fe[-4:] if in_fe[-3:]=='shp' else in_fe+'_dens'
        
        return 
Example #7
Source File: AnalysisHelpers.py    From public-transit-tools with Apache License 2.0 6 votes vote down vote up
def add_TimeOfDay_field_to_sublayer(nalayer, sublayer_object, sublayer_name):
    '''Add a field called TimeOfDay of type DATE to an NA sublayer'''
    time_field = "TimeOfDay"

    # Clean up any pre-existing fields with this name (unlikely case)
    poly_fields = [f for f in arcpy.Describe(sublayer_object).fields if f.name == time_field]
    if poly_fields:
        for f in poly_fields:
            if f.name == time_field and f.type != "Date":
                msg = "Your network analysis layer's %s sublayer already contained a field called %s of a type " + \
                      "other than Date.  This field will be deleted and replaced with a field of type Date used " + \
                      "for the output of this tool."
                arcpy.AddWarning(msg % (sublayer_name, time_field))
                arcpy.management.DeleteField(sublayer_object, time_field)

    # Add the TimeOfDay field to the sublayer.  If it already exists, this will do nothing.
    arcpy.na.AddFieldToAnalysisLayer(nalayer, sublayer_name, time_field, "DATE")

    return time_field 
Example #8
Source File: SSURGO_ExportMuRaster.py    From geo-pit with GNU General Public License v2.0 6 votes vote down vote up
def CheckSpatialReference(inputFC):
    # Make sure that the coordinate system is projected and units are meters
    try:
        desc = arcpy.Describe(inputFC)
        inputSR = desc.spatialReference

        if inputSR.type.upper() == "PROJECTED":
            if inputSR.linearUnitName.upper() == "METER":
                env.outputCoordinateSystem = inputSR
                return True

            else:
                raise MyError, os.path.basename(theGDB) + ": Input soil polygon layer does not have a valid coordinate system for gSSURGO"

        else:
            raise MyError, os.path.basename(theGDB) + ": Input soil polygon layer must have a projected coordinate system"

    except MyError, e:
        # Example: raise MyError, "This is an error message"
        PrintMsg(str(e), 2)
        return False 
Example #9
Source File: FeaturesToGPX.py    From sample-gp-tools with Apache License 2.0 6 votes vote down vote up
def featuresToGPX(inputFC, outGPX, zerodate, pretty):
    ''' This is called by the __main__ if run from a tool or at the command line
    '''

    descInput = arcpy.Describe(inputFC)
    if descInput.spatialReference.factoryCode != 4326:
        arcpy.AddWarning("Input data is not projected in WGS84,"
                         " features were reprojected on the fly to create the GPX.")

    generatePointsFromFeatures(inputFC , descInput, zerodate)

    # Write the output GPX file
    try:
        if pretty:
            gpxFile = open(outGPX, "w")
            gpxFile.write(prettify(gpx))
        else:
            gpxFile = open(outGPX, "wb")
            ET.ElementTree(gpx).write(gpxFile, encoding="UTF-8", xml_declaration=True)
    except TypeError as e:
        arcpy.AddError("Error serializing GPX into the file.")
    finally:
        gpxFile.close() 
Example #10
Source File: _data_objects.py    From registrant with MIT License 6 votes vote down vote up
def get_attachments_count(self):
        """Get number of attachments stored for a table/feature class."""
        rel_classes = [
            os.path.join(self.root, rc)
            for rc in getattr(self._desc, 'relationshipClassNames', [''])
        ]
        for rc in rel_classes:
            rc_desc = arcpy.Describe(rc)
            if rc_desc.isAttachmentRelationship:
                return int(
                    arcpy.GetCount_management(
                        os.path.join(
                            self.root,
                            rc_desc.destinationClassNames[0])).getOutput(0))

    # ---------------------------------------------------------------------- 
Example #11
Source File: describe_reporter.py    From sample-gp-tools with Apache License 2.0 6 votes vote down vote up
def check_prop_list(user_types):
    """ Verify that the user has entered valid Describe Object types/classes and
        print a warning message for any invalid choices. If no arguments are 
        provided, the report will print all Describe properties.Returns a list 
        of Describe properties whose attributes will be included in the report.
    """
    if not user_types:
        queried_types = [p for p in properties]
    else:
        invalid_types = list()
        queried_types = list()
        [queried_types.append(k) if k in properties else invalid_types.append(k) for k in user_types]
        if invalid_types:
            print("WARNING! Describe Types will not be included in report:")
            for t in invalid_types:
                print(t)
    return queried_types 
Example #12
Source File: _data_objects.py    From registrant with MIT License 6 votes vote down vote up
def __init__(self, path):
        """Initialize `arcpy.Describe` object with basic properties."""
        self.path = path
        self._desc = arcpy.Describe(self.path)
        self.catalogPath = self._desc.catalogPath
        self.name = self._desc.name
        self.root = os.path.dirname(self.catalogPath)

        if hasattr(arcpy.Describe(self.root),
                   'datasetType'):  # 'FeatureDataset':
            self.wkspc = os.path.dirname(self.root)
        else:  # FeatureClass
            self.wkspc = self.root

        if 'Remote' in arcpy.Describe(self.wkspc).workspaceType:
            self.name = '.'.join(self.name.split('.')[1:])


######################################################################## 
Example #13
Source File: utils.py    From restapi with GNU General Public License v2.0 6 votes vote down vote up
def form_connection_string(ws):
            """Esri's describe workspace connection string does not work at 10.4, bug???"""
            desc = arcpy.Describe(ws)
            if 'SdeWorkspaceFactory' in desc.workspaceFactoryProgID:
                cp = desc.connectionProperties
                props =  ['server', 'instance', 'database', 'version', 'authentication_mode']
                db_client = cp.instance.split(':')[1]
                con_properties = cp.server
                parts = []
                for prop in props:
                    parts.append('{}={}'.format(prop.upper(), getattr(cp, prop)))
                parts.insert(2, 'DBCLIENT={}'.format(db_client))
                parts.insert(3, 'DB_CONNECTION_PROPERTIES={}'.format(cp.server))
                return ';'.join(parts)
            else:
                return 'DATABASE=' + ws 
Example #14
Source File: WMX_Generalization.py    From CTM with Apache License 2.0 6 votes vote down vote up
def updateOverrides(fcs):
    """ loops through all feature classes and applies overrides to the geometry"""
    for fc in fcs:
        arcpy.env.overwriteOutput = True
        arcpy.env.addOutputsToMap = False
        desc = arcpy.Describe(fc)
        rep_name = ""
        if hasattr(desc, "representations"):
            reps = desc.representations
            for rep in reps:
                rep_name = rep.name
                arcpy.AddMessage("Applying Rep Overrides for " + str(fc))
                arcpy.UpdateOverride_cartography(fc, rep_name, "BOTH")
        arcpy.AddMessage("Repairing Geometry for " + str(fc))
        arcpy.RepairGeometry_management(fc)

    return fcs 
Example #15
Source File: arcapi.py    From arcapi with GNU Lesser General Public License v3.0 6 votes vote down vote up
def make_poly_from_extent(ext, sr):
    """Make an arcpy polygon object from an input extent object.,Returns
    a polygon geometry object.

    Required:
    ext -- extent object
    sr -- spatial reference

    Example
    >>> ext = arcpy.Describe(fc).extent
    >>> sr = 4326  #WKID for WGS 84
    >>> poly = make_poly_from_extent(ext, sr)
    >>> arcpy.CopyFeatures_management(poly, r'C:\Temp\Project_boundary.shp')
    """
    array = arcpy.Array()
    array.add(ext.lowerLeft)
    array.add(ext.lowerRight)
    array.add(ext.upperRight)
    array.add(ext.upperLeft)
    array.add(ext.lowerLeft)
    return arcpy.Polygon(array, sr) 
Example #16
Source File: SSURGO_CheckgSSURGO.py    From geo-pit with GNU General Public License v2.0 5 votes vote down vote up
def GetFieldInfo(gdb):
    # Not being used any more.
    #
    # Assumption is that this is all dictated by the XML Workspace document so schema problems
    # should not occur as long as the standard tools were used to create all databases.
    #
    # Create standard schema description for each geodatabase and use it in comparison
    # to the rest of the tables

    try:
        env.workspace = gdb
        tblList = arcpy.ListTables()
        tblList.extend(arcpy.ListFeatureClasses())
        tblList.extend(arcpy.ListRasters())
        dSchema = dict()
        arcpy.SetProgressorLabel("Reading geodatabase schema...")
        arcpy.SetProgressor("step", "Reading geodatabase schema...",  0, len(tblList), 1)

        for tbl in tblList:
            tblName = tbl.encode('ascii').upper()
            arcpy.SetProgressorLabel("Reading schema for " + os.path.basename(gdb) + ": " + tblName )
            desc = arcpy.Describe(tblName)
            fields = desc.fields
            stdSchema = list()

            for fld in fields:
                stdSchema.append((fld.baseName.encode('ascii').upper(), fld.length, fld.precision, fld.scale, fld.type.encode('ascii').upper()))
                #stdSchema.append((fld.baseName.encode('ascii').upper(), fld.length, fld.precision, fld.scale, fld.type.encode('ascii').upper(), fld.aliasName.encode('ascii').upper()))

            dSchema[tblName] = stdSchema
            arcpy.SetProgressorPosition()

        arcpy.ResetProgressor()
        return dSchema

    except:
        errorMsg()
        return dict()

## =================================================================================== 
Example #17
Source File: _geodatabase.py    From registrant with MIT License 5 votes vote down vote up
def _get_wkspc_type(self):
        """Get geodatabase workspace type."""
        if self.arcpy_found:
            return [
                value for key, value in GDB_WKSPC_TYPE.items() if key.lower() in
                arcpy.Describe(self.path).workspaceFactoryProgID.lower()
            ][0]
        else:
            return 'File geodatabase' 
Example #18
Source File: recreate_geometry.py    From collector-tools with Apache License 2.0 5 votes vote down vote up
def main():
    # Get all of the input parameters as text
    parameters = arcpy.GetParameterInfo()
    input_fc = parameters[0].valueAsText
    output_path = arcpy.Describe(parameters[5].value).path
    output_name = arcpy.Describe(parameters[5].value).name
    in_spatial_ref = parameters[1].valueAsText
    x_field = parameters[2].valueAsText
    y_field = parameters[3].valueAsText
    z_field = parameters[4].valueAsText
    update_geom(input_fc, output_path, output_name, in_spatial_ref, x_field, y_field, z_field) 
Example #19
Source File: add_update_gnss_fields.py    From collector-tools with Apache License 2.0 5 votes vote down vote up
def get_geodatabase_path(input_layer):
    """
    Gets the parent geodatabase of the layer
    :param input_layer: (string) The feature layer to get the parent database of
    :return: (string) The path to the geodatabase
    """
    workspace = os.path.dirname(arcpy.Describe(input_layer).catalogPath)
    if [any(ext) for ext in ('.gdb', '.mdb', '.sde') if ext in os.path.splitext(workspace)]:
        return workspace
    else:
        return os.path.dirname(workspace) 
Example #20
Source File: SSURGO_CheckgSSURGO2.py    From geo-pit with GNU General Public License v2.0 5 votes vote down vote up
def GetFieldInfo(gdb):
    # Not being used any more.
    #
    # Assumption is that this is all dictated by the XML Workspace document so schema problems
    # should not occur as long as the standard tools were used to create all databases.
    #
    # Create standard schema description for each geodatabase and use it in comparison
    # to the rest of the tables

    try:
        env.workspace = gdb
        tblList = arcpy.ListTables()
        tblList.extend(arcpy.ListFeatureClasses())
        tblList.extend(arcpy.ListRasters())
        dSchema = dict()
        arcpy.SetProgressorLabel("Reading geodatabase schema...")
        arcpy.SetProgressor("step", "Reading geodatabase schema...",  0, len(tblList), 1)

        for tbl in tblList:
            tblName = tbl.encode('ascii').upper()
            arcpy.SetProgressorLabel("Reading schema for " + os.path.basename(gdb) + ": " + tblName )
            desc = arcpy.Describe(tblName)
            fields = desc.fields
            stdSchema = list()

            for fld in fields:
                stdSchema.append((fld.baseName.encode('ascii').upper(), fld.length, fld.precision, fld.scale, fld.type.encode('ascii').upper()))
                #stdSchema.append((fld.baseName.encode('ascii').upper(), fld.length, fld.precision, fld.scale, fld.type.encode('ascii').upper(), fld.aliasName.encode('ascii').upper()))

            dSchema[tblName] = stdSchema
            arcpy.SetProgressorPosition()

        arcpy.ResetProgressor()
        return dSchema

    except:
        errorMsg()
        return dict()

## =================================================================================== 
Example #21
Source File: Select_Mapunits_by_Project.py    From geo-pit with GNU General Public License v2.0 5 votes vote down vote up
def FindField(ssurgoInput, chkField):
    # Check table or featureclass to see if specified field exists
    # If fully qualified name is found, return that name; otherwise return ""
    # Set workspace before calling FindField

    try:

        if arcpy.Exists(ssurgoInput):

            theDesc = arcpy.Describe(ssurgoInput)
            theFields = theDesc.fields
            theField = theFields[0]

            for theField in theFields:

                # Parses a fully qualified field name into its components (database, owner name, table name, and field name)
                parseList = arcpy.ParseFieldName(theField.name) # (null), (null), (null), MUKEY

                # choose the last component which would be the field name
                theFieldname = parseList.split(",")[len(parseList.split(','))-1].strip()  # MUKEY

                if theFieldname.upper() == chkField.upper():
                    return theField.name

            return ""

        else:
            AddMsgAndPrint("\tInput layer not found", 0)
            return ""

    except:
        errorMsg()
        return ""

## =================================================================================== 
Example #22
Source File: SSURGO_Slope_Range_Inventory.py    From geo-pit with GNU General Public License v2.0 5 votes vote down vote up
def FindField(layer, chkField):
    # Check table or featureclass to see if specified field exists
    # If fully qualified name is found, return that name; otherwise return ""
    # Set workspace before calling FindField

    try:

        if arcpy.Exists(layer):

            theDesc = arcpy.Describe(layer)
            theFields = theDesc.fields
            theField = theFields[0]

            for theField in theFields:

                # Parses a fully qualified field name into its components (database, owner name, table name, and field name)
                parseList = arcpy.ParseFieldName(theField.name) # (null), (null), (null), MUKEY

                # choose the last component which would be the field name
                theFieldname = parseList.split(",")[len(parseList.split(','))-1].strip()  # MUKEY

                if theFieldname.upper() == chkField.upper():
                    return theField.name

            return ""

        else:
            AddMsgAndPrint("\tInput layer not found", 0)
            return ""

    except:
        errorMsg()
        return ""

## =============================================================================================================== 
Example #23
Source File: arc_restapi.py    From restapi with GNU General Public License v2.0 5 votes vote down vote up
def find_ws_type(path):
    """Determines output workspace (feature class if not FileSystem).
        returns a tuple of workspace path and type.

    Arg:
        path: Path for workspace.
    """

    # try original path first
    if not arcpy.Exists(path):
        path = os.path.dirname(path)

    desc = arcpy.Describe(path)
    if hasattr(desc, 'workspaceType'):
        return path, desc.workspaceType

    # search until finding a valid workspace
    split = list(filter(None, path.split(os.sep)))
    if path.startswith('\\\\'):
        split[0] = r'\\{0}'.format(split[0])

    # find valid workspace
    for i in range(1, len(split)):
        sub_dir = os.sep.join(split[:-i])
        desc = arcpy.Describe(sub_dir)
        if hasattr(desc, 'workspaceType'):
            return sub_dir, desc.workspaceType 
Example #24
Source File: Area_Geodata_Breakdown_Description.py    From geo-pit with GNU General Public License v2.0 5 votes vote down vote up
def FindField(layer, chkField):
    # Check table or featureclass to see if specified field exists
    # If fully qualified name is found, return that name; otherwise return ""
    # Set workspace before calling FindField

    try:

        if arcpy.Exists(layer):

            theDesc = arcpy.Describe(layer)
            theFields = theDesc.fields
            theField = theFields[0]

            for theField in theFields:

                # Parses a fully qualified field name into its components (database, owner name, table name, and field name)
                parseList = arcpy.ParseFieldName(theField.name) # (null), (null), (null), MUKEY

                # choose the last component which would be the field name
                theFieldname = parseList.split(",")[len(parseList.split(','))-1].strip()  # MUKEY

                if theFieldname.upper() == chkField.upper():
                    return theField.name

            return ""

        else:
            AddMsgAndPrint("\tInput layer not found", 0)
            return ""

    except:
        errorMsg()
        return ""

# =============================================================================================================== 
Example #25
Source File: tool_densfilter.py    From HiSpatialCluster with Apache License 2.0 5 votes vote down vote up
def updateParameters(self, parameters):
#        if parameters[0].altered and not parameters[2].altered:
#            parameters[2].value=arcpy.Describe(parameters[0].valueAsText).OIDFieldName
            
        if parameters[0].altered and not parameters[5].altered:
            in_fe=parameters[0].valueAsText   
            parameters[5].value=in_fe[:len(in_fe)-4]+'_filter'+in_fe[-4:] if in_fe[-3:]=='shp' else in_fe+'_filter'
                          
        return 
Example #26
Source File: arcapi.py    From arcapi with GNU Lesser General Public License v3.0 5 votes vote down vote up
def copy_schema(template, new, sr=''):
    """Copy the schema (field definition) of a feature class or a table.

    Required:
    template -- template table or fc
    new -- new output fc or table

    Optional:
    sr -- spatial reference (only applies if fc) If no sr
          is defined, it will default to sr of template.

    Example:
    >>> copy_schema(r'C:\Temp\soils_city.shp', r'C:\Temp\soils_county.shp')
    """
    path, name = os.path.split(new)
    desc = arcpy.Describe(template)
    ftype = desc.dataType
    if 'table' in ftype.lower():
        arcpy.CreateTable_management(path, name, template)
    else:
        stype = desc.shapeType.upper()
        sm = 'SAME_AS_TEMPLATE'
        if not sr:
            sr = desc.spatialReference
        arcpy.CreateFeatureclass_management(path, name, stype, template, sm, sm, sr)
    return new 
Example #27
Source File: arcapi.py    From arcapi with GNU Lesser General Public License v3.0 5 votes vote down vote up
def fill_no_data(in_raster, out_raster, w=5, h=5):
    """Fill "NoData" cells with mean values from focal statistics.

    Use a larger neighborhood for raster with large areas of no data cells.

    *** Requires spatial analyst extension ***

    Required:
    in_raster -- input raster
    out_raster -- output raster

    Optional:
    w -- search radius width for focal stats (rectangle)
    h -- search radius height for focal stats (rectangle)

    Example:
    >>> fill_no_data(r'C:\Temp\ndvi', r'C:\Temp\ndvi_filled', 10, 10)
    """
    try:
        import arcpy.sa as sa
        # Make Copy of Raster
        _dir, name = os.path.split(arcpy.Describe(in_raster).catalogPath)
        temp = os.path.join(_dir, 'rast_copyxxx')
        if arcpy.Exists(temp):
            arcpy.Delete_management(temp)
        arcpy.CopyRaster_management(in_raster, temp)

        # Fill NoData
        arcpy.CheckOutExtension('Spatial')
        filled = sa.Con(sa.IsNull(temp),sa.FocalStatistics(temp,sa.NbrRectangle(w,h),'MEAN'),temp)
        filled.save(out_raster)
        arcpy.BuildPyramids_management(out_raster)
        arcpy.CheckInExtension('Spatial')

        # Delete original and replace
        if arcpy.Exists(temp):
            arcpy.Delete_management(temp)
        msg('Filled NoData Cells in: %s' %out_raster)
        return out_raster
    except ImportError:
        return 'Module arcpy.sa not found.' 
Example #28
Source File: arcapi.py    From arcapi with GNU Lesser General Public License v3.0 5 votes vote down vote up
def to_scratch(name, enforce=False):
    """Return path to a dataset called name in scratch workspace.

    LIMITATION: Reliable for geodatabases only! Does not handle extensions.

    Returns os.path.join(arcpy.env.scratchWorkspace, name).
    If scratchWorkspace is None, it tries workspace, then scratchGDB.

    This function 'to_scratch' has also an alias 'tos'!

    Required:
    name -- basename of the output dataset

    Optional:
    enforce -- if True, arcpy.CreateScratchName is used to ensure name does not
        exist in scratch workspace, otherwise returns basename equal to name.

    Example:
    >>> to_scratch('foo', 0) # '...\\scratch.gdb\\foo'
    >>> to_scratch('foo', 1) # '...\\scratch.gdb\\foo0'
    >>> to_scratch('foo.shp', 0) # '...\\scratch.gdb\\foo_shp'
    >>> to_scratch('foo.shp', 1) # '...\\scratch.gdb\\foo_shp0'
    >>> tos('foo', 0) # '...\\scratch.gdb\\foo'
    """
    ws = arcpy.env.scratchWorkspace
    if ws is None: ws = arcpy.env.workspace
    if ws is None: ws = arcpy.env.scratchGDB

    if arcpy.Describe(ws).workspaceType.lower() == 'filesystem':
        m = "Scratch workspace is a folder, scratch names may be incorrect."
        msg(m)
        arcpy.AddWarning(m)

    nm = os.path.basename(name)
    nm = arcpy.ValidateTableName(nm, ws)
    if enforce:
        nm = arcpy.CreateScratchName(nm, workspace=ws)
    else:
        nm = os.path.join(ws, nm)
    return nm 
Example #29
Source File: Validate_Mapunit_Slope_Range.py    From geo-pit with GNU General Public License v2.0 5 votes vote down vote up
def FindField(layer, chkField):
    # Check table or featureclass to see if specified field exists
    # If fully qualified name is found, return that name; otherwise return ""
    # Set workspace before calling FindField

    try:

        if arcpy.Exists(layer):

            theDesc = arcpy.Describe(layer)
            theFields = theDesc.fields
            theField = theFields[0]

            for theField in theFields:

                # Parses a fully qualified field name into its components (database, owner name, table name, and field name)
                parseList = arcpy.ParseFieldName(theField.name) # (null), (null), (null), MUKEY

                # choose the last component which would be the field name
                theFieldname = parseList.split(",")[len(parseList.split(','))-1].strip()  # MUKEY

                if theFieldname.upper() == chkField.upper():
                    return theField.name

            return ""

        else:
            AddMsgAndPrint("\tInput layer not found", 0)
            return ""

    except:
        errorMsg()
        return ""

## =================================================================================== 
Example #30
Source File: Select_Mapunits_by_Project_NATSYM.py    From geo-pit with GNU General Public License v2.0 5 votes vote down vote up
def FindField(ssurgoInput, chkField):
    # Check table or featureclass to see if specified field exists
    # If fully qualified name is found, return that name; otherwise return ""
    # Set workspace before calling FindField

    try:

        if arcpy.Exists(ssurgoInput):

            theDesc = arcpy.Describe(ssurgoInput)
            theFields = theDesc.fields
            theField = theFields[0]

            for theField in theFields:

                # Parses a fully qualified field name into its components (database, owner name, table name, and field name)
                parseList = arcpy.ParseFieldName(theField.name) # (null), (null), (null), MUKEY

                # choose the last component which would be the field name
                theFieldname = parseList.split(",")[len(parseList.split(','))-1].strip()  # MUKEY

                if theFieldname.upper() == chkField.upper():
                    return theField.name

            return ""

        else:
            AddMsgAndPrint("\tInput layer not found", 0)
            return ""

    except:
        errorMsg()
        return ""

## ===================================================================================