Python arcpy.Delete_management() Examples

The following are 30 code examples of arcpy.Delete_management(). 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_test.py    From arcapi with GNU Lesser General Public License v3.0 7 votes vote down vote up
def testto_points(self):
        obs = 10
        wc = '"OBJECTID" < ' + str(obs + 1)
        ofc = arcpy.CreateScratchName("tmp_out.dbf", workspace="c:\\temp").replace('.dbf', '.shp')
        cs = 27700
        ptfc = ap.to_points(self.t_fc, ofc, "POP_EST", "GDP_MD_EST", cs, w = wc)
        est = int(arcpy.GetCount_management(ptfc).getOutput(0))
        arcpy.Delete_management(ptfc)
        self.assertEqual(est, obs)
        pass


##    def testwsp(self):
##        pass
##
##    def testswsp(self):
##        pass 
Example #3
Source File: mapmatcher.py    From mapmatching with MIT License 6 votes vote down vote up
def exportPath(opt, trackname):
    """
    This exports the list of segments into a shapefile, a subset of the loaded segment file, including all attributes
    """
    start_time = time.time()
    opt=getUniqueList(opt)
    qr =  '"OBJECTID" IN ' +str(tuple(opt))
    outname = (os.path.splitext(os.path.basename(trackname))[0][:9])+'_pth'
    arcpy.SelectLayerByAttribute_management('segments_lyr',"NEW_SELECTION", qr)
    try:
        if arcpy.Exists(outname):
            arcpy.Delete_management(outname)
        arcpy.FeatureClassToFeatureClass_conversion('segments_lyr', arcpy.env.workspace, outname)
        print("--- export: %s seconds ---" % (time.time() - start_time))
    except Exception:
        e = sys.exc_info()[1]
        print(e.args[0])

        # If using this code within a script tool, AddError can be used to return messages
        #   back to a script tool.  If not, AddError will have no effect.
        arcpy.AddError(e.args[0])
        arcpy.AddError(arcpy.env.workspace)
        arcpy.AddError(outname)
        #raise arcpy.ExecuteError
    except arcpy.ExecuteError:
        arcpy.AddError(arcpy.GetMessages(2))

    # Return any other type of error
    except:
        # By default any other errors will be caught here
        #
        e = sys.exc_info()[1]
        print(e.args[0])
        arcpy.AddError(e.args[0])
        arcpy.AddError(arcpy.env.workspace)
        arcpy.AddError(outname) 
Example #4
Source File: WMX_Generalization.py    From CTM with Apache License 2.0 6 votes vote down vote up
def splitLines(in_workspace, job_aoi, names=[]):
    """ gets a list of all feature classes in a database, includes feature
    classes inside and outside of the feature datasets"""

    fcs = []

    walk = arcpy.da.Walk(in_workspace, datatype="FeatureClass")

    for dirpath, dirnames, filenames in walk:
        for filename in filenames:
            if filename in names:
                fc = os.path.join(dirpath, filename)
                split = arcpy.Identity_analysis(fc, job_aoi, "in_memory\\split_"+filename)
                single = arcpy.MultipartToSinglepart_management(split, "in_memory\\split"+filename)
                arcpy.DeleteFeatures_management(fc)
                arcpy.Append_management(single, fc, "NO_TEST")

                arcpy.Delete_management(split)
                arcpy.Delete_management(single)


    return fcs 
Example #5
Source File: arcapi_test.py    From arcapi with GNU Lesser General Public License v3.0 6 votes vote down vote up
def testcombine_pdfs(self):
        _dir = os.path.dirname(self.testingfolder)
        mapDoc = os.path.join(_dir, 'chart.mxd')
        mxd = arcpy.mapping.MapDocument(mapDoc)
        txt_elm = [elm for elm in arcpy.mapping.ListLayoutElements(mxd, 'TEXT_ELEMENT')
                   if elm.text == 'SomeText'][0]
        del_list = []
        for i in range(3):
            txt_elm.text = "Hi, I'm page {0}".format(i)
            pdf = os.path.join(_dir, 'test_{0}.pdf'.format(i))
            arcpy.mapping.ExportToPDF(mxd, pdf, resolution=100)
            del_list.append(pdf)
        combined = os.path.join(_dir, 'combined.pdf')
        del mxd
        ap.combine_pdfs(combined, del_list)
        self.assertTrue(os.path.exists(combined))
        del_list.append(combined)
        try:
            for p in del_list:
                arcpy.Delete_management(p)
        except:
            pass
        pass 
