Exemplo n.º 1
0
# Created:     06/10/2017
#-------------------------------------------------------------------------------

import arcpy
from arcpy import env
env.workspace = r'D:/Geoprocessing/HW/HW7'
env.OverwriteOutput = True
inFile = "BaileysRegions.shp"
#Project file
projFile = "baileys_albers.shp"
if arcpy.Exists(projFile):
    arcpy.Delete_management(projFile)
    print 'File exists and is being deleted'
arcpy.Project_management(
    inFile, projFile,
    "PROJCS['NAD_1983_Texas_Centric_Mapping_System_Albers',GEOGCS['GCS_North_American_1983',DATUM['D_North_American_1983',SPHEROID['GRS_1980',6378137.0,298.257222101]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]],PROJECTION['Albers'],PARAMETER['False_Easting',1500000.0],PARAMETER['False_Northing',6000000.0],PARAMETER['Central_Meridian',-100.0],PARAMETER['Standard_Parallel_1',27.5],PARAMETER['Standard_Parallel_2',35.0],PARAMETER['Latitude_Of_Origin',18.0],UNIT['Meter',1.0]]",
    "",
    "GEOGCS['GCS_North_American_1983',DATUM['D_North_American_1983',SPHEROID['GRS_1980',6378137.0,298.257222101]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]]",
    "NO_PRESERVE_SHAPE", "", "NO_VERTICAL")
print 'File projected'

#Select by attribute
selectFile = "great_plains.shp"
if arcpy.Exists(selectFile):
    arcpy.Delete_management(selectFile)
    print 'File exists and is being deleted'
arcpy.Select_analysis(
    projFile, selectFile,
    "\"PROVINCE\" = 'Great Plains Steppe and Shrub Province'")
print 'Attributes selected'

#Buffer
    wbsr.create()
    webMercator = wbsr
    #webMercator = arcpy.SpatialReference(r"WGS 1984 Web Mercator (Auxiliary Sphere)")
    env.overwriteOutput = True
    scratch = env.scratchWorkspace

    #Project doesn't like in_memory featureclasses, copy to scratch
    copyInFeatures = os.path.join(scratch, "copyInFeatures_towerrangefanlos")
    arcpy.CopyFeatures_management(tower, copyInFeatures)
    deleteme.append(copyInFeatures)

    prjInFeature = os.path.join(scratch, "prjInFeature_towerrangefanlos")
    srInputPoints = arcpy.Describe(copyInFeatures).spatialReference
    if DEBUG == True:
        arcpy.AddMessage("Projecting input points to Web Mercator ...")
    arcpy.Project_management(copyInFeatures, prjInFeature, webMercator)
    deleteme.append(prjInFeature)
    tempFans = os.path.join(env.scratchWorkspace, "tempFans_towerrangefanlos")

    #########################################################################
    # Create Range Fans
    #########################################################################
    # put bearing into 0 - 360 range
    geoBearing = math.fmod(geoBearing, 360.0)
    if DEBUG == True: arcpy.AddMessage("geoBearing: " + str(geoBearing))
    arithmeticBearing = Geo2Arithmetic(
        geoBearing
    )  # need to convert from geographic angles (zero north clockwise) to arithmetic (zero east counterclockwise)
    if DEBUG == True:
        arcpy.AddMessage("arithmeticBearing: " + str(arithmeticBearing))
Exemplo n.º 3
0
#export
outpath = "C:\Users\dmehri\Documents\DATA\ArcGIS\Spatial_Join\output"
arcpy.FeatureClassToFeatureClass_conversion("InspectionList_points", outpath,
                                            "InspectionListPoints.shp")

#Project the points
#set input feature as savled shape file
input_features = "C:\Users\dmehri\Documents\DATA\ArcGIS\Spatial_Join\output\InspectionListPoints.shp"

#ouput data
output_feature_class = "C:\Users\dmehri\Documents\DATA\ArcGIS\Spatial_Join\output\InspectionListProjectedPoints.shp"
# create a spatial reference object for the output coordinate system
out_coordinate_system = arcpy.SpatialReference(
    'NAD 1983 (2011) StatePlane New York Long Isl FIPS 3104 (US Feet)')
#run the projected points tool
arcpy.Project_management(input_features, output_feature_class,
                         out_coordinate_system)

#Now the projected points are exported, delete layers not needed anymore
#arcpy.Delete_management("InspectionListProjectedPoints")
#arcpy.Delete_management("InspectionList_points")
#arcpy.Delete_management("InspectionList")
#arcpy.Delete_management("InspectionListPoints")

print "DONE WITH PROJECTED POINTS"
""" 
the below code creates a spatial join with community districts and
projected points shape files, then applies graduated colors to the new
spatial join layer
"""

print "Running Spatial join"
Exemplo n.º 4
0
                                        driver='ESRI Shapefile',
                                        schema=myschema) as output:
                            output.write({
                                'geometry':
                                geometry.mapping(concave_hull),
                                'properties': {
                                    'id': 107187
                                }
                            })
                        output.close
                        proj = arcpy.projection(3686)
                        arcpy.Define_Projection_management(tempShp, proj)
                        outShp = arcpy.CreateLayer(inWs + "\\" + dgnName +
                                                   "Outline.shp")
                        reProj = arcpy.projection(3857)
                        arcpy.Project_management(tempShp, outShp, reProj)
                        arcpy.Delete_management(tempShp)
                    #get the input layer
##    					inShp = inWs + "\\" + dgnName + "Outline.shp"
##    					driver = ogr.GetDriverByName('ESRI Shapefile')
##
##    					polyShp = driver.Open(outShp)
##    					polyLyr = polyShp.GetLayer()
##
##    					#create the output layer
##    					outShp2 = inWs + "\\" + dgnName + "Outline2.shp"
##    					outDataSet = driver.CreateDataSource(outShp2)
##    					outLayer = outDataSet.CreateLayer("basemap_4326", geom_type=ogr.wkbMultiPolygon)
##    					outLayerDefn = outLayer.GetLayerDefn()
##
##    					inCS = osr.SpatialReference()
Exemplo n.º 5
0
                kab = str('"') + line[7] + str('"')
                kec = str('"') + line[8] + str('"')
                pro = str('"') + line[6] + str('"')
                #print
                print shp
                print output
                #Change workspace
                arcpy.env.workspace = str(os.path.join(tools_folder, gdb, pmn))
                arcpy.env.overwriteOutput = True
                print arcpy.env.workspace
                # Process: Project (moving)
                print 'Moving Feature ' + output + ' to Database'

                #project
                arcpy.Project_management(
                    shp, output,
                    "GEOGCS['GCS_WGS_1984',DATUM['D_WGS_1984',SPHEROID['WGS_1984',6378137.0,298.257223563]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]]",
                    "", "", "NO_PRESERVE_SHAPE", "", "NO_VERTICAL")

                # Process: Add Field
                print 'Creating Fields for Feature ' + output
                # objID
                arcpy.AddField_management(output, "objID", "SHORT", "", "", "",
                                          "", "NULLABLE", "NON_REQUIRED", "")
                arcpy.CalculateField_management(output, "objID", "[OBJECTID]",
                                                "VB", "")
                # objType
                arcpy.AddField_management(output, "objType", "TEXT", "", "",
                                          "", "", "NULLABLE", "NON_REQUIRED",
                                          "")

                # objYear
Exemplo n.º 6
0
arcpy.env.overwriteOutput = True

lista = fnmatch.filter(os.listdir(path), "*.tif")

