def check_stream_direction(stream, z_raster, streamID): """Samples the elevation raster at both ends of the stream polyline to see which is the downstream end and returns flip = 1 if the stream km need to be reversed""" down = stream.positionAlongLine(0, True).centroid up = stream.positionAlongLine(1, True).centroid # when a single raster cell is sampled it is a little faster to # use arcpy compared to converting to an array and then sampling. # I left the code just in case though z_down = float( arcpy.GetCellValue_management(z_raster, str(down.X) + " " + str(down.Y), 1).getOutput(0)) z_up = float( arcpy.GetCellValue_management(z_raster, str(up.X) + " " + str(up.Y), 1).getOutput(0)) #z_down = arcpy.RasterToNumPyArray(z_raster, arcpy.Point(down.X, down.Y), 1, 1, -9999)[0][0] #z_up = arcpy.RasterToNumPyArray(z_raster, arcpy.Point(up.X, up.Y), 1, 1, -9999)[0][0] if z_down <= z_up or z_down == -9999 or z_up == -9999: # do not reverse stream km flip = 0 else: print("Reversing {0}".format(streamID)) # reversed stream km flip = 1 return flip
def summitBuffer(x,y, buff): # Start in top right corner x = x + CellSizeX * buff y = y + CellSizeY * buff # Move down for buffer in range(1, (2 * buff) + 1): point = str(x) + ' ' + str(y - (buffer * CellSizeY)) value = arcpy.GetCellValue_management(srcLocation, point).getOutput(0) #arcpy.AddMessage(point) #arcpy.AddMessage(value) if value == 'NoData': pass else: value = float(value) neighbors.push(point, value) y = y - (CellSizeY * buff * 2) # Move right for buffer in range(1, (2 * buff) + 1): point = str(x - (buffer * CellSizeX)) + ' ' + str(y) value = arcpy.GetCellValue_management(srcLocation, point).getOutput(0) #arcpy.AddMessage(point) #arcpy.AddMessage(value) if value == 'NoData': pass else: value = float(value) neighbors.push(point, value) x = x - (CellSizeX * buff * 2) # Move up for buffer in range(1, (2 * buff) + 1): point = str(x) + ' ' + str(y + (buffer * CellSizeY)) value = arcpy.GetCellValue_management(srcLocation, point).getOutput(0) #arcpy.AddMessage(point) #arcpy.AddMessage(value) if value == 'NoData': pass else: value = float(value) neighbors.push(point, value) y = y + (CellSizeY * buff * 2) # Move left for buffer in range(1, (2 * buff) + 1): point = str(x + (buffer * CellSizeX)) + ' ' + str(y) value = arcpy.GetCellValue_management(srcLocation, point).getOutput(0) #arcpy.AddMessage(point) #arcpy.AddMessage(value) if value == 'NoData': pass else: value = float(value) neighbors.push(point, value)
def onClick(self): #get the inputs (theoretically I'd like to loop though and find parent i,j automatically, but there's a variable # of domains and master regions) master_domain = pythonaddins.OpenDialog("Select your Master Domain", False, "", "","","") nest = pythonaddins.OpenDialog("Select your next Nested Domain", False, "", "","","") #calculate extents and get the lat/lon origin of the nested domain desc1 = ap.Describe(master_domain) desc2 = ap.Describe(nest) ext_master = desc1.extent ext_nested = desc2.extent if ext_master.contains(ext_nested) == True: #check if it actually fits nest_x = ext_nested.XMin nest_y = ext_nested.YMin x_y = "%s %s"%(nest_x, nest_y) #get cell value of MASTER at the point from nest cell_val = float(ap.GetCellValue_management(master_domain, x_y, "")[0]) #with cell value, find index on numpy array my_array = ap.RasterToNumPyArray(master_domain) index = numpy.where(my_array == cell_val) max_rows = int(ap.GetRasterProperties_management(master_domain, "ROWCOUNT", "")[0]) print "rows complete" def index_to_namelist(sample_index, rows): #using the actual index instead of calculating it based on geographic distance i = int(sample_index[1])+1 y = int(sample_index[0]) j = rows - y return i, j i_temp, j_temp = index_to_namelist(index, max_rows) global global_i, global_j global_i.append(i_temp) global_j.append(j_temp) print "The current nest indexes are: \ni: %r \nj:%r\nKeep on going until all nests are added" %(global_i, global_j) else: pythonaddins.MessageBox("DOMAIN ERROR: Nested domain is not contained within the Master Domain","DOMAIN ERROR!", 5) print "Try again!" #message box should get this, but keeping things consistent
def extractPixelValue(rasterFolder, namingConv, date, x, y, aggreLevel): aggreLevel = aggreLevel.lower() res = 0.0 cnt = 0 #valid number of days #the default aggregate level is daily beginDate = date endDate = date if aggreLevel == "monthly": beginDate = date.replace(day=1) numberDays = calendar.monthrange( date.year, date.month)[1] #the number of days in that month endDate = date.replace(day=numberDays) elif aggreLevel == "yearly": begindDate = date.replace(month=1, day=31) endDate = date.replace(month=12, day=31) while beginDate <= endDate: filename = parseFileName(beginDate, namingConv) filePath = rasterFolder + filename val = arcpy.GetCellValue_management(filePath, str(x) + " " + str(y), "1") if val.getOutput(0) == 'NoData': raster = arcpy.Raster(filePath) return True, raster.noDataValue #there is no data for the pixel location, then there is no need to continue search for other dates res += float(val.getOutput(0)) cnt += 1 beginDate += datetime.timedelta(days=1) if cnt != 0: res /= cnt return False, res
def execute(self, parameters, messages): raster = parameters[0].valueAsText feature = parameters[1].valueAsText fields = arcpy.ListFields(feature) fieldList = [field.name for field in fields] addFields = [] desc = arcpy.Describe(raster) for bandIndex in range(desc.bandCount): fname = 'BAND' + str(bandIndex) addFields.append(fname) if (not fname in fieldList): arcpy.AddField_management(feature, fname, "DOUBLE", 18, 11) addFields.append('SHAPE@XY') bandIndex = ';'.join(str(x) for x in range(1, desc.bandCount + 1)) with arcpy.da.UpdateCursor(feature, addFields) as cursor: for row in cursor: fname = 'BAND' + str(bandIndex) result = arcpy.GetCellValue_management( raster, str((row[-1])[0]) + " " + str((row[-1])[1]), bandIndex) res = result.getOutput(0).split('\\n') for inx in range(len(res)): cellValue = float(res[inx]) row[inx] = cellValue #Update the FC row cursor.updateRow(row) return
def reset_shapefile(self, shape_file): #print('Reset init camera locations') fieldlist = ['AZIMUTH1', 'AZIMUTH2', 'OFFSETA', 'RADIUS2'] tokens = ['SHAPE@X', 'SHAPE@Y'] with arcpy.da.UpdateCursor(shape_file, tokens + fieldlist) as cursor: delta = -1 X = self.init_observer_dist for row in cursor: delta += 1 #print('hei') row[0] = 150 #self.init_x + (delta%4)*X row[1] = 150 #self.init_y + (delta//4)*X*1.5 row[2] = self.init_azimuth1 row[3] = self.init_azimuth2 x = row[0] y = row[1] p = str(x) + " " + str(y) p_value = arcpy.GetCellValue_management(self.input_raster, p) #print('p_value', p_value) if int(p_value[0]) > 1: row[4] = int(p_value[0]) else: row[4] = int(p_value[0]) #0 row[5] = self.outer_radius cursor.updateRow(row) del cursor
def getBufferAverage(self, x, y): # create the point pnt = "{} {}".format(x, y) buffer_image = self.image_path.replace("100", "1000") arcpy.AddMessage(buffer_image) return self.encodePixelValue( arcpy.GetCellValue_management(buffer_image, pnt, "1"))
def __appendZs__(self, points): try: newcoords = "" coordpairs = points.split(';') pointGeometryList = [] fields=["SHAPE@X", "SHAPE@Y"] rows = arcpy.da.SearchCursor(points, fields) for row in rows: coordpair = str(row[0]) + ' ' + str(row[1]) arcpy.AddMessage('coords: ' + coordpair) result = arcpy.GetCellValue_management(self.islyr, coordpair) e = result.getOutput(0) if e != 'NoData': v = int(e) + self.height else: v = self.height if len(newcoords)>0: newcoords += ";" + coordpair + " " + str(v) else: newcoords += coordpair + " " + str(v) del rows del row arcpy.AddMessage('newcoords: ' + newcoords) return newcoords except arcpy.ExecuteError: EH = ErrorHandling.ErrorHandling() line, filename, err = EH.trace() m = "Python error on " + line + " of " + __file__ + \ " : with error - " + err arcpy.AddError(m)
def getvalue(self): global g_dir, flist location_point = str(self.map_x) + " " + str(self.map_y) for f in flist: inraster = g_dir + '/' + f result = ap.GetCellValue_management(inraster, location_point).getOutput(0) self.value.append(result)
def valore_precipitation_reliability_centroid(self): file_amministrativo = self.dirOut + self.admin + ".shp" file_centroide = self.dirOut + self.admin + "_ctrd.shp" adm2_centroid = arcpy.FeatureToPoint_management( file_amministrativo, file_centroide, "CENTROID") coords = arcpy.da.SearchCursor(adm2_centroid, ["SHAPE@XY"]) global x global y for polyg in coords: x, y = polyg[0] os.chdir(self.monthly_precipitation_dir) lista_raster = glob.glob("*.tif") valore = arcpy.GetCellValue_management(self.risk_raster, str(x) + " " + str(y))[0] if valore == "NoData": self.reliability_value = 0.0 else: self.reliability_value = valore valori_mensili = {} for raster_mese in lista_raster: result = arcpy.GetCellValue_management(raster_mese, str(x) + " " + str(y)) if result[0] == "NoData": valori_mensili[raster_mese] = 0.0 else: valori_mensili[raster_mese] = int(result[0]) global dizionario_in dizionario_in = self.build_value_list(valori_mensili) with open(self.dirOut + self.admin + "_prec.csv", 'wb') as csvfile: csvwriter = csv.writer(csvfile, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) for linea in dizionario_in.iteritems(): csvwriter.writerow(linea) return "Monthly Probability Function calculated....\n"
def getvalue(corr): x = corr[0] y = corr[1] global indir, flist location_point = str(x) + " " + str(y) value = [] for f in flist: inraster = indir + '/' + f result = ap.GetCellValue_management(inraster, location_point).getOutput(0) value.append(result) return value
def get_data(ship_data, data_raster_name, cell_size): if ship_data.ship_position.X < 0: position = str(ship_data.ship_position.X + 360) + " " + str( ship_data.ship_position.Y) else: position = str(ship_data.ship_position.X) + " " + str( ship_data.ship_position.Y) data = arcpy.GetCellValue_management(data_raster_name, position).getOutput(0) if data == 'NoData': avg_data = 0 count = 0 i = -2 while i < 3: j = -2 while j < 3: if math.fabs(i) + math.fabs(j) < 3: if ship_data.ship_position.X + i * cell_size < 0: position = str(ship_data.ship_position.X + 360 + i * cell_size) + " " + \ str(ship_data.ship_position.Y + j * cell_size) else: position = str(ship_data.ship_position.X + i * cell_size) + " " + \ str(ship_data.ship_position.Y + j * cell_size) near_data = arcpy.GetCellValue_management( data_raster_name, position).getOutput(0) if near_data != 'NoData': avg_data += float(near_data) count += 1 j += 1 i += 1 if count > 0: return avg_data / count else: return 'NoData' else: return float(data)
def calculate_aspect(order_obj, aspect_tif_pcs): order_geometry_pcs = order_obj.geometry.projectAs( order_obj.spatial_ref_pcs) centre_point_pcs = order_geometry_pcs.trueCentroid location = str(centre_point_pcs.X) + " " + str(centre_point_pcs.Y) aspect = arcpy.GetCellValue_management(aspect_tif_pcs, location) if aspect.getOutput((0)) != "NoData": aspect_text = utility.degree_direction_to_text( float(aspect.getOutput((0)))) if float(aspect.getOutput((0))) == -1: aspect_text = r'N/A' else: print('fail to use point XY to retrieve') aspect_text = '-9999' raise ValueError('No aspect retrieved CHECK data spatial reference') return aspect_text, centre_point_pcs.X, centre_point_pcs.Y
def getValueAtCentroid(self, inFeature, inRaster): try: sr = arcpy.Describe(inRaster).spatialReference i=0 totvalue = 0 shapeName = arcpy.Describe(inFeature).shapeFieldName with arcpy.da.SearchCursor(inFeature, "SHAPE@", spatial_reference=sr) as source_curs: for row in source_curs: i = i + 1 feature = row[0] value = arcpy.GetCellValue_management(inRaster,str(feature.centroid.X) + ' ' + str(feature.centroid.Y)).getOutput(0) totvalue = float(value)/i return totvalue except: tb = traceback.format_exc() self._sm("Failed to get raster at point " +tb,"ERROR",220) raise Exception("Failed to get raster at point " +tb)
def onSelChange(self, selection): mxd = arcpy.mapping.MapDocument("CURRENT") df = arcpy.mapping.ListDataFrames(mxd)[0] addLayer = arcpy.mapping.Layer(tool.varpath + selection) pythonaddins.MessageBox("Cargando: %s"%(tool.varpath + selection), "Carga Layer") arcpy.mapping.AddLayer(df, addLayer, "TOP") layer = arcpy.CreateFeatureclass_management(r'{0}\Users\{1}\Documents\ArcGIS\Default.gdb'.format(os.environ['systemdrive'],os.environ['username']), "data", "POINT").getOutput(0) fcaux = r'{0}\Users\{1}\Documents\ArcGIS\Default.gdb\data'.format(os.environ['systemdrive'],os.environ['username']) ras = arcpy.mapping.ListLayers(mxd, "V_*") ras = [ i for i in ras if i.isRasterLayer] names = [i.name for i in ras] [arcpy.AddField_management (fcaux, field_name=i.name, field_type="TEXT") for i in ras] vec = [ i for i in ras if not i.isRasterLayer and i.name != 'data'] rdat = [arcpy.GetCellValue_management(i.name,"{} {}".format(tool.x,tool.y),"1").getOutput(0) for i in ras] fields = ["SHAPE@XY"] fields.extend(names) cursor = arcpy.da.InsertCursor(fcaux, fields) xy = (tool.x, tool.y) fields = [xy] fields.extend(rdat) cursor.insertRow(fields) vect = arcpy.mapping.ListLayers(mxd, "V_*") prefijos=["APT_","W_","_APT","Des","GRIDCODE"] vec = [ i for i in vect if i.isFeatureLayer and i.name != 'data'] vector_name =[i.name for i in vec] [arcpy.AddField_management (fcaux, field_name=i.name, field_type="TEXT") for i in vec] vector_fields=[self.getCampoPrefijo(i,prefijos) for i in vec] valores_vector = [str(self.getValoresVector(fcaux,i,"in_memory//"+arcpy.Describe(i).name,self.getCampoPrefijo(i,prefijos)).encode('utf-8').strip()) for i in vec] with arcpy.da.UpdateCursor(fcaux, vector_name) as cursor: for fila in cursor: for num in xrange(len(valores_vector)): expre = """fila[%s] = valores_vector[%s]"""%(str(num),str(num)) exec(expre) cursor.updateRow(fila) extent = arcpy.Extent(tool.x-5000, tool.y-5000, tool.x+5000, tool.y+5000) # tool.deactivate() mxd = arcpy.mapping.MapDocument("CURRENT") lyr=arcpy.mapping.ListLayers(mxd) df = arcpy.mapping.ListDataFrames(mxd)[0] lyr = arcpy.mapping.ListLayers(mxd, "data", df)[0] arcpy.SelectLayerByAttribute_management(lyr, "NEW_SELECTION", ' "OBJECTID" = 1 ') # df.zoomToSelectedFeatures() df.extent = extent#lyr.getSelectedExtent()
def sample_NLDAS_timeseries(sdate, edate, lonlat_tuple, band): """ Given a month and location, get values from NLDAS raster """ xy_tuple = utm.from_latlon(lonlat_tuple[1], lonlat_tuple[0]) date = sdate ts = [] while date < edate: wildcard = ('*%04d%02d*' % (date.year, date.month)) date = date + relativedelta(months=+1) raster_list = arcpy.ListRasters(wildcard) raster = arcpy.Raster(raster_list[0]) # should only be one in the list result = arcpy.GetCellValue_management( raster, str(lonlat_tuple[0]) + " " + str(lonlat_tuple[1]), str(band)) val = float(result.getOutput(0)) ts.append(val) return numpy.asarray(ts)
def GetCellValue(demPath: str, fcPath: str) -> list: cursor = arcpy.da.SearchCursor(fcPath, ['POINT_X', 'POINT_Y']) xyList = [] for row in cursor: xyList.append((row[0], row[1])) del row, cursor xyzList = [] index = 0 for row in xyList: ## TEST OUTPUT ## print("Getting cell value for row {0}".format(index)) xyPair = str(row[0]) + " " + str(row[1]) result = arcpy.GetCellValue_management(demPath, xyPair, "1") xyzList.append((row[0], row[1], float(result.getOutput(0)))) index += 1 return xyzList
def findvisible(datapath, allfltpts, x, y): """ :param datapath: Path to input/output directory :param allfltpts: List of all flight points :param x: X coordinate location :param y: Y coordinate location :return: List of observed flight points """ coord = str(x) + " " + str(y) observed = [] for fp in allfltpts: print('Determining visibility of flight point {}'.format(fp)) cell = arcpy.GetCellValue_management(datapath + "vs_" + str(fp), coord) try: if int(cell.getOutput(0)) == 1: observed.append(fp) print('Visible.') except: print('Not visible.') print('Number of visible flight points: {}'.format(len(observed))) print(observed) return observed
def rasterStatistics(feature, featureID, inRaster, calculateStat): try: #create results obj results = {} #get values outExtractByMask = ExtractByMask(inRaster, feature) value = arcpy.GetRasterProperties_management( outExtractByMask, calculateStat).getOutput(0) value = round(float(value), 5) results[calculateStat] = value data = ResultObj(featureID, results) return data except: try: #check raster cell size against input cellsize = float( arcpy.GetRasterProperties_management(inRaster, 'CELLSIZEX').getOutput(0)) print 'in Except block, area check:', feature.area, cellsize**2 #get centroid value if first method failed value = arcpy.GetCellValue_management( inRaster, str(feature.centroid.X) + ' ' + str(feature.centroid.Y)).getOutput(0) value = round(float(value), 5) results[calculateStat] = value data = ResultObj(featureID, results) return data except: tb = format_exc() raise Exception(tb)
def createPixelValues(self, *args, **kwargs): buffer = kwargs.get("buffer", None) for x in self.coord: pnt = "{} {}".format(x["x"], x["y"]) res = self.encodePixelValue( arcpy.GetCellValue_management(self.image_path, pnt, "1")) # get the buffer average if the paramter is set if buffer: self.buffer_size = int(buffer) buffer_average = self.getBufferAverage(x["x"], x["y"]) object = { "indicator": self.indicator, "time": self.time, "indicator_value": str(res), "value_buffer": str(buffer_average) } else: object = { "indicator": self.indicator, "time": self.time, "indicator_value": str(res) } x["values"].append(object)
COUNTER += 1 # https://docs.python.org/3/library/decimal.html pctDone = Decimal(COUNTER) / Decimal(COUNT_RECORDS) * 100 LOGGER.info("Processing OID " + str(row[0]) + ", with current ASPECT value of " + str(row[3]) + ". Feature " + str(COUNTER) + " of " + str(COUNT_RECORDS) + " or " + str(pctDone) + " %") # Print the coordinate tuple LOGGER.debug("X and Y: " + str(row[1]) + " " + str(row[2])) # Set an initial default value LOGGER.debug("Setting default value of -2 before row is processed") cellvalue = -2.00 # Get the Cell Value from the Aspect Raster try: cellresult = arcpy.GetCellValue_management( ASPECT_RASTER, str(row[1]) + " " + str(row[2])) # See http://gis.stackexchange.com/questions/55246/casting-arcpy-result-as-integer-instead-arcpy-getcount-management cellvalue = float(cellresult.getOutput(0)) LOGGER.debug("The raster cell value is " + str(cellvalue)) except Exception as err: arcpy.AddError(err.args[0]) row[3] = cellvalue cursor.updateRow(row) LOGGER.debug("The aspect value is now: " + str(row[3])) # Calculate the execution time LOGGER.info("Aspect value calculation completed") #print datetime.now()
arcpy.AddMessage("iterations: " + str(iterations)) if (stepRange > 0): if debug == True: arcpy.AddMessage("Normal range") #for d in xrange(0,stepRange,step): #UPDATE for d in range(0, stepRange, step): h = SurfaceRange(d) if debug == True: arcpy.AddMessage("d,h: " + str(d) + "," + str(h)) t = TimeToRange(h) if t > tMax: tMax = t x = longitudeOfObserver + (d * math.cos(azimuthAngleRadians)) y = latitudeOfObserver + (d * math.sin(azimuthAngleRadians)) z = elevationOfObserver + h result = arcpy.GetCellValue_management(inputSurface, str(x) + " " + str(y)) if result.getOutput(0) == None or result.getOutput( 0) == "NoData": arcpy.AddWarning( "Encountered NoData cell on surface.\nStopping trajectory for observer " + str(obsOID)) break surfElev = float(result.getOutput(0)) if debug == True: arcpy.AddMessage(str([d, x, y, z, h, t, surfElev])) path.append([x, y, z, t]) pathArray.append(arcpy.Point( x, y, z, t)) # add the point to the path array
feat.setValue(mbgShapeFieldName, arcpy.Point(mbgCenterX, mbgCenterY)) rows.insertRow(feat) del rows delete_me.append(mbgCenterPoint) # Get the proper distance radius, tower height (offset), and z_factor maxRad = obsMaximums['RADIUS2'] maxOffset = obsMaximums['OFFSETA'] z_factor = float(zfactor(tower)) horizonDistance = 0.0 if RADIUS2_to_infinity == True: # if going to infinity what we really need is the distance to the horizon based on height/elevation arcpy.AddMessage("...Finding horizon distance ...") result = arcpy.GetCellValue_management( input_surface, str(mbgCenterX) + " " + str(mbgCenterY)) centroid_elev = result.getOutput(0) R2 = float(centroid_elev) + float(maxOffset) R = 6378137.0 # length, in meters, of semimajor axis of WGS_1984 spheroid. horizonDistance = math.sqrt(math.pow((R + R2), 2) - math.pow(R, 2)) arcpy.AddMessage("..." + str(horizonDistance) + " meters.") horizonExtent = str(mbgCenterX - horizonDistance) + " " + str( mbgCenterY - horizonDistance) + " " + str( mbgCenterX + horizonDistance) + " " + str(mbgCenterY + horizonDistance) else: pass # reset center of AZED using Lat/Lon of MBG center point # Project point to WGS 84
def GetHeight(point, dem): result = arcpy.GetCellValue_management(dem, str(point)) valuestr = result.getOutput(0) return float(valuestr) if valuestr != "NoData" else 0.0
) #information is saved into a new tiff file with NDVI information NDVI_Raster = folder_path + '\NDVI1.tif' #variable is assigned the newly created tiff file Range1 = RemapRange( [[-1, 0, 1], [0, 0.3, 2], [0.3, 1, 3]] ) # Class is defined for the reclassification scheme specified by the project guidelines Reclass = Reclassify( NDVI_Raster, 'Value', Range1 ) #reclassifies the tiff file in accordance to the range presented above Reclass.save(folder_path + '\_Reclassified.tif' ) #saves information in a newly created reclassified tiff file NDVI_Val = arcpy.GetCellValue_management(NDVI_Raster, '349201, 3772463') # gets the cell value of the NDVI Raster File at specified coordinates and assigns them a variable Reclass_Val = arcpy.GetCellValue_management(folder_path + '\_reclassified.tif', '349201, 3772463') # gets the cell value of the Reclassified raster file at the specified coordinates and assigns them a variable print 'NDVI Cell Value = ' + str( NDVI_Val) + ' and Reclassified Cell Value = ' + str( Reclass_Val) + ' at coordinates 349201, 3772463' # prints NDVI cell value plus the reclassified NDVI value from the variable set above print '_____________________________________________' #### NDWI #### NIR2 = arcpy.Raster(Landsat + '/Band_4') # Near Infrared band is assigned to a variable
def FindSummit(source_location, input_file, store_dir, store_name): arcpy.CreateFeatureclass_management(store_dir, store_name, "POINT", input_file, "DISABLED", "DISABLED", spatial_ref) for row in arcpy.da.SearchCursor(pointFC, fields, spatial_reference=spatial_ref): pointName = row[0] pointFID = row[1] pointState = row[2] pointCounty = row[3] pointShape = row[5] x, y = pointShape.firstPoint.X, pointShape.firstPoint.Y feature = row[4] # If a multipoint, store it, but do not change it point = str(x) + ' ' + str(y) point_list = [pointName, pointFID, pointState, pointCounty, feature, pointShape] if row[1] in multi_points and feature == 'Summit': pointsToAddOverall.append({'NAME': pointName, 'FID': pointFID, 'STATE': pointState, 'COUNTY': pointCounty, 'FEATURE': feature, 'POINT': pointShape, 'DISTANCE': 0, 'ELEV': float(arcpy.GetCellValue_management(source_location, point).getOutput(0))}) continue # If a single summit, process through the summit analysis if feature == 'Summit': print ('') arcpy.AddMessage(pointName) arcpy.AddMessage(pointFID) arcpy.AddMessage(feature) # Set global bool to false indicating a summit has not been found global summitFound summitFound = False # Clear the queue neighbors.clear() global moved # Set moved to 0 indicating a new summit moved = 0 global GNISx,GNISy # Store the original x and y values GNISx = x GNISy = y # Create the point using xy point = str(x) + ' ' + str(y) # Get value under point testValue = float(arcpy.GetCellValue_management(source_location, point).getOutput(0)) # Get its 8 neighbors values adjValues(seperatePoint(point, 0), seperatePoint(point, 1)) # Test for a summit checkNeighbors(testValue, point, source_location, point_list) else: pass arcpy.AddMessage('Writing data to feature class....') # Add data to the new feature class FCFile = store_dir + '\\' + store_name if not FCFile.endswith('.shp'): FCFile = FCFile + '.shp' arcpy.AddField_management(FCFile, 'distance_m', 'FLOAT') arcpy.AddField_management(FCFile, 'elevation', 'FLOAT') # cursor = arcpy.da.InsertCursor(FCFile, newFields) for entry in pointsToAddOverall: with arcpy.da.InsertCursor(FCFile, newFields) as cursor: row = [entry['NAME'], entry['FID'], entry['STATE'], entry['COUNTY'], entry['FEATURE'], entry['POINT'], entry['DISTANCE'], entry['ELEV']] cursor.insertRow(row) arcpy.AddMessage(row) arcpy.AddMessage('Done!') return (FCFile)
for raster in rasterlist: RasObj = arcpy.Raster(raster) #create raster object for later analysis print raster + ": " + RasObj.spatialReference.Name + ' Band #: ' + str( RasObj.bandCount) print RasObj.height, RasObj.width, RasObj.meanCellHeight, RasObj.meanCellWidth, RasObj.spatialReference.linearUnitName del raster, rasterlist, RasObj print "End of List Rasters" #----------------------------------------------- #3. Accessing cell values inRaster = arcpy.Raster("Landsat.TIF") BandID = '1' result = arcpy.GetCellValue_management(inRaster, "349202 3772473", BandID) print result cellValues = result.getOutput(0).split("\\n") for cellValue in cellValues: print int(cellValue) del inRaster print "Done with Cell Value" #----------------------------------------------- #4. Access band data RasterData = "Landsat.tif" RedBand = arcpy.Raster(RasterData + "/Band_3") RedBand.save("Red3.TIF") del RedBand
# Loop through geometry attributes and get the x and y with arcpy.da.SearchCursor(InputPoint, ['SHAPE@X', 'SHAPE@Y']) as cursor: PointIndex = 1 for row in cursor: X = row[0] Y = row[1] # Get rasters and extract data at an X and Y index = 0 for (path, dirs, files) in os.walk(DataSource): for ThisFile in files: fName, fExt = os.path.splitext(ThisFile) if fExt.upper() == ".IMG" or fExt.upper() == ".TIF": RasterPath = path + "\\" + ThisFile data = (arcpy.GetCellValue_management( RasterPath, str(X) + " " + str(Y), "").getOutput(0)) aquisition_date = arcpy.GetRasterProperties_management( in_raster=RasterPath, property_type="ACQUISITIONDATE") if str(aquisition_date).upper() == "UNKNOWN": insertcursor = arcpy.InsertCursor(OutputFC) row = insertcursor.newRow() row.setValue("LABEL", "{}, Point: {}".format(index, PointIndex)) if data.isdigit() == True: row.setValue("VALUE", int(data)) insertcursor.insertRow(row) del insertcursor index += 1
'rain_raster_proj.tif') pet_raster_proj = os.path.join(arcpy.env.scratchFolder, 'pet_raster_proj.tif') arcpy.ProjectRaster_management(in_raster=rain_raster, out_raster=rain_raster_proj, out_coor_system=spat_ref) arcpy.ProjectRaster_management(in_raster=pet_raster, out_raster=pet_raster_proj, out_coor_system=spat_ref) # Open Strahler 1 shp and loop through reach ids list with arcpy.da.SearchCursor(reaches_shp, ['nzseg_v3', 'SHAPE@']) as search_cursor: for row in search_cursor: reach_id = row[0] shape = row[1] if reach_id in reach_ids: # Find rainfall value from closest grid square to polygon centrepoint rasterValueAtPoint = arcpy.GetCellValue_management( rain_raster_proj, shape.centroid).getOutput(0) print(rasterValueAtPoint) # Use rain and pet data from this square # Generate soil params for reach # Write data to input netCDF file # Close off netCDF files
clip_raster = arcpy.sa.ExtractByMask( "us.tmax_nohads_ll_20140525_float_NAD.tif", clipzone, ) clip_raster.save("us.tmax_nohads_ll_20140525_float_NAD_extract_by_mask.tif") arcpy.AddMessage( "ExtractByMask raster us.tmax_nohads_ll_20140525_float_NAD_extract_by_mask.tif" ) # Get value temperature with arcpy.da.SearchCursor("us_cities_level_" + str(popsize) + ".shp", "SHAPE@XY") as cursor: temperature = [] for i in cursor: res = arcpy.GetCellValue_management( "us.tmax_nohads_ll_20140525_float_NAD_extract_by_mask.tif", str(i[0][0]) + " " + str(i[0][1])) value = float(str(res.getOutput(0)).replace(",", ".")) temperature.append(float(value)) arcpy.AddMessage("Get value temperature") # Add new fields and update arcpy.AddField_management("us_cities_level_" + str(popsize) + ".shp", "TEMPERATUR", 'FLOAT') arcpy.AddField_management("us_cities_level_" + str(popsize) + ".shp", "EXCESS", 'FLOAT') arcpy.AddMessage('Added new fields to the TEMPERATUR and EXCESS') with arcpy.da.UpdateCursor("us_cities_level_" + str(popsize) + ".shp", ["TEMPERATUR", "EXCESS"]) as Upcursor: i = 0