Example #6
Source File: arcapi_test.py    From arcapi with GNU Lesser General Public License v3.0 6 votes vote down vote up
def testconcatenate_fields(self):
        if arcpy.Exists(r'in_memory\copy'):
            arcpy.Delete_management(r'in_memory\copy')
        fc = os.path.join(self.testing_gdb, 'Illinois')
        copy = fc + '_copy'
        if arcpy.Exists(copy):
            arcpy.Delete_management(copy)
        arcpy.CopyFeatures_management(fc, copy)
        ap.concatenate_fields(copy, 'FULL', 75, ['NAME', 'STATE_NAME'], ' County, ')
        obs = 'Jo Daviess County, Illinois'
        with arcpy.da.SearchCursor(copy, 'FULL') as rows:
            est = rows.next()[0]
        del rows
        try:
            arcpy.Delete_management(copy)
        except: pass
        self.assertEqual(est, obs)
        pass 
Example #7
Source File: arcapi_test.py    From arcapi with GNU Lesser General Public License v3.0 6 votes vote down vote up
def testjoin_using_dict(self):
        if arcpy.Exists(r'in_memory\copy'):
            arcpy.Delete_management(r'in_memory\copy')
        fc = os.path.join(self.testing_gdb, 'Illinois')
        copy = fc + '_copy'
        if arcpy.Exists(copy):
            arcpy.Delete_management(copy)
        arcpy.CopyFeatures_management(fc, copy)
        flds = ['POP1990', 'POP2000']
        tab = fc = os.path.join(self.testing_gdb, 'Illinois_county_info')
        ap.join_using_dict(copy, 'CNTY_FIPS', tab, 'CNTY_FIPS', flds)
        est = [f.name for f in arcpy.ListFields(copy)]
        try:
            arcpy.Delete_management(copy)
        except: pass
        for f in flds:
            self.assertTrue(f in est)
        pass 
Example #8
Source File: arcapi_test.py    From arcapi with GNU Lesser General Public License v3.0 6 votes vote down vote up
def testadd_fields_from_table(self):
        fc = os.path.join(self.testing_gdb, 'Illinois')
        copy = fc + '_copy'
        if arcpy.Exists(copy):
            arcpy.Delete_management(copy)
        arcpy.CopyFeatures_management(fc, copy)
        flds = ['POP1990', 'POP2000']
        tab = fc = os.path.join(self.testing_gdb, 'Illinois_county_info')
        ap.add_fields_from_table(copy, tab, flds)
        est = [f.name for f in arcpy.ListFields(copy)]
        try:
            arcpy.Delete_management(copy)
        except: pass
        for f in flds:
            self.assertTrue(f in est)
        pass 
Example #9
Source File: arcapi_test.py    From arcapi with GNU Lesser General Public License v3.0 6 votes vote down vote up
def testint_to_float(self):
        _dir = os.path.join(self.testingfolder, r'testing_files\rasters')
        ndvi = os.path.join(_dir, 'dh_july_ndvi')
        ob = round(arcpy.Raster(ndvi).maximum, 5)
        int_rst = os.path.join(_dir, 'ndvi_int')
        est = os.path.join(_dir, 'ndvi_tst')
        if arcpy.CheckExtension('Spatial') == 'Available':
            arcpy.CheckOutExtension('Spatial')
            arcpy.sa.Int(arcpy.sa.Times(ndvi, 1000000)).save(int_rst)
            arcpy.CheckInExtension('Spatial')
            ap.int_to_float(int_rst, est, 6)
            self.assertEqual(ob, round(arcpy.Raster(est).maximum, 5))
            for rast in [int_rst, est]:
                try:
                    arcpy.Delete_management(rast)
                except:pass
        pass 