namesLista = [x[:3] for x in lista]
for x in range(len(namesLista)):
    raster = arcpy.Raster(os.path.join(path, lista[x]))
    spr = raster.spatialReference

    if spr.name == u'WGS_1984_UTM_Zone_17S':
        spn = arcpy.SpatialReference(32717)
    elif spr.name == u'WGS_1984_UTM_Zone_18S':
        spn = arcpy.SpatialReference(32718)
    elif spr.name == u'WGS_1984_UTM_Zone_19S':
        spn = arcpy.SpatialReference(32719)
    else:
        spn = arcpy.SpatialReference(4326)

    areaHoja = arcpy.MakeFeatureLayer_management(
        shp, "in_memory\ghp", "COD_100 = '{}'".format(namesLista[x]))
    areaHojaN = arcpy.Project_management(areaHoja,
                                         os.path.join(path, "temp.shp"), spn)

    pathRaster = '{}'.format(''.join([namesLista[x], ".tif"]))
    pathRaster2 = os.path.join(path, 'RASTER', pathRaster)

    dsc = arcpy.Describe(areaHojaN)
    Rectangle = dsc.Extent.__str__().replace('NaN', '')

    arcpy.Clip_management(raster, Rectangle, pathRaster2)
Exemplo n.º 7
0
    def execute(self, parameters, messages):
        """The source code of the tool."""

        # local variables and env
        arcpy.env.workspace = "E:/gina/poker/pip"
        adnr_lo_shp = "E:/gina/poker/shp/wip/land_ownership_data/adnr_gls_dls_merge_20170823_v1.shp"
        pfrr_popn_places = "E:/gina/poker/shp/wip/popn_places_data/pokerflat_popn_places_gcs_wgs84_to_akalbers_2.shp"
        pipTable = "E:/gina/poker/dbf/predicted_impact_xy.dbf"
        pip_point_shp = "E:/gina/poker/pip/pip_point.shp"
        pip_point_3338 = "E:/gina/poker/pip/pip_point_3338.shp"
        pip_buffer_shp = "E:/gina/poker/pip/pip_buffer.shp"
        pip_lo_in_buffer_shp = "E:/gina/poker/pip/pip_lo_in_buffer.shp"
        pip_lo_in_buf_sum_dbf = "E:/gina/poker/pip/pip_lo_in_buf_sum.dbf"
        pip_lo_in_buf_sum_csv = "E:/gina/poker/pip/pip_lo_in_buf_sum.csv"
        pip_popn_places_in_buffer_shp = "E:/gina/poker/pip/pip_popn_places_in_buffer.shp"
        x = parameters[0].valueAsText
        y = parameters[1].valueAsText
        r = parameters[2].valueAsText + " NauticalMiles"
        pipLayer = "pipLayer"
        srs = arcpy.SpatialReference("Alaska Albers Equal Area Conic")
        intersect_fc1 = [adnr_lo_shp, pip_buffer_shp]
        intersect_fc2 = [pfrr_popn_places, pip_buffer_shp]
        mxd = arcpy.mapping.MapDocument("current")
        dataframe = arcpy.mapping.ListDataFrames(mxd)[0]
        sourceLoSymbologyLayer = arcpy.mapping.Layer(
            "E:/gina/poker/lyr/lo2.lyr")
        sourcePipSymbologyLayer = arcpy.mapping.Layer(
            "E:/gina/poker/lyr/pip.lyr")

        # Process: Calculate Lon Field
        arcpy.CalculateField_management(pipTable, "Lon", x, "PYTHON", "")

        # Process: Calculate Lat Field
        arcpy.CalculateField_management(pipTable, "Lat", y, "PYTHON", "")

        # Process: Make XY Event Layer
        arcpy.MakeXYEventLayer_management(
            pipTable, "Lon", "Lat", pipLayer,
            "GEOGCS['GCS_WGS_1984',DATUM['D_WGS_1984',SPHEROID['WGS_1984',6378137.0,298.257223563]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]];-400 -400 1000000000;-100000 10000;-100000 10000;8.98315284119522E-09;0.001;0.001;IsHighPrecision",
            "")

        # Process: Copy Features
        arcpy.CopyFeatures_management(pipLayer, pip_point_shp, "", "0", "0",
                                      "0")

        # Process: Project pip point
        arcpy.Project_management(pip_point_shp, pip_point_3338, srs)

        # Process: Buffer pip point
        arcpy.Buffer_analysis(pip_point_3338, pip_buffer_shp, r, "FULL",
                              "ROUND", "NONE", "", "PLANAR")

        # Process: Intersect pip buffer with land ownership
        arcpy.Intersect_analysis(intersect_fc1, pip_lo_in_buffer_shp, "ALL",
                                 "", "INPUT")

        # Process: Intersect pip buffer with popn places
        arcpy.Intersect_analysis(intersect_fc2, pip_popn_places_in_buffer_shp,
                                 "ALL", "", "INPUT")

        # Process: Make feature layers and add to the map
        ## pip feature class list
        fclist = arcpy.ListFeatureClasses()

        ## pip layer
        arcpy.MakeFeatureLayer_management(pip_point_3338,
                                          "Predicted Impact Point")

        ## land ownership layer
        arcpy.MakeFeatureLayer_management(
            pip_lo_in_buffer_shp,
            "Land Ownership within 3sigma of Predicted Impact Point")

        ## populated places layer
        popn_places_records = int(
            arcpy.GetCount_management(pip_popn_places_in_buffer_shp).getOutput(
                0))
        if popn_places_records > 0:
            arcpy.MakeFeatureLayer_management(
                pip_popn_places_in_buffer_shp,
                "Populated Places within 3sigma of Predicted Impact Point")
            addPipPopnPlacesLayer = arcpy.mapping.Layer(
                "Populated Places within 3sigma of Predicted Impact Point")
            arcpy.mapping.AddLayer(dataframe, addPipPopnPlacesLayer)

        addPipPointLayer = arcpy.mapping.Layer("Predicted Impact Point")
        arcpy.mapping.AddLayer(dataframe, addPipPointLayer)

        add3sigmaLoLayer = arcpy.mapping.Layer(
            "Land Ownership within 3sigma of Predicted Impact Point")
        arcpy.mapping.AddLayer(dataframe, add3sigmaLoLayer)

        # Add and calc Acres field for intersected Land Ownership
        arcpy.AddField_management(pip_lo_in_buffer_shp, "Acres", "DOUBLE")
        arcpy.CalculateField_management(pip_lo_in_buffer_shp, "Acres",
                                        "!shape.area@acres!", "PYTHON_9.3", "")

        # Summarize intersected Land Ownership by Owner and total Acres
        arcpy.Statistics_analysis(pip_lo_in_buffer_shp, pip_lo_in_buf_sum_dbf,
                                  "Acres SUM", "OWNER")
        # arcpy.MakeTableView_management(pip_lo_in_buf_sum_dbf)
        add3sigmaLoSumTbl = arcpy.mapping.TableView(pip_lo_in_buf_sum_dbf)
        arcpy.mapping.AddTableView(dataframe, add3sigmaLoSumTbl)

        # Symbolize and Refresh
        lo_layer = arcpy.mapping.ListLayers(
            mxd, "*Land Ownership within 3sigma of Predicted Impact Point*",
            dataframe)[0]
        arcpy.mapping.UpdateLayer(dataframe, lo_layer, sourceLoSymbologyLayer,
                                  True)
        lo_layer.symbology.addAllValues()

        pip_layer = arcpy.mapping.ListLayers(mxd, "*Predicted Impact Point*",
                                             dataframe)[0]
        arcpy.mapping.UpdateLayer(dataframe, pip_layer,
                                  sourcePipSymbologyLayer, True)

        arcpy.RefreshTOC()
        arcpy.RefreshActiveView()

        return