Example #10
Source File: arcapi_test.py    From arcapi with GNU Lesser General Public License v3.0 6 votes vote down vote up
def testdlt(self):
        est = []
        wc = '"OBJECTID" < 11'
        lr = arcpy.management.MakeFeatureLayer(self.t_fc, "lr", wc).getOutput(0)
        # TODO: test for deleting layers won't pass even though ap.dlt works
        #print lr
        #print arcpy.Exists(lr)
        tempfc = 'in_memory\\tmp'
        if arcpy.Exists(tempfc):
            arcpy.Delete_management(tempfc)
        tmpfc = arcpy.CopyFeatures_management(lr, tempfc).getOutput(0)
        tempshp = arcpy.CreateScratchName('tmp.dbf', workspace='c:\\temp').replace('.dbf', '.shp')
        fc = arcpy.CopyFeatures_management(tmpfc, tempshp).getOutput(0)
        ap.dlt(lr)
        est.append(ap.dlt(tmpfc))
        est.append(ap.dlt(fc))
        est.append(ap.dlt('this does not exist'))
        self.assertEquals(est, [True, True, False])
        pass 
Example #11
Source File: dataprep.py    From utilities-solution-data-automation with Apache License 2.0 6 votes vote down vote up
def _CheckCreateGDBProcess(self):
        try:
            # If user param is to overwrite GDB, then delete it first
            if self.overWrite.upper() == "YES":
                if arcpy.Exists(self.end_db)==True:
                    arcpy.Delete_management(self.end_db)
                    self.overWrite = None
                    print "Deleted previous GDB {0}".format(self.end_db)
             
            # if the local gdb doesn't exist, then create it using the path and name given in the end_db string
            if arcpy.Exists(self.end_db)==False:
                if self.end_db.rfind("\\") != -1:    
                    lastSlash = self.end_db.rfind("\\")
                else:
                    lastSlash = self.end_db.rfind("/")           
                arcpy.CreateFileGDB_management(self.end_db[:lastSlash], self.end_db[lastSlash+1:])
                self.overWrite = None
                print "Created geodatabase {0}".format(self.end_db[lastSlash+1:])
            else:
                self.overWrite = None
                #print "Geodatabase already exists" 
            return True 
        except:
            print "Unexpected error create geodatabase:", sys.exc_info()[0]
            return False 
Example #12
Source File: mapmatcher.py    From mapmatching with MIT License 6 votes vote down vote up
def getClosestSegment(point, segments, maxdist):
    arcpy.Delete_management('segments_lyr')
    arcpy.MakeFeatureLayer_management(segments, 'segments_lyr')
    arcpy.SelectLayerByLocation_management ("segments_lyr", "WITHIN_A_DISTANCE", point, maxdist)

    #Go through these, compute distances, probabilities and store them as candidates
    cursor = arcpy.da.SearchCursor('segments_lyr', ["OBJECTID", "SHAPE@"])
    sdist = 100000
    candidate = ''
    for row in cursor:
        #compute the spatial distance
        dist = point.distanceTo(row[1])
        if dist <sdist:
            sdist=dist
            candidate = row[0]
    del row
    del cursor
    #print str(candidates)
    return candidate 
Example #13
Source File: mapmatcher.py    From mapmatching with MIT License 6 votes vote down vote up
def getSegmentInfo(segments):
    """
    Builds a dictionary for looking up endpoints of network segments (needed only because networkx graph identifies edges by nodes)
    """
    if arcpy.Exists(segments):
        cursor = arcpy.da.SearchCursor(segments, ["OBJECTID", "SHAPE@"])
        endpoints = {}
        segmentlengths = {}
        for row in cursor:
              endpoints[row[0]]=((row[1].firstPoint.X,row[1].firstPoint.Y), (row[1].lastPoint.X, row[1].lastPoint.Y))
              segmentlengths[row[0]]= row[1].length
        del row
        del cursor
        print "Number of segments: "+ str(len(endpoints))
        #prepare segment layer for fast search
        arcpy.Delete_management('segments_lyr')
        arcpy.MakeFeatureLayer_management(segments, 'segments_lyr')
        return (endpoints,segmentlengths)
    else:
        print "segment file does not exist!" 