Exemplo n.º 8
0
        for fC in fCList:  # For files in the feature classes list..
            desc = arcpy.Describe(
                fC)  # ..describe them for multiple purposes for later use
            spatialRef = desc.spatialReference  # Describe the spatial reference system of the files

            if spatialRef.Name == 'Unknown':  # If spatial reference system is unknown..
                continue  # ..go to Line 43
                print "\n" + fC, (
                    "has an 'Unknown' spatial reference\n"
                )  # Display list of names of feature classes with no spatial reference system

            else:
                definedfC = fC + '_UTM_1983'  # Name of output file
                prjFile = 'Coordinate Systems/Projected Coordinate Systems/UTM/NAD 1983/NAD 1983 UTM Zone 11N.prj'  # Default path to .prj file in ArcMap
                arcpy.Project_management(
                    fC, definedfC,
                    prjFile)  # Define projection function from ArcPy

        for fC in fCList:  # For files in the feature classes list..
            if spatialRef.Name == 'Unknown':  # ..if spatial reference system is unknown..
                print "\n" + fC, ("has an 'Unknown' spatial reference\n"
                                  )  # ..display those files
            else:
                Unknown = [
                    fC for fC in fCList
                    if arcpy.Describe(fC).spatialReference.Name == 'Unknown'
                ]  # List of files with unknown spatial reference
                Known = len(fCList) - len(
                    Unknown
                )  # Determine the number of files with known spatial reference system
Exemplo n.º 9
0
    def getAOIarea():
        sr = arcpy.Describe(
            aoiBasin
        ).SpatialReference  # Determine aoiBasin spatial reference system
        srname = sr.name
        srtype = sr.type
        srunitname = sr.linearUnitName  # Units
        arcpy.AddMessage("\nAOI basin spatial reference:  " + srname +
                         "\nUnit type: " + srunitname +
                         "\nSpatial reference type: " + srtype)

        aoiArea = 0.0
        rows = arcpy.SearchCursor(aoiBasin)
        for row in rows:
            feat = row.getValue("Shape")
            aoiArea += feat.area
        if srtype == 'Geographic':  # Must have a surface projection.  If one doesn't exist it projects a temporary file and uses that.
            arcpy.AddMessage(
                "\n***The basin shapefile's spatial reference 'Geographic' is not supported.  Projecting temporary shapefile for AOI.***"
            )
            arcpy.Project_management(
                aoiBasin, env.scratchGDB + "\\TempBasin", 102039
            )  #Projects AOI Basin (102039 = USA_Contiguous_Albers_Equal_Area_Conic_USGS_version)
            TempBasin = env.scratchGDB + "\\TempBasin"  # Path to temporary basin created in scratch geodatabase
            sr = arcpy.Describe(
                TempBasin
            ).SpatialReference  # Determine Spatial Reference of temporary basin
            aoiArea = 0.0
            rows = arcpy.SearchCursor(
                TempBasin)  # Assign area size in square meters
            for row in rows:
                feat = row.getValue("Shape")
                aoiArea += feat.area
            aoiArea = aoiArea * 0.000000386102  # Converts square meters to square miles
        elif srtype == 'Projected':  # If a projection exists, it re-projects a temporary file and uses that for data consistency.
            arcpy.AddMessage(
                "\n***The basin shapefile's spatial reference will be reprojected to USA_Contiguous_Albers_Equal_Area_Conic_USGS_version for data consistency.  Projecting temporary shapefile for AOI.***"
            )
            arcpy.Project_management(
                aoiBasin, env.scratchGDB + "\\TempBasin", 102039
            )  #Projects AOI Basin (102039 = USA_Contiguous_Albers_Equal_Area_Conic_USGS_version)
            TempBasin = env.scratchGDB + "\\TempBasin"  # Path to temporary basin created in scratch geodatabase
            sr = arcpy.Describe(
                TempBasin
            ).SpatialReference  # Determine Spatial Reference of temporary basin
            aoiArea = 0.0
            rows = arcpy.SearchCursor(
                TempBasin)  # Assign area size in square meters
            for row in rows:
                feat = row.getValue("Shape")
                aoiArea += feat.area
            aoiArea = aoiArea * 0.000000386102  # Converts square meters to square miles

        aoiArea = round(aoiArea, 3)
        arcpy.AddMessage("\nArea of interest: " + str(aoiArea) +
                         " square miles.")

        if arcpy.GetParameter(5) == False:
            aoiArea = arcpy.GetParameter(6)  # Enable a constant area size
        aoiArea = round(aoiArea, 1)
        arcpy.AddMessage("\n***Area used for PMP analysis: " + str(aoiArea) +
                         " sqmi***")
        return aoiArea
Exemplo n.º 10
0
# Process: Get the InputDataset File Name
InputFileName = os.path.basename(InputDataset).rstrip(
    os.path.splitext(InputDataset)[1])
OutputProject = DataPath + "\\Scratch.gdb\\" + InputFileName + "_Project"
OutputShapefile = DataPath + os.path.sep + "Shapefiles" + os.path.sep
OutputZipFiles = DataPath + os.path.sep + "ZipFiles" + os.path.sep
OutputFCLocation = DataPath + "\\NDUpdate20140930.gdb\\Provider_Coverage\\"
OutTable = DataPath + "\\NDUpdate20140930.gdb\\" + "tbl_CheckGeo_" + InputFileName

# Create a copy of the input FeatureClass
arcpy.FeatureClassToFeatureClass_conversion(InputDataset, OutputFCLocation,
                                            InputFileName, "")

# Process: Project the Input Dataset to WGS84
arcpy.Project_management(InputDataset, OutputProject, outCS,
                         "WGS_1984_(ITRF00)_To_NAD_1983")

#Check Geometry
arcpy.CheckGeometry_management(OutputProject, OutTable)

#Repair Geometry
arcpy.RepairGeometry_management(OutputProject)

values = [row[0] for row in arcpy.da.SearchCursor(OutputProject, (fieldName))]
uniqueValues = set(values)
uniqueValues2 = list(uniqueValues)

x = 0
for value in uniqueValues2:

    #Create the query
Exemplo n.º 11
0
            str_bef = "PROJCS['Equirectangular_Moon',GEOGCS['GCS_Moon',DATUM['D_Moon',SPHEROID['Moon_localRadius',1737400.0,0.0]],PRIMEM['Reference_Meridian',0.0],UNIT['Degree',0.0174532925199433]],PROJECTION['Equidistant_Cylindrical'],PARAMETER['false_easting',0.0],PARAMETER['false_northing',0.0],"
            str_cent_med = "PARAMETER['central_meridian'," + str(
                cent_med) + "],"
            str_parall = "PARAMETER['standard_parallel_1'," + str(
                std_parall) + "],"
            str_after = "UNIT['Meter',1.0]]"

            # the whole string is
            spatialReference_new = str_bef + str_cent_med + str_parall + str_after

            # projection
            arcpy.Project_management(in_dataset="CENTER_TMP",
                                     out_dataset="CENTER_PROJ",
                                     out_coor_system=spatialReference_new,
                                     transform_method="",
                                     in_coor_system=spatialReference,
                                     preserve_shape="NO_PRESERVE_SHAPE",
                                     max_deviation="",
                                     vertical="NO_VERTICAL")

            # buffer creation
            arcpy.Buffer_analysis("CENTER_PROJ", out, bufferField, sideType,
                                  endType, dissolveType)

            # run feature to envelope tool
            arcpy.FeatureEnvelopeToPolygon_management(
                pathdab + "miniarea_TMP", pathdab + "miniarea_square",
                "SINGLEPART")

            #reproject in normal
            arcpy.Project_management(
Exemplo n.º 12
0
		arcpy.MakeFeatureLayer_management (_selected_watersheds,  layerName)
			
		# Join the feature layer to a table
		arcpy.AddJoin_management(in_layer_or_view=layerName, in_field=infield, join_table=_zonalStatsMean,
								 join_field=joinfield, join_type="KEEP_COMMON" )
			

		# Copy the layer to a new permanent feature class
		arcpy.CopyFeatures_management(layerName, _watershed_with_mean)


		# Local variables:
		watershed_with_mean_Project = os.path.join(output_loc,"X_watershed_with_mean_Project")

		# Process: Project
		arcpy.Project_management(_watershed_with_mean, watershed_with_mean_Project, "PROJCS['WGS_1984_UTM_Zone_43N',GEOGCS['GCS_WGS_1984',DATUM['D_WGS_1984',SPHEROID['WGS_1984',6378137.0,298.257223563]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]],PROJECTION['Transverse_Mercator'],PARAMETER['False_Easting',500000.0],PARAMETER['False_Northing',0.0],PARAMETER['Central_Meridian',75.0],PARAMETER['Scale_Factor',0.9996],PARAMETER['Latitude_Of_Origin',0.0],UNIT['Meter',1.0]]", "", "GEOGCS['GCS_WGS_1984',DATUM['D_WGS_1984',SPHEROID['WGS_1984',6378137.0,298.257223563]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]]", "NO_PRESERVE_SHAPE", "", "NO_VERTICAL")



# Step 5

		# select intersecting watershed to contributing area
		#  finding contributing area (actual)
		a_area = []
		with arcpy.da.SearchCursor(watershed_with_mean_Project, ['Shape_Area']) as cursor:
			for row in cursor:
				a_area.append(row[0])
			print('area is: {}'.format(sum(a_area)))
		list_excel.append(sum(a_area))

Exemplo n.º 13
0
    arcpy.CreateFolder_management(working_directory, "outputFiles")

# Name the map and dataframe for removing layers
# ----------------------------------------------
mxd = arcpy.mapping.MapDocument("CURRENT")
df = arcpy.mapping.ListDataFrames(mxd)[0]

# ===================
# Reproject Flowlines
# ===================
# Define the projection to use (that of the wetlands)
projection_definition = wetlandsFolder + "/" + states[
    0] + "_wetlands.gdb/" + states[0] + "_Wetlands"

# Reproject the flowlines
arcpy.Project_management(flowlinesFile, working_db + "/flowlines_prj",
                         projection_definition)

# ===================
# Create Range Raster
# ===================
# Generates a blank raster of the entire range. This raster will serve as the template to which the state rasters will be mosaicked.

spatial_ref = arcpy.Describe(wetlandsFolder + "/" + states[1] +
                             "_wetlands.gdb/" + states[1] +
                             "_Wetlands").spatialReference

# Project the states file to match the wetlands
arcpy.Project_management(statesFile, working_db + "/statesFilePrj",
                         spatial_ref)

arcpy.Sort_management(working_db + "/statesFilePrj",
Exemplo n.º 14
0
            raster_field="Value",
            simplify="NO_SIMPLIFY")
        print "    Dissolving features into contiguous forest features"
        arcpy.Dissolve_management(
            legal_loss_year_PRODES_noFire_neighbor_shp,
            legal_loss_year_PRODES_noFire_neighbor_shp_dissolve,
            dissolve_field=["gridcode"],
            multi_part="MULTI_PART")
        print "    End time is", str(datetime.datetime.now())

        print "  Reprojecting {} loss area to World Eckert IV".format(year)
        print "    Start time is", str(datetime.datetime.now())
        out_coordinate_system = "PROJCS['World_Eckert_IV',GEOGCS['GCS_WGS_1984',DATUM['D_WGS_1984',SPHEROID['WGS_1984',6378137.0,298.257223563]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]],PROJECTION['Eckert_IV'],PARAMETER['False_Easting',0.0],PARAMETER['False_Northing',0.0],PARAMETER['Central_Meridian',0.0],UNIT['Meter',1.0]]"
        arcpy.Project_management(
            legal_loss_year_PRODES_noFire_neighbor_shp_dissolve,
            legal_loss_year_PRODES_noFire_neighbor_shp_dissolve_reproj,
            out_coor_system=out_coordinate_system,
            transform_method="")
        print "    End time is", str(datetime.datetime.now())

        print "  Calculating feature areas"
        print "    Start time is", str(datetime.datetime.now())
        arcpy.CalculateAreas_stats(
            legal_loss_year_PRODES_noFire_neighbor_shp_dissolve_reproj,
            legal_loss_year_PRODES_noFire_neighbor_shp_dissolve_reproj_areas)
        print "    End time is", str(datetime.datetime.now())

        # Keeps only the features that are larger than 6.25 ha (Brazil exclusion criteria 4)
        print "  Selecting features larger than 6.25 ha"
        print "    Start time is", str(datetime.datetime.now())
        where = "F_AREA > 62500"
Exemplo n.º 15
0
NED19smooth = os.path.join(rootdir, 'results/ned19_smooth')
NED13smooth = os.path.join(rootdir, 'results/ned13_smooth')

Seattleroads = os.path.join(
    rootdir, 'data/CitySeattle_20180601/Seattle_Streets/Seattle_Streets.shp')
UTM10 = arcpy.SpatialReference(26910)
sroadsras = os.path.join(PSgdb, 'Seattle_roadras')
srangetab19 = os.path.join(PSgdb, 'Seattle_elv19range')
srangetab13 = os.path.join(PSgdb, 'Seattle_elv13range')
Seattleroadsproj = os.path.join(PSgdb, 'Seattle_roadproj')

#########################################################################################################################
#ANALYSIS

#Compare to Seattle roads slope values. Apply same method to Seattle road dataset
roadproj = arcpy.Project_management(Seattleroads, Seattleroadsproj, UTM10)

#Densify roads
arcpy.CopyFeatures_management(Seattleroadsproj, Seattleroadsproj + 'dens10m')
arcpy.Densify_edit(Seattleroadsproj + 'dens10m',
                   densification_method='DISTANCE',
                   distance='10',
                   max_deviation='1.5')
#Split at vertices
arcpy.SplitLine_management(Seattleroadsproj + 'dens10m',
                           Seattleroadsproj + 'split10')

#Compute statistics
arcpy.PolylineToRaster_conversion(Seattleroadsproj + 'split10',
                                  'OBJECTID_1',
                                  sroadsras,
def do_analysis(inFeatureClass, outFeatureClass, lengthNum, lengthField, blockWidthValue, referenceFeatureClass):
    """This function will create blocks in one location based on the incoming reference centroid for the
    purpose of being used for data driven design applications in CityEngine."""
    # try:
    # Delete Existing Output
    arcpy.env.overwriteOutput = True
    if arcpy.Exists(outFeatureClass):
        arc_print("Deleting existing output feature.", True)
        arcpy.Delete_management(outFeatureClass)
    workspace = os.path.dirname(outFeatureClass)
    tempOutName = arcpy.ValidateTableName("TempBlockFC_1", workspace)
    tempOutFeature = os.path.join(workspace, tempOutName)
    # Add New Fields
    arc_print("Adding new fields for old object IDs and geometry name.", True)
    OldObjectIDName = "UniqueFeatID"
    GeometryName = "CEStreetName"
    AddNewField(inFeatureClass, OldObjectIDName, "LONG")
    AddNewField(inFeatureClass, GeometryName, "TEXT")
    # Create feature class to get outputFC
    arc_print("Making a new output feature class using the input as a template", True)
    OutPut = arcpy.CreateFeatureclass_management(workspace, tempOutName, "POLYLINE", template=inFeatureClass,
                                                 spatial_reference=inFeatureClass)

    arc_print("Gathering feature information.", True)
    # Get feature description and spatial reference information for tool use
    desc = arcpy.Describe(inFeatureClass)
    SpatialRef = desc.spatialReference
    shpType = desc.shapeType
    srName = SpatialRef.name
    arc_print(
            "The shape type is {0}, and the current spatial reference is: {1}".format(str(shpType), str(srName)),
            True)
    # Get mean center of feature class (for pointGeo)
    if arcpy.Exists(referenceFeatureClass) and referenceFeatureClass != "#":
        arc_print("Calculating the mean center of the reference feature class.", True)
        meanCenter = arcpy.MeanCenter_stats(referenceFeatureClass)
    else:
        arc_print("Calculating the mean center of the copied feature.", True)
        meanCenter = arcpy.MeanCenter_stats(inFeatureClass)

    fieldNames = getFields(inFeatureClass)
    arc_print("Getting point geometry from copied center.", True)
    pointGeo = copy.deepcopy(arcpy.da.SearchCursor(meanCenter, ["SHAPE@"]).next()[0])  # Only one center, so one recor

    # Check if the optional Street Length/ Lot Area field is used.
    idsAndFieldSearchNames = ["SHAPE@"] + fieldNames
    arc_print("The search cursor's fields and tags are:{0}".format(str(idsAndFieldSearchNames)), True)
    records = []
    with arcpy.da.SearchCursor(inFeatureClass, idsAndFieldSearchNames) as cursorSearch:
        arc_print("Loading input feature classes rows into a new record list.", True)
        for search_row in cursorSearch:
            records.append(search_row)
    arc_print("Inserting new rows and geometries to new feature class.", True)
    count = 0
    with arcpy.da.InsertCursor(tempOutFeature, idsAndFieldSearchNames) as cursorInsert:
        if desc.shapeType == "Polyline":
            for row in records:
                # Use two try statements, one time to try to catch the error
                count += 1
                try:
                    arc_print("A creating geometry dictionary for feature iteration: {0}.".format(str(count)))
                    geoDict = CreateMainStreetBlockCEGeometry(pointGeo, lineLength(row, lengthField, lengthNum,
                                                                                   idsAndFieldSearchNames),
                                                              blockWidthValue)
                    # print geoDict
                    for key in geoDict.keys():
                        try:
                            rowList = copyAlteredRow(row, idsAndFieldSearchNames,
                                                     {"SHAPE@": geoDict[key], OldObjectIDName: count,
                                                      GeometryName: str(key)})
                            cursorInsert.insertRow(rowList)
                        except:
                            arcpy.AddWarning("Passed line at iteration {0}.".format(str(count)))
                            pass
                except:
                    arcpy.GetMessage(2)
                    arc_print("Failed on iteration {0}.".format(str(count)), True)
                    pass
        else:
            arc_print("Input geometry is not a polyline. Check arguments.", True)
            arcpy.AddError("Input geometry is not a polyline. Check arguments.")

    arc_print("Projecting data into Web Mercator Auxiliary Sphere (a CityEngine compatible projection).", True)
    webMercatorAux = arcpy.SpatialReference(3857)
    arcpy.Project_management(OutPut, outFeatureClass, webMercatorAux)
    arc_print("Cleaning up intermediates.", True)
    arcpy.Delete_management(meanCenter)
    arcpy.Delete_management(OutPut)
    arcpy.DeleteField_management(inFeatureClass, OldObjectIDName)
    arcpy.DeleteField_management(inFeatureClass, GeometryName)
    del SpatialRef, desc, cursorSearch, webMercatorAux, cursorInsert
Exemplo n.º 17
0
    #______________________________________________________________________________#
    #
    # If Name is used for ParcelPIN make adjustments
    #______________________________________________________________________________#

    if ParcelPIN is "Name":
        arcpy.AlterField_management(PhotoFeatureClass, ParcelPIN, "Image_Name")
    else:
        pass

    SR = arcpy.Describe(Parcels)
    SRHelper = SR.spatialReference
    PhotoFeatureClass2 = """{}\\PointAttachments""".format(Geodatabase)

    arcpy.Project_management(PhotoFeatureClass, PhotoFeatureClass2, SRHelper)
    arcpy.DeleteIdentical_management(PhotoFeatureClass2, "Shape")
    arcpy.Delete_management(PhotoFeatureClass)

    EntGDB = arcpy.Describe(Geodatabase)
    EntGDB.workspaceType

    if EntGDB is 'RemoteDatabase':
        arcpy.RegisterAsVersioned_management(PhotoFeatureClass2)
    else:
        pass

    arcpy.AddMessage("Step 2:  Converting Photos to points")

    # Load up the parcel dataset for the property association (and make a copy)
                originCoordinate = str(desc.extent.lowerLeft)
                yAxisCoordinate = str(
                    desc.extent.XMin) + " " + str(desc.extent.YMax + 10)
                oppositeCoorner = str(desc.extent.upperRight)


                fishnet =arcpy.CreateFishnet_management(fishnet_out,originCoordinate,yAxisCoordinate,cellSizeWidth,\
                                                        cellSizeHeight,numRows, numColumns, oppositeCoorner, labels,templateExtent, geometryType)

                #print r"fishnet created"

            ###
            out_coordinate_system = arcpy.Describe(urban_edge).spatialReference
            project_out = r"%s\\fGDB.gdb\\%s_fishnet_T%s_%s_project" % (
                output, city, t, year)
            arcpy.Project_management(fishnet_out_gdb, project_out,
                                     out_coordinate_system)
            arcpy.AddField_management(project_out, "AreaH", "DOUBLE", "", "",
                                      "", "", "NULLABLE", "NON_REQUIRED", "")
            arcpy.CalculateField_management(project_out, "AreaH",
                                            "!Shape.Area@hectares!", "PYTHON",
                                            "")
            ###
            #with arcpy.da.SearchCursor(project_out,'AreaH') as cursor:
            #   print max(cursor)

            max_total = max(
                (r[0] for r in arcpy.da.SearchCursor(project_out, ['AreaH'])))
            min_total = min(
                (r[0] for r in arcpy.da.SearchCursor(project_out, ['AreaH'])))
            factor = (max_total + min_total) / 2
            #print "summed total %s " % factor
	print outRotation
	if arcpy.Exists(outRotation):
		continue
	arcpy.SelectLayerByAttribute_management('fishnet', 'NEW_SELECTION', '"FID" = ' + str(FID))

	rid = str(random.randint(10000,99999))
	watershedCdlPrj = tempGdb + '/watershedCdlPrj_' + rid
	samplePts = tempGdb + '/samplePts_' + rid
	outRotation1 = tempGdb + '/outRotation1_' + rid
	outHigh1 = tempGdb + '/outHigh1_' + rid
	outLow1 = tempGdb + '/outLow1_' + rid
	cdlUrl = r'http://nassgeodata.gmu.edu:8080/axis2/services/CDLService/GetCDLFile?'

	arcpy.AddMessage("Projecting Area Of Interest to Cropland Data Layer projection...")
	print watershedCdlPrj
	arcpy.Project_management('fishnet', watershedCdlPrj, sr)

	ext = arcpy.Describe(watershedCdlPrj).extent

	if downloadBool == 'true':
		ping = Popen(['ping', '-n', '1', 'nassgeodata.gmu.edu'], startupinfo=startupinfo)
		ping.wait()
		if ping == 1:
			arcpy.AddError('The CropScape server is down. Please try again later, or download local Cropland Data Layers at http://www.nass.usda.gov/research/Cropland/Release/index.htm')
		arcpy.AddMessage("Downloading Cropland Data Layers...")
		years = range(int(yrStart), int(yrEnd) + 1)
		cdlTiffs = []
		for year in years:
			year = str(year)
			clipUrl = cdlUrl\
				+ r'year='\
Exemplo n.º 20
0
def make_identical_tif_extents(tif_list, temp_dir="tmp"):
    if os.path.exists(temp_dir):
        shutil.rmtree(temp_dir)
    os.mkdir(temp_dir)
    start_time = time.time() 
    print("Setting extents to be identical on {} GeoTIFFS...".format(len(tif_list)))
    # Temporary variables 
    output_tif_list = [] 
    tif_list_fixed_extents = []
    tif_properties = {}
    cell_extentX = []
    cell_extentY = []
    coords = set()
    coords_str = set()
    coords_str_l = []
    coords_l = []
    all_top = []
    all_bottom = []
    all_left = []
    all_right = []
    outlines_unchanged = []
    arcpy.env.overwriteOutput = True 
    main_coord_s = arcpy.Describe(tif_list[0]).spatialReference
    
    # Load tif properties that we care about into dictionary 
    for a_tif in tif_list:                                    
        coord, csX, csY = (arcpy.Describe(a_tif).spatialReference,
                           arcpy.GetRasterProperties_management(a_tif, "CELLSIZEX"),
                           arcpy.GetRasterProperties_management(a_tif, "CELLSIZEY"))

        cell_extentX.append(float(str(csX)))
        cell_extentY.append(float(str(csY)))
        coords.add(coord)
        coords_str.add(coord.name)
        coords_str_l.append(coord.name)
        coords_l.append(coord)
        tif_properties[a_tif] = [coord.name]
    print("Step 1/4: Setting projections to be identical....")
    # Reproject rasters to one projection
    j = 0
    for a_tif in tif_properties.keys():
        desc = arcpy.Describe(a_tif).baseName
        if not os.path.isfile(os.path.join(temp_dir, desc + "_reproject.tif")):
            arcpy.ProjectRaster_management(a_tif, os.path.join(temp_dir, desc + "_reproject.tif"), main_coord_s)
        tif_properties[os.path.join(temp_dir, desc + "_reproject.tif")] = main_coord_s
                                                                           
        del tif_properties[a_tif]
        
    print("Step 2/4: Setting cell sizes to be identical....")
    
    # Set cell sizes to be identical if necessary    
    if len(set(cell_extentX)) > 1 or len(set(cell_extentY)) > 1:
        x_freq = max(set(cell_extentX), key=cell_extentX.count)
        y_freq = max(set(cell_extentY), key=cell_extentY.count)
        tif_list = tif_properties.keys()
        for a_tif in tif_list: 
            desc = arcpy.Describe(a_tif).baseName
            if float(str(arcpy.GetRasterProperties_management(a_tif, "CELLSIZEX"))) != x_freq or float(str(arcpy.GetRasterProperties_management(a_tif, "CELLSIZEY"))) != y_freq:
                if not os.path.isfile(os.path.join(temp_dir, desc + "_resample.tif")):
                    arcpy.Resample_management(a_tif,os.path.join(temp_dir, desc + "_resample.tif"), x_freq)
                tif_properties[os.path.join(temp_dir, desc + "_resample.tif")] = main_coord_s
                try:
                    del tif_properties[a_tif]
                except:
                    pass
    # Generate polygon extent shape for each tif
    print("Step 3/4: Generating minimum bounding polygon....")
    for a_tif in tif_properties.keys():
        desc = arcpy.Describe(a_tif).baseName
        arcpy.RasterDomain_3d(a_tif, os.path.join(temp_dir, desc + "_Outline_notproj.shp"), "POLYGON")
        arcpy.Project_management(os.path.join(temp_dir, desc + "_Outline_notproj.shp"),os.path.join(temp_dir, desc + "_Outline.shp"), main_coord_s)
        outlines_unchanged.append(os.path.join(temp_dir, desc + "_Outline.shp"))
    for x in range(0, len(outlines_unchanged)):
        this_outline = outlines_unchanged[x]
        if x == 0:
            outline_to_clip_to = outlines_unchanged[x + 1]
            outline_to_save_to = os.path.join(temp_dir, "final_cutout_tmp.shp")
            arcpy.Clip_analysis(this_outline, outline_to_clip_to, outline_to_save_to)
            arcpy.CopyFeatures_management(outline_to_save_to, os.path.join(temp_dir, "final_cutout.shp"))
        else:
            outline_to_clip_to = os.path.join(temp_dir, "final_cutout.shp")
            outline_to_save_to = os.path.join(temp_dir, "final_cutout_tmp.shp")
            arcpy.Clip_analysis(this_outline, outline_to_clip_to, outline_to_save_to)
            arcpy.CopyFeatures_management(outline_to_save_to, outline_to_clip_to)
    desc = arcpy.Describe(os.path.join(temp_dir, "final_cutout.shp"))
    bounding = "{} {} {} {}".format(desc.extent.XMin, desc.extent.YMin, desc.extent.XMax, desc.extent.YMax)
    print("Step 4/4: Clipping rasters to minimum bounding polygon....")
    for a_tif in tif_properties.keys():
        desc = arcpy.Describe(a_tif).baseName
        ## Reproject the shapefile to be the same projection as the input raster 
        coord_system = arcpy.Describe(a_tif).spatialReference 
        arcpy.Project_management(os.path.join(temp_dir, "final_cutout.shp"), os.path.join(temp_dir, "final_cutout_proj.shp"), main_coord_s)
        if not os.path.isfile(os.path.join(temp_dir, desc + "_clip.tif")):
            outExtract = arcpy.sa.ExtractByMask(a_tif, os.path.join(temp_dir, "final_cutout_proj.shp"))
            outExtract.save(os.path.join(temp_dir, desc + "_clip.tif"))
        tif_list_fixed_extents.append(os.path.join(temp_dir, desc + "_clip.tif"))
    end_time = time.time()
    t = gt.readable_time(start_time, end_time) 
    output_tif_list = tif_list_fixed_extents
    print("{} GeoTIFFs processed to have identical extents in {} days, {}:{}:{}".format(len(tif_list), t['dd'], t["hh"], t["mm"], t['ss']))
    
    return output_tif_list
Exemplo n.º 21
0
            data = json.load(f)
        return data

    d = read_config(coffee_cfg)

    print(d['data']['out_cs'])

    proj_filename = 'F:/GIS/Pratt/Ind. Study - Arc/CIAT Data/Coffee Points/AEA Projected/' + s + '_proj'
    out_cs = d['data']['out_cs']
    transform = ''
    in_cs = d['data']['in_cs']
    shp_preserve = 'NO_PRESERVE_SHAPE'
    max_dev = ''
    vertical = 'NO_VERTICAL'

    arcpy.Project_management(
        out_layer,
        proj_filename,
        out_cs,
        transform,
        in_cs,
        shp_preserve,
        max_dev,
        vertical,
    )

    arcpy.CopyFeatures_management(out_layer, saved_layer)

    # Save layer to file
    arcpy.SaveToLayerFile_management(out_layer, saved_layer)
Exemplo n.º 22
0
    st = st_tuple[c]

    urban_area_tracts = "urban_area_tracts_" + str(c) + ".shp"
    urban_area_join = "urban_area_lehd_join_" + str(c) + ".shp"
    urban_area_tracts_prj = "urban_area_tracts_prj.shp"
    uat_emp_hspt = "uat_emp_hspt_" + str(c) + ".shp"

    print "(" + str(c) + ") " + ua
    print "- Project"
    # Process: Project
    #arcpy.Project_management(urban_area_tracts_0, urban_area_tracts_prj_0, "PROJCS['NAD_1983_UTM_Zone_18N',GEOGCS['GCS_North_American_1983',DATUM['D_North_American_1983',SPHEROID['GRS_1980',6378137.0,298.257222101]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]],PROJECTION['Transverse_Mercator'],PARAMETER['False_Easting',500000.0],PARAMETER['False_Northing',0.0],PARAMETER['Central_Meridian',-75.0],PARAMETER['Scale_Factor',0.9996],PARAMETER['Latitude_Of_Origin',0.0],UNIT['Meter',1.0]]", "", "GEOGCS['GCS_North_American_1983',DATUM['D_North_American_1983',SPHEROID['GRS_1980',6378137.0,298.257222101]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]]")

    utm_zone = 'NAD 1983 UTM Zone ' + long_dict[ua] + 'N'
    print "- " + utm_zone
    outCS = arcpy.SpatialReference(utm_zone)
    arcpy.Project_management(urban_area_tracts, urban_area_tracts_prj, outCS)

    print "- Add Area Field"
    # Process: Add Field
    arcpy.AddField_management(urban_area_tracts_prj, "AREA", "DOUBLE", "", "",
                              "", "", "NULLABLE", "NON_REQUIRED", "")

    print "- Compute Area"
    # Process: Calculate Field
    arcpy.CalculateField_management(urban_area_tracts_prj, "AREA",
                                    "!SHAPE.AREA@SQUAREMILES!", "PYTHON_9.3")

    print "- Join to LEHD"
    # Process: Feature Layer
    arcpy.MakeFeatureLayer_management(urban_area_tracts_prj, layerName)
    # Process: Add Join
Exemplo n.º 23
0
fc_pl = os.path.join(folder_shpfile, shp_pl)
tb_pdnm = os.path.join(folder_shpfile, dbf_pdnm)
tb_plnm = os.path.join(folder_shpfile, dbf_plnm)

# create temp fgdb for data preparing

arcpy.env.workspace = os.path.join(folder_shpfile, fgdb_tmp)

if not arcpy.Exists(arcpy.env.workspace):
    arcpy.CreateFileGDB_management(folder_shpfile, fgdb_tmp)

# project to NAD 1983 HARN StatePlane Washington South FIPS 4602 (US Feet)
msg = '%s Project source shapefile %s to fgdb %s with datum transformation WGS_1984_(ITRF00)_To_NAD_1983_HARN ...' % (
    datetime.datetime.now(), fc_pd, arcpy.env.workspace)
print(msg)
arcpy.Project_management(fc_pd, 'pd', arcpy.SpatialReference(2927),
                         'WGS_1984_(ITRF00)_To_NAD_1983_HARN')
msg = '%s Project source shapefile %s to fgdb %s with datum transformation WGS_1984_(ITRF00)_To_NAD_1983_HARN ...' % (
    datetime.datetime.now(), fc_pl, arcpy.env.workspace)
print(msg)
arcpy.Project_management(fc_pl, 'pl', arcpy.SpatialReference(2927),
                         'WGS_1984_(ITRF00)_To_NAD_1983_HARN')

# add/calculate fields for 'ReleaseVersion', 'FeatureType', 'AreaSqMi', 'GDLPublishDate'
msg = '%s calculate pd ReleaseVersion, FeatureType, AreaSqMi, GDLPublishDate ...' % datetime.datetime.now(
)
print(msg)
arcpy.CalculateField_management('pd', 'ReleaseVersion', "'" + version + "'")
arcpy.CalculateField_management('pd', 'FeatureType', "'Postal Code'")
date_now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
arcpy.CalculateField_management('pd', 'GDLPublishDate', "'" + date_now + "'")
arcpy.CalculateField_management('pd', 'AreaSqMi', "!SHAPE_Area! / 27880000")
Exemplo n.º 24
0
print "Step 1 completed at", datetime.datetime.now().strftime("%A, %B %d %Y %I:%M:%S%p")

## ---------------------------------------------------------------------------
## 2. Project the polygons
## Description: Project the land-use dataset for the Mexico RGB to North America Albers Equal Area Conic

print "\nStep 2 Project the polygon starts at", datetime.datetime.now().strftime("%A, %B %d %Y %I:%M:%S%p")

outCS = arcpy.SpatialReference("North America Albers Equal Area Conic")

for fc in fcList:
    root = os.path.splitext(fc)[0]
    name = os.path.split(root)[1]
    projFile = os.path.join(out_gdb, name)
    arcpy.Project_management(fc, projFile, outCS)
    projList.append(projFile)
    print "Projection" , fc, "completed at" , datetime.datetime.now().strftime("%I:%M:%S%p")

print "Step 2 Project completed at", datetime.datetime.now().strftime("%I:%M:%S%p")


## ---------------------------------------------------------------------------
## 3. Clip
## Description: Clip the MX INEGI dataset for the study area.

print "\nStep 3 starts at", datetime.datetime.now().strftime("%A, %B %d %Y %I:%M:%S%p")

# Create the clip_features
folderShapefiles = "C:\\GIS_RGB\\Geodatabase\\rgb_bound\\"
listfc = ["RGB_Ses_na_albers.shp"]
Exemplo n.º 25
0
         
         for f in allbutpos:
             fromShp = allshp[f]
             
             
             # reproject data if necessary
             coordFrom = arcpy.Describe(fromShp).spatialReference
             coordFrom_str = coordFrom.exportToString()
             
             fromShpProj = os.path.splitext(fromShp)[0] + "_proj.shp"
             
             if (coordFrom_str[0:40] == coordTo_str[0:40]) == False:
                 
                 if (os.path.isfile(fromShpProj)):
                     arcpy.Delete_management(fromShpProj)
                 arcpy.Project_management(fromShp, fromShpProj, coordTo)
                 fromShp = fromShpProj
 
                 
             # change geometry if necessary
             interm = os.path.splitext(fromShp)[0] + "_interm.shp"
             if fromGeometries[f] != fromGeometries[pos]:
                 
                 if (os.path.isfile(interm)):
                     arcpy.Delete_management(interm)
                 
                 if fromGeometries[pos] == "Point":
                     
                     # check if feature midpoints or vertices should be converted to points    
                     if userTab[row][0] in verTab:
                         arcpy.FeatureVerticesToPoints_management(fromShp, interm, "ALL")
            dem_clipped,
            aoi,
            nodata_value="-3.402823e+38",
            clipping_geometry="NONE",
            maintain_clipping_extent="NO_MAINTAIN_EXTENT"
        )
    else:
        # set the dem_clipped to original dem in the case it doesn't exist
        dem_clipped = dem

    # reproject the datasets to something with common units - dem is in meters,
    # so use utm zone 19
    utmz19 = ea.sr.get_sr_nad83_utm_z19()
        
    nhd_flowline_p = str(here('./results/nhd_p.shp', warn=False))
    arcpy.Project_management(nhd_flowline, nhd_flowline_p, utmz19)

    # convert nhd flowline to raster with same cellsize as dem
    nhd_flowline_r = str(here('./results/nhd_f_raster.tif', warn=False))
    
    arcpy.PolylineToRaster_conversion(
        nhd_flowline_p,
        "Enabled",
        nhd_flowline_r,
        "MAXIMUM_LENGTH",
        "NONE")
    
    # reclass to 0 / height
    nhd_flowline_rc = str(here('./results/nhd_f_rasterrc.tif', warn=False))
    
    stream_burn_height = 5
Exemplo n.º 27
0
lstFCs = arcpy.ListFeatureClasses("*")
for fc in lstFCs:
    #fcList.append(os.path.join(folder + "\\" + fc))
    print fc
    dsc = arcpy.Describe(fc)
    if dsc.spatialReference.Name == "Unknown":
        print('skipped this fc due to undefined coordinate system: ' + infc)
    else:
        print dsc.spatialReference.Name
        print dsc.spatialReference.Name.find("1983")
        # Determine the new output feature class path and name
        newname = fc.strip('.shp')
        print newname
        outfc = os.path.join(outWorkspace, newname)

        # Set output coordinate system
        prjFile = "C:\Program Files (x86)\ArcGIS\Desktop10.0\Coordinate Systems\WGS 1984 Web Mercator (Auxiliary Sphere).prj"
        outCS = arcpy.SpatialReference(prjFile)
        print outfc
        if dsc.spatialReference.Name.find("1983") > 1:
            print "This has an 1983 Datum"
            arcpy.Project_management(fc, outfc, outCS,
                                     "NAD_1983_To_WGS_1984_1")

        if dsc.spatialReference.Name.find("1984") > 1:
            print "This has an 1984 Datum"
            arcpy.Project_management(fc, outfc, outCS)

        print
        print
        print
Exemplo n.º 28
0
                                  'LATITUDE', 'boxlayer', xycs)