Example #14
Source File: mapmatcher.py    From mapmatching with MIT License 6 votes vote down vote up
def exportPath(opt, trackname):
    """
    This exports the list of segments into a shapefile, a subset of the loaded segment file, including all attributes
    """
    start_time = time.time()
    opt=getUniqueList(opt)
    qr =  '"OBJECTID" IN ' +str(tuple(opt))
    outname = (os.path.splitext(os.path.basename(trackname))[0][:9])+'_pth'
    arcpy.SelectLayerByAttribute_management('segments_lyr',"NEW_SELECTION", qr)
    try:
        if arcpy.Exists(outname):
            arcpy.Delete_management(outname)
        arcpy.FeatureClassToFeatureClass_conversion('segments_lyr', arcpy.env.workspace, outname)
        print("--- export: %s seconds ---" % (time.time() - start_time))
    except Exception:
        e = sys.exc_info()[1]
        print(e.args[0])

        # If using this code within a script tool, AddError can be used to return messages
        #   back to a script tool.  If not, AddError will have no effect.
        arcpy.AddError(e.args[0])
        arcpy.AddError(arcpy.env.workspace)
        arcpy.AddError(outname)
        #raise arcpy.ExecuteError
    except arcpy.ExecuteError:
        arcpy.AddError(arcpy.GetMessages(2))

    # Return any other type of error
    except:
        # By default any other errors will be caught here
        #
        e = sys.exc_info()[1]
        print(e.args[0])
        arcpy.AddError(e.args[0])
        arcpy.AddError(arcpy.env.workspace)
        arcpy.AddError(outname) 
Example #15
Source File: mapmatcher.py    From mapmatching with MIT License 6 votes vote down vote up
def getClosestSegment(point, segments, maxdist):
    arcpy.Delete_management('segments_lyr')
    arcpy.MakeFeatureLayer_management(segments, 'segments_lyr')
    arcpy.SelectLayerByLocation_management ("segments_lyr", "WITHIN_A_DISTANCE", point, maxdist)

    #Go through these, compute distances, probabilities and store them as candidates
    cursor = arcpy.da.SearchCursor('segments_lyr', ["OBJECTID", "SHAPE@"])
    sdist = 100000
    candidate = ''
    for row in cursor:
        #compute the spatial distance
        dist = point.distanceTo(row[1])
        if dist <sdist:
            sdist=dist
            candidate = row[0]
    del row
    del cursor
    #print str(candidates)
    return candidate 
Example #16
Source File: arcapi_test.py    From arcapi with GNU Lesser General Public License v3.0 5 votes vote down vote up
def testrename_col(self):
        import arcpy
        import tempfile
        owo = arcpy.env.overwriteOutput
        arcpy.env.overwriteOutput = True
        tmpfc = os.path.join(tempfile.gettempdir(), "tmp")
        tmpfc = arcpy.CopyFeatures_management(self.t_fc, tmpfc).getOutput(0)
        est = ap.rename_col(tmpfc, "ABBREV", "ABBREVIATION")
        obs = "ABBREVIATI"
        arcpy.Delete_management(tmpfc)
        arcpy.env.overwriteOutput = owo
        self.assertEqual(est, obs)
        pass 
Example #17
Source File: WMX_Generalization.py    From CTM with Apache License 2.0 5 votes vote down vote up
def setEdgeHierarchy(fcs, aoi, hier_field):
    """ sets the hierarchy of all features touching the aoi to 0"""
    arcpy.AddMessage("Setting hierarcy for edge features")
    for fc in fcs:
        fields = [f.name for f in arcpy.ListFields(fc)]
        if hier_field in fields:
            lyr = arcpy.MakeFeatureLayer_management(fc, "layera")
            arcpy.SelectLayerByLocation_management(lyr, "INTERSECT", aoi)
            arcpy.CalculateField_management(lyr, hier_field, "0")
            arcpy.Delete_management(lyr) 
Example #18
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 #19
Source File: arcapi.py    From arcapi with GNU Lesser General Public License v3.0 5 votes vote down vote up
def dlt(x):
    """arcpy.Delete_management(x) if arcpy.Exists(x).

    Return False if x does not exist, True if x exists and was deleted.
    """
    deletted = False
    if arcpy.Exists(x):
        arcpy.Delete_management(x)
        deletted = True
    return deletted 