# convert event layer to preliminary line feature class with PointsToLine_management
arcpy.PointsToLine_management('boxlayer', 'xxMapOutline')
# densify MapOutline
arcpy.Densify_edit('xxMapOutline', 'DISTANCE', 0.0001)

# project to correct spatial reference
### THIS ASSUMES THAT OUTPUT COORDINATE SYSTEM IS HARN AND WE ARE IN OREGON OR WASHINGTON!!
if isNAD27:
    geotransformation = 'NAD_1927_To_NAD_1983_NADCON;NAD_1983_To_HARN_OR_WA'
else:
    geotransformation = 'NAD_1983_To_HARN_OR_WA'

geotransformation = ''

arcpy.Project_management('xxMapOutline', 'MapOutline', outSpRef,
                         geotransformation, xycs)

## TICS
# calculate minTicLong, minTicLat, maxTicLong, maxTiclat
ticInterval = ticInterval / 60.0  # convert minutes to degrees
minTicLong = int(round(0.1 + minLong // ticInterval))
maxTicLong = int(round(1.1 + maxLong // ticInterval))
minTicLat = int(round(0.1 + minLat // ticInterval))
maxTicLat = int(round(1.1 + maxLat // ticInterval))
if minTicLong < 0:
    minTicLong = minTicLong + 1
if maxTicLong < 0:
    maxTicLong = maxTicLong + 1
# make xy file for tics
addMsgAndPrint('  writing tic file')
genf = open(scratch + '/xxxtics.csv', 'w')
import arcpy
import arcgisscripting

gp = arcgisscripting.create()
arcpy.CheckOutExtension("3D")
gp.workspace = r"\\server23\Tasks\NightlyWeatherShapefile\Shapefile"

#Project Points From HRAP to State Plane
arcpy.Project_management(
    in_dataset="/nws_precip.shp",
    out_dataset="/nws_precip_projected.shp",
    out_coor_system=
    "GEOGCS['HRAP_Sphere',DATUM['<custom>',SPHEROID['<custom>',6371200.0,0.0]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]]",
    transform_method="#",
    in_coor_system=
    "GEOGCS['HRAP_Sphere',DATUM['<custom>',SPHEROID['<custom>',6371200.0,0.0]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]]"
)
print "Projecting Points Completed"

#Create Tin from Points
arcpy.CreateTin_3d(
    "E:/Tasks/NightlyWeatherShapefile/Shapefile/precipitation",
    "PROJCS['NAD_1983_StatePlane_Nebraska_FIPS_2600_Feet',GEOGCS['GCS_North_American_1983',DATUM['D_North_American_1983',SPHEROID['GRS_1980',6378137.0,298.257222101]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]],PROJECTION['Lambert_Conformal_Conic'],PARAMETER['False_Easting',1640416.666666667],PARAMETER['False_Northing',0.0],PARAMETER['Central_Meridian',-100.0],PARAMETER['Standard_Parallel_1',40.0],PARAMETER['Standard_Parallel_2',43.0],PARAMETER['Latitude_Of_Origin',39.83333333333334],UNIT['Foot_US',0.3048006096012192]]",
    "C:/Tasks/NightlyWeatherShapefile/Shapefile/nws_precip_projected.shp Globvalue masspoints <None>",
    "DELAUNAY")
print "Creating Tin from Points Completed"

#Create Contours from Tin
arcpy.SurfaceContour_3d(in_surface="/precipitation",
                        out_feature_class="/Contours.shp",
                        interval="1",
Exemplo n.º 30
0
        print("Please choose a valid analysis mode ")

#define spatial reference presets
spatialref_default = arcpy.SpatialReference(4326)
spatialref_proj = arcpy.SpatialReference(epsg)
spatial_ref = arcpy.Describe(inputpath + points)
#check projection of point shapefile and set projection if unknown
if spatial_ref.name == "Unknown":
    print(
        "The source points file has an unknown spatial reference, setting to default projection (EPSG 4326) "
    )
    arcpy.DefineProjection_management(points, spatialref_default)

#reproject shapefile to correct projection
points_projected = "sourcepoints_projected.shp"
arcpy.Project_management(inputpath + points, inputpath + points_projected,
                         spatialref_proj)
if binningmode == 0:
    #calculate interval values and time interval counts
    getintervals_time(sealvl, time, intervals)
elif binningmode == 1:
    getintervals_sealvl(sealvl, time, intervals)
#import interval file generated by getintervals subroutine
intervalfile = pandas.read_csv(outpath + 'intervals.csv')
#run subroutine to generate sea level rasters for each interval
makerasters(intervalfile, inputraster, epsg)
#run subroutine to generate distance matrices for each interval
if mode == 0:
    islandmode(intervalfile, points_projected)
    calcmatrices_island(
        outpath, intervalfile
    )  #run subroutine to calculate time-weighted average across distance matrices