Example #20
Source File: spatial.py    From ArcREST with Apache License 2.0 5 votes vote down vote up
def merge_feature_class(merges, out_fc, cleanUp=True):
    """ merges featureclass into a single feature class """
    if arcpyFound == False:
        raise Exception("ArcPy is required to use this function")
    if cleanUp == False:
        if len(merges) == 0:
            return None
        elif len(merges) == 1:
            desc = arcpy.Describe(merges[0])
            if hasattr(desc, 'shapeFieldName'):
                return arcpy.CopyFeatures_management(merges[0], out_fc)[0]
            else:
                return arcpy.CopyRows_management(merges[0], out_fc)[0]
        else:
            return arcpy.Merge_management(inputs=merges,
                                          output=out_fc)[0]
    else:
        if len(merges) == 0:
            return None
        elif len(merges) == 1:
            desc = arcpy.Describe(merges[0])
            if hasattr(desc, 'shapeFieldName'):
                merged = arcpy.CopyFeatures_management(merges[0], out_fc)[0]
            else:
                merged = arcpy.CopyRows_management(merges[0], out_fc)[0]
        else:
            merged = arcpy.Merge_management(inputs=merges,
                                        output=out_fc)[0]
        for m in merges:
            arcpy.Delete_management(m)
            del m
        return merged
#---------------------------------------------------------------------- 
Example #21
Source File: arcapi_test.py    From arcapi with GNU Lesser General Public License v3.0 5 votes vote down vote up
def testcopy_schema(self):
        tmp = r'in_memory\schema_test'
        ap.copy_schema(self.t_fc, tmp)
        self.assertTrue(arcpy.Exists(tmp))
        arcpy.Delete_management(tmp)
        pass 
Example #22
Source File: arcapi_test.py    From arcapi with GNU Lesser General Public License v3.0 5 votes vote down vote up
def testmeters_to_feet(self):
        _dir = os.path.join(self.testingfolder, r'testing_files\rasters')
        dem = os.path.join(_dir, 'dh30m_dem')
        est = os.path.join(_dir, 'dem_ft')
        ap.meters_to_feet(dem, est)
        self.assertEqual(int(arcpy.Raster(est).maximum), 6244)
        try:
            arcpy.Delete_management(est)
        except:
            pass
        pass 
Example #23
Source File: DataServicePillager.py    From DataPillager with MIT License 5 votes vote down vote up
def combine_data(fc_list, output_fc):
    """ :param fc_list: array of featureclass paths as strings
        :param output_fc: path to output dataset
        Combine the downloaded datafiles into one
        fastest approach is to use cursor
    """
    if len(fc_list) == 1:
        arcpy.Copy_management(fc_list[0], output_fc)
        output_msg("Created {0}".format(output_fc))
    else:
        for fc in fc_list:
            if fc_list.index(fc) == 0:
                # append to first dataset. much faster
                output_msg("Prepping yer first dataset {0}".format(fc))
                if arcpy.Exists(output_fc):
                    output_msg("Avast! {0} exists, deleting...".format(output_fc), severity=1)
                    arcpy.Delete_management(output_fc)
                
                arcpy.Copy_management(fc, output_fc)  # create dataset to append to
                output_msg("Created {0}".format(output_fc))

                fieldlist = []
                #fieldlist = ["SHAPE@"]
                fields = arcpy.ListFields(output_fc)
                for field in fields:
                    if field.name.lower() == u'shape':
                        fieldlist.insert(0, "SHAPE@") # add shape token to start
                    else:
                        fieldlist.append(field.name)
                #fields = [field.name for field in arcpy.ListFields(output_fc) if field.name.lower() not in [u'shape']]
                #fieldlist.extend(fields)
                ##arcpy.CopyFeatures_management(output_fc, fc) # duplicate first one so delete later doesn't fail
                insert_rows = arcpy.da.InsertCursor(output_fc, fieldlist)
            else:
                search_rows = arcpy.da.SearchCursor(fc, fieldlist) # append to first dataset
                for row in search_rows:
                    insert_rows.insertRow(row)
                del row, search_rows
                output_msg("Appended {0}...".format(fc))
        del insert_rows 
Example #24
Source File: reporttools.py    From utilities-solution-data-automation with Apache License 2.0 5 votes vote down vote up
def _CheckCreateGDBProcess(outputWorkspace):
    try:
        # If user param is to overwrite GDB, then delete it first
        if arcpy.Exists(outputWorkspace) == True:
            arcpy.Delete_management(outputWorkspace)
            print "Deleted previous GDB {0}".format(outputWorkspace)

        # if the local gdb doesn't exist, then create it using the path and name given in the end_db string
        if arcpy.Exists(outputWorkspace) == False:
            if outputWorkspace.rfind("\\") != -1:
                lastSlash = outputWorkspace.rfind("\\")
            else:
                lastSlash = outputWorkspace.rfind("/")
            arcpy.CreateFileGDB_management(outputWorkspace[:lastSlash], outputWorkspace[lastSlash + 1:])

            print "Created geodatabase {0}".format(outputWorkspace[lastSlash + 1:])


    except arcpy.ExecuteError:
        line, filename, synerror = trace()
        raise ReportToolsError({
            "function": "_CheckCreateGDBProcess",
            "line": line,
            "filename": filename,
            "synerror": synerror,
            "arcpyError": arcpy.GetMessages(2),
        })
    except:
        line, filename, synerror = trace()
        raise ReportToolsError({
            "function": "_CheckCreateGDBProcess",
            "line": line,
            "filename": filename,
            "synerror": synerror,
        })


# ---------------------------------------------------------------------- 
Example #25
Source File: reporttools.py    From utilities-solution-data-automation with Apache License 2.0 5 votes vote down vote up
def deleteFC(in_datasets):
    for in_data in in_datasets:
        try:
            if in_data is not None:
                if arcpy.Exists(dataset=in_data):
                    arcpy.Delete_management(in_data=in_data)

        except Exception:
            print "Unable to delete %s" % in_data


# ----------------------------------------------------------------------
# Function to merge run time reports into a temp feature class to export to CSV.
# This create a new FC with the first report, then just append fields for subsequent reports. 
Example #26
Source File: arcapi_test.py    From arcapi with GNU Lesser General Public License v3.0 5 votes vote down vote up
def testtlist_to_table(self):
        colnames = ['NAME', 'POP_EST']
        coltypes = ['TEXT', 'DOUBLE']
        collengths = [250, '#']
        coldefs = zip(colnames, coltypes, collengths)
        coldefs2 = ['NAME:TEXT', 'POP_EST:DOUBLE']

        # read data
        tl = []
        with arcpy.da.SearchCursor(self.t_fc, colnames) as sc:
            for row in sc:
                tl.append(tuple(row))

        # write as table using log column definition
        ot = arcpy.CreateScratchName('tmp.dbf', workspace='c:\\temp')
        ot = ap.tlist_to_table(tl, ot, coldefs, -9, 'nullText')
        est1 = int(arcpy.GetCount_management(ot).getOutput(0))

        # write as table using short column definition
        ot = arcpy.CreateScratchName('tmp.dbf', workspace='c:\\temp')
        ot = ap.tlist_to_table(tl, ot, coldefs2, -9, 'nullText')
        est2 = int(arcpy.GetCount_management(ot).getOutput(0))
        obs = int(arcpy.GetCount_management(self.t_fc).getOutput(0))

        arcpy.Delete_management(ot)
        self.assertTrue(all((est1 == obs, est2 == obs)))
        pass

##    def testdocu(self):
##        pass 
Example #27
Source File: gptools.py    From utilities-solution-data-automation with Apache License 2.0 5 votes vote down vote up
def speedyIntersect(fcToSplit,
                    splitFC,
                    fieldsToAssign,
                    countField,
                    onlyKeepLargest,
                    outputFC,
                    report_areas_overlap):
    #arcpy.AddMessage(time.ctime())

    startProcessing = time.time()
    arcpy.env.overwriteOutput = True
    tempWorkspace = arcpy.env.scratchGDB
    tempFCName = Common.random_string_generator()
    tempFC= os.path.join(tempWorkspace, tempFCName)



    tempFCUnionName = Common.random_string_generator()
    tempFCUnion = os.path.join(tempWorkspace, tempFCUnionName)

    arcpy.Dissolve_management(in_features=splitFC,
                              out_feature_class=tempFCUnion,
                             dissolve_field=fieldsToAssign,
                             statistics_fields=None,
                             multi_part='SINGLE_PART',
                             unsplit_lines=None)


    fc = splitByLayer(fcToSplit=fcToSplit,
                      splitFC=tempFCUnion,
                      fieldsToAssign=fieldsToAssign,
                      countField=countField,
                      onlyKeepLargest=onlyKeepLargest,
                      outputFC=outputFC,
                      report_areas_overlap=report_areas_overlap)
    if arcpy.Exists(tempFCUnion):
        arcpy.Delete_management(tempFCUnion) 
Example #28
Source File: arcapi.py    From arcapi with GNU Lesser General Public License v3.0 4 votes vote down vote up
def chart(x, out_file='c:\\temp\\chart.jpg', texts={}, template=None, resolution=95, openit=True):
    """Create and open a map (JPG) showing x and return path to the figure path.

    Required:
    x -- input feature class, raster dataset, or a layer

    Optional:
    out_file -- path to output jpeg file, default is 'c:\\temp\\chart.jpg'
    texts -- dict of strings to include in text elements on the map (by name)
    template -- path to the .mxd to be used, default None points to mxd with
        a single text element called "txt"
    resolution -- output resolution in DPI (dots per inch)
    openit -- if True (default), exported jpg is opened in a webbrowser

    Example:
    >>> chart('c:\\foo\\bar.shp')
    >>> chart('c:\\foo\\bar.shp', texts = {'txt': 'A Map'}, resolution = 300)
    """
    todel = []
    import re
    if template is None: template = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'chart.mxd')
    if not re.findall(".mxd", template, flags=re.IGNORECASE): template += ".mxd"
    if not re.findall(".jpe?g", out_file, flags=re.IGNORECASE): out_file += ".jpg"

    mxd = arcpy.mapping.MapDocument(template)
    if not arcpy.Exists(x):
        x = arcpy.CopyFeatures_management(x, arcpy.CreateScratchName('tmp', workspace = 'in_memory')).getOutput(0)
        todel = [x]
    dtype = arcpy.Describe(x).dataType
    df = arcpy.mapping.ListDataFrames(mxd)[0]

    lr = "chart" + tstamp(tf = "%H%M%S")
    if arcpy.Exists(lr) and arcpy.Describe(lr).dataType in ('FeatureLayer', 'RasterLayer'):
        arcpy.Delete_management(lr)
    if "raster" in dtype.lower():
        arcpy.MakeRasterLayer_management(x, lr)
    else:
        arcpy.MakeFeatureLayer_management(x, lr)

    lyr = arcpy.mapping.Layer(lr)
    arcpy.mapping.AddLayer(df, lyr)

    # try to update text elements if any requested:
    for tel in texts.iterkeys():
        try:
            texel = arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT", tel)[0]
            texel.text = str(texts[tel])
        except Exception, e:
            arcpy.AddMessage("Error when updating text element " + str(tel) + ": "+ str(e)) 
Example #29
Source File: SSURGO_Convert_to_Geodatabase.py    From geo-pit with GNU General Public License v2.0 4 votes vote down vote up
def CreateSSURGO_DB(outputWS, inputXML, areasymbolList, aliasName):
    # Create new 10.0 File Geodatabase using XML workspace document
    #
    try:
        if not arcpy.Exists(inputXML):
            PrintMsg(" \nMissing input file: " + inputXML, 2)
            return False

        outputFolder = os.path.dirname(outputWS)
        gdbName = os.path.basename(outputWS)

        if arcpy.Exists(os.path.join(outputFolder, gdbName)):
            arcpy.Delete_management(os.path.join(outputFolder, gdbName))

        PrintMsg(" \nCreating new geodatabase (" + gdbName + ") in " + outputFolder, 0)

        arcpy.CreateFileGDB_management(outputFolder, gdbName, "10.0")

        arcpy.ImportXMLWorkspaceDocument_management (os.path.join(outputFolder, gdbName), inputXML, "DATA")

        if not arcpy.Exists(os.path.join(outputFolder, gdbName)):
            raise MyError, "Failed to create new geodatabase"

        env.workspace = os.path.join(outputFolder, gdbName)
        tblList = arcpy.ListTables()

        if len(tblList) < 50:
            raise MyError, "Output geodatabase has only " + str(len(tblList)) + " tables"

        # Alter aliases for featureclasses
        if aliasName != "":
            try:

                arcpy.AlterAliasName("MUPOLYGON", "Map Unit Polygons - " + aliasName)
                arcpy.AlterAliasName("MUPOINT", "Map Unit Points - " + aliasName)
                arcpy.AlterAliasName("MULINE", "Map Unit Lines - " + aliasName)
                arcpy.AlterAliasName("FEATPOINT", "Special Feature Points - " + aliasName)
                arcpy.AlterAliasName("FEATLINE", "Special Feature Lines - " + aliasName)
                arcpy.AlterAliasName("SAPOLYGON", "Survey Boundaries - " + aliasName)

            except:
                pass

        arcpy.RefreshCatalog(outputFolder)

        return True

    except MyError, e:
        PrintMsg(str(e), 2)
        return False 
Example #30
Source File: Validate_Mapunit_Slope_Range.py    From geo-pit with GNU General Public License v2.0 4 votes vote down vote up
def determineOverlap(muLayer):
    # This function will compute a geometric intersection of the mu polygons and the extent
    # of the slope layer to determine overlap.  If the number of features in the output is greater than
    # the sum of the features of the muLayerPath and the extentboundary then overlap is assumed
    # and TRUE is returned otherwise FALSE is returned.

    try:
        # -------------- Get the SAPOLYGON ----------- Layer
        AddMsgAndPrint("\nDeterming overlap between input polygons and slope layer",0)

        # Create a polygon footprint from the slope layer
        outDomain = arcpy.CreateScratchName(workspace=arcpy.env.scratchGDB)

        outGeom = "POLYGON"
        arcpy.RasterDomain_3d(slopeLayer, outDomain, outGeom)

        # Intersect the soils and input layer
        outIntersect = arcpy.CreateScratchName(workspace=arcpy.env.scratchGDB)
        arcpy.Intersect_analysis([muLayer,outDomain], outIntersect,"ALL","","INPUT")

        totalMUacres = sum([row[0] for row in arcpy.da.SearchCursor(muLayer, ("SHAPE@AREA"))]) / 4046.85642
        totalIntAcres = sum([row[0] for row in arcpy.da.SearchCursor(outIntersect, ("SHAPE@AREA"))]) / 4046.85642

        # All features are within the geodata extent
        if int(totalMUacres) == int(totalIntAcres):
            AddMsgAndPrint("\tALL polygons are within Raster extent",0)
            return True

        # some features are outside the geodata extent.  Warn the user
        elif totalIntAcres < totalMUacres and totalIntAcres > 1:
            prctOfCoverage = round((totalIntAcres / totalMUacres) * 100,1)

            if prctOfCoverage > 50:
                AddMsgAndPrint("\tWARNING: There is only " + str(prctOfCoverage) + " % coverage between your area of interest and Raster Layer",1)
                AddMsgAndPrint("\tWARNING: " + splitThousands(round((totalMUacres-totalIntAcres),1)) + " .ac will not be accounted for",1)
                return True
            elif prctOfCoverage < 1:
                AddMsgAndPrint("\tALL polygons are outside of your Raster Extent.  Cannot proceed with analysis",2)
                return False
            else:
                AddMsgAndPrint("\tThere is only " + str(prctOfCoverage) + " % coverage between your area of interest and Raster extent",2)
                return False

        # There is no overlap
        else:
            AddMsgAndPrint("\tALL polygons are ouside of your Raster Extent.  Cannot proceed with analysis",2)
            return False

        if arcpy.Exists(outIntersect):
            arcpy.Delete_management(outIntersect)

        if arcpy.Exists(outDomain):
            arcpy.Delete_management(outDomain)

        del outDomain,outGeom,outIntersect,numOfMulayerPolys,tempMULayer,numOfSelectedPolys

    except:
        errorMsg()
        return False

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