def finish_range(msag_range): """Finish attributes in MSAG range dictionary. Args: msag_range (dict): Mapping of range attribute name to value. Returns: dict: Mapping of range attribute name to value. """ new_range = msag_range.copy() # Walk names from address to MSAG range style. change_key = { "esn": "emergency_service_number", "predir": "prefix_direction_code", "name": "street_name", "type": "street_type_code", "sufdir": "suffix_direction_code", "postcomm": "postal_community", } sref = arcpy.SpatialReference(EPSG) for old_key, new_key in change_key.items(): new_range[new_key] = new_range.pop(old_key) new_range["parity"] = parity(new_range["structure_numbers"]) new_range["parity_code"] = new_range["parity"][0].upper() new_range["from_structure_number"] = min(new_range["structure_numbers"]) new_range["to_structure_number"] = max(new_range["structure_numbers"]) if MSAG_GEOMETRY_STYLE == "convex-hull": new_range["shape@"] = (arcpy.Multipoint( arcpy.Array(new_range["points"]), sref).convexHull().buffer(50)) elif MSAG_GEOMETRY_STYLE == "hull-rectangle": LOG.warning( "Hull rectangle style currently cannot create polygons for 2-point ranges." ) if len(new_range["points"]) == 1: centroid = new_range["points"][0] new_range["points"] = [ arcpy.Point(centroid.X - 50, centroid.Y + 50), arcpy.Point(centroid.X + 50, centroid.Y + 50), arcpy.Point(centroid.X + 50, centroid.Y - 50), arcpy.Point(centroid.X - 50, centroid.Y - 50), ] new_range["shape@"] = arcpy.Polygon( arcpy.Array(new_range["points"]), sref) else: new_range["shape@"] = arcpy.Multipoint( arcpy.Array(new_range["points"])) nums = [ float(coord) for coord in new_range["shape@"].hullRectangle.split() ] new_range["points"] = [ arcpy.Point(*nums[i:i + 2]) for i in range(0, len(nums), 2) ] new_range["shape@"] = arcpy.Polygon( arcpy.Array(new_range["points"]), sref).buffer(50) elif MSAG_GEOMETRY_STYLE == "multipoint": new_range["shape@"] = arcpy.Multipoint(arcpy.Array( new_range["points"])) return new_range
def finish_range(msag_range, geometry_style, spatial_reference): """Finish info for MSAG range dictionary. Args: msag_range (dict): Mapping of range attribute name to value. geometry_style (str): Style of geometry for range feature. Can be "convex-hull", "hull-rectangle", or "multipoint". spatial_reference (arcpy.SpatialReference): ArcPy spatial reference object. Returns: dict: Finalized mapping of range attribute name to value. """ final_range = msag_range.copy() final_range["parity"] = parity(final_range["house_numbers"]) final_range["parity_code"] = final_range["parity"][0].upper() final_range["from_house_number"] = min(final_range["house_numbers"]) final_range["to_house_number"] = max(final_range["house_numbers"]) if geometry_style == "convex-hull": final_range["shape@"] = ( arcpy.Multipoint(arcpy.Array(final_range["points"]), spatial_reference) .convexHull() .buffer(50) ) elif geometry_style == "hull-rectangle": LOG.warning( "Hull rectangle style currently cannot create polygons for 2-point ranges." ) if len(final_range["points"]) == 1: centroid = final_range["points"][0] final_range["shape@"] = arcpy.Polygon( arcpy.Array( [ arcpy.Point(centroid.X - 50, centroid.Y + 50), arcpy.Point(centroid.X + 50, centroid.Y + 50), arcpy.Point(centroid.X + 50, centroid.Y - 50), arcpy.Point(centroid.X - 50, centroid.Y - 50), ] ), spatial_reference, ) else: points = arcpy.Multipoint(arcpy.Array(final_range["points"])) nums = [float(coord) for coord in points.hullRectangle.split()] final_range["shape@"] = arcpy.Polygon( arcpy.Array( arcpy.Point(*nums[i : i + 2]) for i in range(0, len(nums), 2) ), spatial_reference, ).buffer(50) elif geometry_style == "multipoint": final_range["shape@"] = arcpy.Multipoint(arcpy.Array(final_range["points"])) return final_range
def get_dis_list(self, field_dis): #fied_dis=DIS env.workspace = self.env pointFeature = self.point_object orignBuffer = self.inhabit_dis field_id = field_dis desc = arcpy.Describe(orignBuffer) with arcpy.da.SearchCursor( pointFeature, [field_id, "SHAPE@XY"], spatial_reference=desc.spatialReference) as curse: xyList = [] Id_list = [] for row in curse: Id_list.append(row[0]) pn = row[1] xyList.append([pn[0], pn[1]]) del row, curse featureList = [] temp_point = arcpy.Point() for pn in xyList: temp_point.X = pn[0] temp_point.Y = pn[1] array = arcpy.Array() array.add(temp_point) MultiPn = arcpy.Multipoint(array) featureList.append(MultiPn) dislist = [] id_list2 = [] for i, Multipn in enumerate(featureList): for j, Multipn2 in enumerate(featureList): if (Multipn != Multipn2): dis = Multipn.distanceTo(Multipn2) dislist.append(dis) id_list2.append([i, j]) return dislist, id_list2
def get_unique_point(line_layer, start_of_drainages="p_o_start"): global start_of_drainages_fullpath arcpy.CreateFeatureclass_management(workspace, start_of_drainages, "Multipoint", "", "DISABLED", "DISABLED", line_layer) geometries = arcpy.CopyFeatures_management(line_layer, arcpy.Geometry()) #arcpy.AddMessage("-"*22) startlist = [] lastlist = [] for geometry in geometries: startlist.append( [round(geometry.firstPoint.X, 2), round(geometry.firstPoint.Y, 2)]) lastlist.append( [round(geometry.lastPoint.X, 2), round(geometry.lastPoint.Y, 2)]) unique_list = [] for x in startlist: if x not in lastlist: unique_list.append(x) for zz in unique_list: array = arcpy.Array(arcpy.Point(zz[0], zz[1])) Multipoint = arcpy.Multipoint(array) cursor = arcpy.da.InsertCursor(start_of_drainages_fullpath, "SHAPE@") cursor.insertRow((Multipoint, )) del cursor
def get9Cells(x,y): masterLayer_dem = arcpy.mapping.Layer(masterlyr_dem) a = numpy.zeros((3,3)) arrays = numpy.array([a,a,a,a,a,a,a,a,a]) outshpP = r"in_memory\nightSHP"#os.path.join(scratch,'nightSHP.shp') arcpy.CreateFeatureclass_management('in_memory', "nightSHP", "MULTIPOINT", "", "DISABLED", "DISABLED", srGCS83) cursor = arcpy.da.InsertCursor(outshpP, ['SHAPE@']) for i in range(9): cursor.insertRow([arcpy.Multipoint(arcpy.Array([arcpy.Point(x+((-3.5+2*(i%3))*cellsize),y+((0.5-2*(i/3))*cellsize))]),srGCS83)]) arcpy.SelectLayerByLocation_management(masterLayer_dem, 'intersect', outshpP) if int((arcpy.GetCount_management(masterLayer_dem).getOutput(0))) != 0: columns = arcpy.SearchCursor(masterLayer_dem) for column in columns: img = column.getValue("image_name") if img.strip() !="": img = os.path.join(imgdir_dem,img) break del column del columns xx = arcpy.RasterToNumPyArray(img,arcpy.Point(x+((-3.5+2*(0%3))*cellsize),y+((0.5-2*(8/3))*cellsize)),9,9) (arrays[0],arrays[1],arrays[2],arrays[3],arrays[4],arrays[5],arrays[6],arrays[7],arrays[8])=(xx[:3,[0,1,2]],xx[:3,[3,4,5]],xx[:3,[6,7,8]],xx[3:6,[0,1,2]],xx[3:6,[3,4,5]],xx[3:6,[6,7,8]],xx[6:9,[0,1,2]],xx[6:9,[3,4,5]],xx[6:9,[6,7,8]]) for i in range(9): arrays[i]=(numpy.ma.masked_where(arrays[i] <0, arrays[i])) return [[arrays[0].mean(),arrays[1].mean(),arrays[2].mean()],[arrays[3].mean(),arrays[4][2,2],arrays[5].mean()],[arrays[6].mean(),arrays[7].mean(),arrays[8].mean()]]
def points_to_multipoints( dataset_path: Union[Path, str], *, output_path: Union[Path, str], dataset_where_sql: Optional[str] = None, log_level: int = logging.INFO, ) -> Counter: """Convert geometry from points to multipoints. Args: dataset_path: Path to dataset. output_path: Path to output dataset. dataset_where_sql: SQL where-clause for dataset subselection. log_level: Level to log the function at. Returns: Feature counts for original and output datasets. """ dataset_path = Path(dataset_path) output_path = Path(output_path) LOG.log( log_level, "Start: Convert points in `%s` to multipoints in output `%s`.", dataset_path, output_path, ) _dataset = Dataset(dataset_path) # ArcPy2.8.0: Convert Path to str (2x). arcpy.management.CreateFeatureclass( out_path=str(output_path.parent), out_name=output_path.name, geometry_type="MULTIPOINT", template=str(dataset_path), spatial_reference=_dataset.spatial_reference.object, ) field_names = _dataset.user_field_names + ["SHAPE@"] # ArcPy2.8.0: Convert Path to str. multipoint_cursor = arcpy.da.InsertCursor(in_table=str(output_path), field_names=field_names) # ArcPy2.8.0: Convert Path to str. point_cursor = arcpy.da.SearchCursor( in_table=str(dataset_path), field_names=field_names, where_clause=dataset_where_sql, ) states = Counter() states["in original dataset"] = dataset.feature_count(dataset_path) with multipoint_cursor, point_cursor: for point_feature in point_cursor: multipoint_geometry = arcpy.Multipoint( point_feature[-1].firstPoint) multipoint_feature = point_feature[:-1] + (multipoint_geometry, ) multipoint_cursor.insertRow(multipoint_feature) states["in output"] = dataset.feature_count(output_path) log_entity_states("features", states, logger=LOG, log_level=log_level) LOG.log(log_level, "End: Convert.") return states
def make_feature(feature): """Makes a feature from a arcrest.geometry object.""" geometry = None sr = arcpy.SpatialReference(4326) if 'paths' in feature['geometry']: paths = feature['geometry']['paths'] if len(paths) == 1: geometry = arcpy.Polyline( arcpy.Array([arcpy.Point(*coords) for coords in paths[0]]), sr) else: parts = [] for path in paths: parts.append( arcpy.Array([arcpy.Point(*coords) for coords in path])) geometry = arcpy.Polyline(arcpy.Array(parts), sr) elif 'rings' in feature['geometry']: rings = feature['geometry']['rings'] if len(rings) == 1: geometry = arcpy.Polygon( arcpy.Array([arcpy.Point(*coords) for coords in rings[0]]), sr) else: parts = [] for ring in rings: parts.append( arcpy.Array([arcpy.Point(*coords) for coords in ring])) geometry = arcpy.Polygon(arcpy.Array(parts), sr) elif 'points' in feature['geometry']: points = feature['geometry']['points'] if len(points) == 1: geometry = arcpy.Multipoint( arcpy.Array([arcpy.Point(*coords) for coords in points[0]]), sr) else: parts = [] for point in points: parts.append( arcpy.Array([arcpy.Point(*coords) for coords in point])) geometry = arcpy.Multipoint(arcpy.Array(parts), sr) if geometry: return geometry else: raise NullGeometry
def Mcp(pointList): if type(pointList[0]) != arcpyPointType: pointList = [arcpy.Point(point[0], point[1]) for point in pointList] #MinimumBoundingGeometry() will not accept a list or an arcpy.Array of geometries, #only a single geometry works (Polyline or Multipoint is much faster than a Polygon). points = arcpy.Multipoint(arcpy.Array(pointList)) empty = arcpy.Geometry() #correct results are dependent on having arcpy.env.outputCoordinateSystem set mcpList = arcpy.MinimumBoundingGeometry_management(points, empty, "CONVEX_HULL", "ALL") return mcpList[0]
def CreateMultiPointFromXYdecimal(lonlatlist): """lonlatlist in a form of [[px,py],[px', py']...] returns a multipoint geometry, need insert cursor to make it a feature class""" point = arcpy.Point() array = arcpy.Array() for eachpoint in lonlatlist: point.X = float(eachpoint[0]) point.Y = float(eachpoint[1]) array.add(point) multipoint = arcpy.Multipoint(array) return multipoint
def createGeometry(pntCoords, geometry_type): geometry = arcpy.Geometry() spatialRef = arcpy.SpatialReference(4326) if geometry_type.lower() == 'point': geometry = arcpy.Multipoint( arcpy.Array([arcpy.Point(*coords) for coords in pntCoords]), spatialRef) elif geometry_type.lower() == 'polyline': geometry = arcpy.Polyline( arcpy.Array([arcpy.Point(*coords) for coords in pntCoords]), spatialRef) elif geometry_type.lower() == 'polygon': geometry = arcpy.Polygon( arcpy.Array([arcpy.Point(*coords) for coords in pntCoords]), spatialRef) return geometry
def arcpnts_poly(in_, out_type='Polygon', SR=None): """Convert arcpy Point lists to poly* features : out_type - either 'Polygon' or 'Polyline' : """ s = [] for i in in_: for j in i: if out_type == 'Polygon': g = arcpy.Polygon(arcpy.Array(j), SR) elif out_type == 'Polyline': g = arcpy.Polyline(arcpy.Array(j), SR) elif out_type == 'Points': j = _flat_(j) g = arcpy.Multipoint(arcpy.Array(j), SR) # check s.append(g) return s
def centreFromPolygon(self, polygonSHP, coordinate_system): arcpy.AddField_management(polygonSHP, "xCentroid", "DOUBLE", 18, 11) arcpy.AddField_management(polygonSHP, "yCentroid", "DOUBLE", 18, 11) arcpy.CalculateField_management(in_table=polygonSHP, field="xCentroid", expression="!SHAPE.CENTROID.X!", expression_type="PYTHON_9.3", code_block="") arcpy.CalculateField_management(in_table=polygonSHP, field="yCentroid", expression="!SHAPE.CENTROID.Y!", expression_type="PYTHON_9.3", code_block="") in_rows = arcpy.SearchCursor(polygonSHP) outPointFileName = "polygonCentre" centreSHP = os.path.join(cfg.scratch, cfg.scratchgdb, outPointFileName) point1 = arcpy.Point() array1 = arcpy.Array() featureList = [] arcpy.CreateFeatureclass_management( os.path.join(cfg.scratch, cfg.scratchgdb), outPointFileName, "POINT", "", "DISABLED", "DISABLED", coordinate_system) cursor = arcpy.InsertCursor(centreSHP) feat = cursor.newRow() for in_row in in_rows: # Set X and Y for start and end points point1.X = in_row.xCentroid point1.Y = in_row.yCentroid array1.add(point1) centerpoint = arcpy.Multipoint(array1) array1.removeAll() featureList.append(centerpoint) feat.shape = point1 cursor.insertRow(feat) del feat del in_rows del cursor del point1 del array1 arcpy.AddXY_management(centreSHP) return centreSHP
def exercise_6(): arcpy.env.overwriteOutput = True arcpy.env.outputCoordinateSystem = arcpy.SpatialReference(103501) print("Modules imported and environments set.") #variables outageXY = r"C:\Users\Student\Desktop\ArcPy\PYTS_1.1_Jul18_StudentData\EsriTraining\PYTS\Data\OutageXY.csv" outConvexHull = r"C:\Users\Student\Desktop\ArcPy\PYTS_1.1_Jul18_StudentData\EsriTraining\PYTS\Data\Outages.gdb\CurrentAffectedArea" outputJoin = r"in_memory\outputJoin" serviceAreas = r"C:\Users\Student\Desktop\ArcPy\PYTS_1.1_Jul18_StudentData\EsriTraining\PYTS\Data\CountyData.gdb\ServiceAreas" print("Variables are set.") #Append coordinates from csv in a list outageCoords = [] csvFile = open(outageXY, 'r') csvReader = csv.reader(csvFile) next(csvReader) for row in csvReader: outageCoords.append(row) #Create a multipoint geometry object from list of coordinates outagePoints = (arcpy.Multipoint( arcpy.Array([arcpy.Point(*coords) for coords in outageCoords]))) print("Geometry object created") #Create outage boundary using convex hull convexHull = outagePoints.convexHull() arcpy.CopyFeatures_management(convexHull, outConvexHull) print("Outage boundary created") #Use Spatial Join to identify affected areas arcpy.SpatialJoin_analysis(serviceAreas, outagePoints, outputJoin) print("Spatial join finished.") #Search join output sFields = ['Join_Count', 'ServArNu'] exp = '"Join_Count" = 1' print("Affected service areas") with arcpy.da.SearchCursor(outputJoin, sFields, exp) as sCursor: for row in sCursor: print("Service Area: {}".format(row[1])) print("Analysis complete.")
def get_buffer_list(): env.workspace = 'E:/data/shenzhen/shenzhen.mdb' pointFeature = 'shenzhen_random_split' orignBuffer = 'shenzhen' field_id = "DIS" desc = arcpy.Describe(orignBuffer) with arcpy.da.SearchCursor( pointFeature, [field_id, "SHAPE@XY"], spatial_reference=desc.spatialReference) as curse: xyList = [] Id_list = [] for row in curse: Id_list.append(row[0]) pn = row[1] xyList.append([pn[0], pn[1]]) del row, curse featureList = [] temp_point = arcpy.Point() for pn in xyList: temp_point.X = pn[0] temp_point.Y = pn[1] array = arcpy.Array() array.add(temp_point) MultiPn = arcpy.Multipoint(array) featureList.append(MultiPn) bufferList = [] bufferList2 = [] for Multipn in featureList: temp_bufferlist = [] for Multipn2 in featureList: if (Multipn != Multipn2): dis = Multipn.distanceTo(Multipn2) temp_poly = Multipn.buffer(dis) temp_poly2 = temp_poly.projectAs( arcpy.Describe(orignBuffer).spatialReference) temp_bufferlist.append(temp_poly2) bufferList2.append(temp_poly2) bufferList.append(temp_bufferlist) #arcpy.CopyFeatures_management(bufferList2, outFeature) return bufferList, Id_list
def createGeometry(coordslist, typeOrder): outshpP = str(r'in_memory/outshpP') if typeOrder.lower() == 'point': arcpy.CreateFeatureclass_management(r'in_memory', "outshpP", "MULTIPOINT", "", "DISABLED", "DISABLED", srGCS83) cursor = arcpy.da.InsertCursor(outshpP, ['SHAPE@']) cursor.insertRow([ arcpy.Multipoint( arcpy.Array([arcpy.Point(*coords) for coords in coordslist[0]]), srGCS83) ]) elif typeOrder.lower() == 'polyline': arcpy.CreateFeatureclass_management(r'in_memory', "outshpP", "POLYLINE", "", "DISABLED", "DISABLED", srGCS83) arcpy.AddField_management(outshpP, "BearingD", 'FLOAT', 10) cursor = arcpy.da.InsertCursor(outshpP, ['SHAPE@', 'BearingD']) cursor.insertRow(((arcpy.Polyline( arcpy.Array([arcpy.Point(*coords) for coords in coordslist[0]]), srGCS83)), BearingD)) else: arcpy.CreateFeatureclass_management(r'in_memory', "outshpP", "POLYGON", "", "DISABLED", "DISABLED", srGCS83) cursor = arcpy.da.InsertCursor(outshpP, ['SHAPE@']) cursor.insertRow([ arcpy.Polygon( arcpy.Array([arcpy.Point(*coords) for coords in coordslist[0]]), srGCS83) ]) del cursor outputShp = os.path.join(scratch, 'outshpP.shp') if typeOrder.lower() == 'polyline': arcpy.Buffer_analysis(outshpP, outputShp, u'1 Feet') else: arcpy.CopyFeatures_management(outshpP, outputShp) if typeOrder.lower() != 'point': calculateBearDistance(outputShp) return outputShp
def createSHP(pntPairs): try: outshpP = os.path.join(r'in_memory', r'outshpP') arcpy.Delete_management(outshpP) _ = outshpP srGCS83 = arcpy.SpatialReference(4269) arcpy.CreateFeatureclass_management(r'in_memory', r"outshpP", "MULTIPOINT", "", "DISABLED", "DISABLED", srGCS83) cursor = arcpy.da.InsertCursor(_, ['SHAPE@']) cursor.insertRow([ arcpy.Multipoint( arcpy.Array( [arcpy.Point(*coords) for coords in pntPairs.values()]), srGCS83) ]) return _ except Exception as e: print e.message return _
def createordergeometry(self, order_obj, projection): arcpy.env.overwriteOutput = True point = arcpy.Point() array = arcpy.Array() sr = arcpy.SpatialReference() sr.factoryCode = 4269 # requires input geometry is in 4269 sr.XYTolerance = .00000001 sr.scaleFactor = 2000 sr.create() featureList = [] for feature in json.loads(order_obj.geometry.JSON).values()[0]: # order coordinates # For each coordinate pair, set the x,y properties and add to the Array object. for coordPair in feature: try: point.X = coordPair[0] point.Y = coordPair[1] except: point.X = feature[0] point.Y = feature[1] sr.setDomain(point.X, point.X, point.Y, point.Y) array.add(point) if order_obj.geometry.type.lower() == 'point' or order_obj.geometry.type.lower() == 'multipoint': feat = arcpy.Multipoint(array, sr) elif order_obj.geometry.type.lower() =='polyline': feat = arcpy.Polyline(array, sr) else: feat = arcpy.Polygon(array,sr) array.removeAll() # Append to the list of Polygon objects featureList.append(feat) arcpy.CopyFeatures_management(featureList, cfg.orderGeometry) arcpy.Project_management(cfg.orderGeometry, cfg.orderGeometryPR, projection) del point del array
def get_buffer_list(self,field_dis): #fied_dis=DIS env.workspace =self.env pointFeature = self.point_object orignBuffer =self.inhabit_dis field_id = field_dis desc = arcpy.Describe(orignBuffer) with arcpy.da.SearchCursor(pointFeature, [field_id, "SHAPE@XY"], spatial_reference=desc.spatialReference) as curse: xyList = [] Id_list = [] for row in curse: Id_list.append(row[0]) pn = row[1] xyList.append([pn[0], pn[1]]) del row, curse featureList = [] temp_point = arcpy.Point() for pn in xyList: temp_point.X = pn[0] temp_point.Y = pn[1] array = arcpy.Array() array.add(temp_point) MultiPn = arcpy.Multipoint(array) featureList.append(MultiPn) bufferList = [] bufferList2 = [] for Multipn in featureList: temp_bufferlist = [] for Multipn2 in featureList: if (Multipn != Multipn2): dis = Multipn.distanceTo(Multipn2) temp_poly = Multipn.buffer(dis) temp_poly2 = temp_poly.projectAs(arcpy.Describe(orignBuffer).spatialReference) temp_bufferlist.append(temp_poly2) bufferList2.append(temp_poly2) bufferList.append(temp_bufferlist) # arcpy.CopyFeatures_management(bufferList2, outFeature) return bufferList, Id_list
def createGeometry(pntCoords, geometry_type, output_folder, output_name, spatialRef=arcpy.SpatialReference(4326)): outputSHP = os.path.join(output_folder, output_name) if geometry_type.lower() == 'point': arcpy.CreateFeatureclass_management(output_folder, output_name, "MULTIPOINT", "", "DISABLED", "DISABLED", spatialRef) cursor = arcpy.da.InsertCursor(outputSHP, ['SHAPE@']) cursor.insertRow([ arcpy.Multipoint( arcpy.Array([arcpy.Point(*coords) for coords in pntCoords]), spatialRef) ]) elif geometry_type.lower() == 'polyline': arcpy.CreateFeatureclass_management(output_folder, output_name, "POLYLINE", "", "DISABLED", "DISABLED", spatialRef) cursor = arcpy.da.InsertCursor(outputSHP, ['SHAPE@']) cursor.insertRow([ arcpy.Polyline( arcpy.Array([arcpy.Point(*coords) for coords in pntCoords]), spatialRef) ]) elif geometry_type.lower() == 'polygon': arcpy.CreateFeatureclass_management(output_folder, output_name, "POLYGON", "", "DISABLED", "DISABLED", spatialRef) cursor = arcpy.da.InsertCursor(outputSHP, ['SHAPE@']) cursor.insertRow([ arcpy.Polygon( arcpy.Array([arcpy.Point(*coords) for coords in pntCoords]), spatialRef) ]) del cursor return outputSHP
p = re.compile(re_pattern) a = [] for i in liste_of_groupings: m = p.findall(i) a.append([int(m[0]), float(m[1].replace('</UND>', ''))]) b = sorted(a, key=lambda l: (l[0], l[1]), reverse=False) print t.incremental_runtime() f = open(ScriptRunFolder + '/Output/DataExtract_' + datetime.datetime.today().strftime('%y%m%d%H%M') + '.txt', 'w') for en, r in enumerate(list(set([row[0] for row in f_data]))): inner_temp = [row for row in f_data if row[0] == r] coordinates = [[row[2], row[3]] for row in inner_temp] coordinate_min = inner_temp[0][2:4] arcpy.MakeFeatureLayer_management(gdblocation + "/Annotation", "Annotation_001") arcpy.SelectLayerByLocation_management('Annotation_001', "WITHIN_A_DISTANCE", arcpy.Multipoint(arcpy.Array([arcpy.Point(*coords) for coords in coordinates])), 5) annoQueryResult = [[row[0], row[1]] for row in arcpy.da.SearchCursor('Annotation_001', ["Layer", "TextString"])] Chainage = [] for q in annoQueryResult: if q[0] == CrossSectionIdentifier: m2 = p.findall(q[1]) Chainage.append([int(m2[0]), float(m2[1].replace('</UND>', ''))]) print 'Length of Chainge is :: ', len(Chainage) # arcpy.SelectLayerByLocation_management(gdblocation + "\\Annotation", "WITHIN_A_DISTANCE", arcpy.Multipoint(arcpy.Array([arcpy.Point(*coords) for coords in coordinates])), 5) f.write("1\n%s\n" % NameOftheCrossSection) f.write("%20.3lf" % (Chainage[0][0] * 1000 + Chainage[0][1])) coordinate_max = inner_temp[-1][2:4] f.write("\nCOORDINATES\n %s %12.3lf %12.3lf %12.3lf %12.3lf\n" % ( StreamIdentifier, coordinate_min[0], coordinate_min[1], coordinate_max[0], coordinate_max[1])) f.write( "FLOW DIRECTION\n 0 \nPROTECT DATA\n 0 \nDATUM\n 0.00\nRADIUS TYPE\n 0\nDIVIDE X-Section\n0\nSECTION ID\n")
def createOrderGeometry(self, order_obj, projection, buffsize): arcpy.env.overwriteOutput = True point = arcpy.Point() array = arcpy.Array() sr = arcpy.SpatialReference() sr.factoryCode = 4269 # requires input geometry is in 4269 sr.XYTolerance = .00000001 sr.scaleFactor = 2000 sr.create() featureList = [] for feature in json.loads( order_obj.geometry.JSON).values()[0]: # order coordinates # For each coordinate pair, set the x,y properties and add to the Array object. for coordPair in feature: try: point.X = coordPair[0] point.Y = coordPair[1] except: point.X = feature[0] point.Y = feature[1] sr.setDomain(point.X, point.X, point.Y, point.Y) array.add(point) if order_obj.geometry.type.lower( ) == 'point' or order_obj.geometry.type.lower() == 'multipoint': feat = arcpy.Multipoint(array, sr) elif order_obj.geometry.type.lower() == 'polyline': feat = arcpy.Polyline(array, sr) else: feat = arcpy.Polygon(array, sr) array.removeAll() # Append to the list of Polygon objects featureList.append(feat) arcpy.CopyFeatures_management(featureList, cfg.orderGeometry) arcpy.Project_management(cfg.orderGeometry, cfg.orderGeometryPR, projection) del point del array # create buffer if order_obj.geometry.type.lower() == 'polygon' and float( buffsize) == 0: buffsize = "0.001" # for polygon no buffer orders, buffer set to 1m, to avoid buffer clipping error elif float(buffsize ) < 0.01: # for site orders, usually has a radius of 0.001 buffsize = "0.25" # set the FIP search radius to 250m bufferDistance = buffsize + " KILOMETERS" if order_obj.geometry.type.lower( ) == "polygon" and order_obj.radius_type.lower() == "centre": # polygon order, buffer from Centre instead of edge # completely change the order geometry to the center point centreSHP = self.centreFromPolygon( cfg.orderGeometryPR, arcpy.Describe(cfg.orderGeometryPR).spatialReference) if bufferDistance > 0.001: # cause a fail for (polygon from center + no buffer) orders arcpy.Buffer_analysis(centreSHP, cfg.outBufferSHP, bufferDistance) else: arcpy.Buffer_analysis(cfg.orderGeometryPR, cfg.outBufferSHP, bufferDistance)
srGCS83 = arcpy.SpatialReference(4269) #create the center point shapefile, for positioning point = arcpy.Point() array = arcpy.Array() sr = arcpy.SpatialReference() sr.factoryCode = 4269 # requires input geometry is in 4269 sr.XYTolerance = .00000001 sr.scaleFactor = 2000 sr.create() featureList = [] point.X = float(long_center) point.Y = float(lat_center) sr.setDomain(point.X, point.X, point.Y, point.Y) array.add(point) feat = arcpy.Multipoint(array, sr) # Append to the list of Polygon objects featureList.append(feat) orderCenter = os.path.join(scratch, "orderCenter.shp") arcpy.CopyFeatures_management(featureList, orderCenter) arcpy.DefineProjection_management(orderCenter, srGCS83) del point, array, feat, featureList point = arcpy.Point() array = arcpy.Array() sr = arcpy.SpatialReference() sr.factoryCode = 4269 # requires input geometry is in 4269 sr.XYTolerance = .00000001 sr.scaleFactor = 2000 sr.create()
elif fil['fields'][field_counter]['type'] == 'Geometry': points = arcpy.Array() for j in i['coordinates']: part = arcpy.Array() for k in j: if k['x'] != None and k['y'] != None: pt = arcpy.Point(k['x'], k['y'], k['z'], k['m']) part.add(pt) points.add(part) if i['type'] == 'polygon': geometria = arcpy.Polygon(points) elif i['type'] == 'polyline': geometria = arcpy.Polyline(points) elif i['type'] == 'point': geometria = arcpy.PointGeometry(pt) elif i['type'] == 'multipoint': geometria = arcpy.Multipoint(points) else: arcpy.AddError( 'Typ geometrii niewspierany przez program. Program konczy dzialanie.' ) row.setValue(file_fieldname_list[field_counter], geometria) cur.updateRow(row) field_counter += 1 cur.updateRow(row) row_counter += 1 del row, cur arcpy.AddMessage("Ukonczono zapis danych z kopii zapasowej dla pliku " + filename)
array.add(point1) if row[12] != '': if row[13] != '': point2 = arcpy.Point((float(row[13])), (float(row[12]))) array.add(point2) if row[15] != '': if row[16] != '': point3 = arcpy.Point((float(row[16])), (float(row[15]))) array.add(point3) if len(array) == 3: ptGeo = arcpy.Multipoint(array) validPointCount += 1 i = -1 for field in fields: ## print field if i < 0: iRow.append(ptGeo) ## print ptGeo i += 1 else: iRow.append(row[i]) ## print row[i] i += 1 if len(iRow) > 0:
def _build_geom(self): arr = [] for v in self._vertices: arr.append(arcpy.Point(**v.kw)) self._shape = arcpy.Multipoint(arcpy.Array(arr))
def createHull(pDict, outCaseField, lastValue, kStart, dictCount, includeNull): # Value of k must result in enclosing all data points; create condition flag enclosesPoints = False notNullGeometry = False k = kStart if dictCount > 1: pList = [arcpy.Point(xy[0], xy[1]) for xy in pDict.values()] mPoint = arcpy.Multipoint(arcpy.Array(pList), sR) minY = min([xy[1] for xy in pDict.values()]) while not enclosesPoints and k <= 30: arcpy.AddMessage("Finding hull for k = " + str(k)) # Find start point (lowest Y value) startOID = [ id for id in pDict.keys() if pDict[id][1] == minY ][0] # Select the next point (rightmost turn from horizontal, from start point) kOIDList = kNeighbours(k, startOID, pDict, []) minATAN = min([ math.atan2(pDict[id][1] - pDict[startOID][1], pDict[id][0] - pDict[startOID][0]) for id in kOIDList ]) nextOID = [ id for id in kOIDList if math.atan2(pDict[id][1] - pDict[startOID][1], pDict[id][0] - pDict[startOID][0]) == minATAN ][0] # Initialise the boundary array bArray = arcpy.Array( arcpy.Point(pDict[startOID][0], pDict[startOID][1])) bArray.add( arcpy.Point(pDict[nextOID][0], pDict[nextOID][1])) # Initialise current segment lists currentOID = nextOID prevOID = startOID # Initialise list to be excluded from candidate consideration (start point handled additionally later) excludeList = [startOID, nextOID] # Build the boundary array - taking the closest rightmost point that does not cause a self-intersection. steps = 2 while currentOID <> startOID and len(pDict) <> len( excludeList): try: angle = math.atan2( (pDict[currentOID][1] - pDict[prevOID][1]), (pDict[currentOID][0] - pDict[prevOID][0])) oidList = kNeighbours(k, currentOID, pDict, excludeList) nextOID = Rightmost(currentOID, 0 - angle, pDict, oidList) pcArray = arcpy.Array([arcpy.Point(pDict[currentOID][0], pDict[currentOID][1]), \ arcpy.Point(pDict[nextOID][0], pDict[nextOID][1])]) while arcpy.Polyline(bArray, sR).crosses( arcpy.Polyline(pcArray, sR)) and len(oidList) > 0: # arcpy.AddMessage("Rightmost point from " + str(currentOID) + " : " + str(nextOID) + " causes self intersection - selecting again") excludeList.append(nextOID) oidList.remove(nextOID) oidList = kNeighbours(k, currentOID, pDict, excludeList) if len(oidList) > 0: nextOID = Rightmost( currentOID, 0 - angle, pDict, oidList) # arcpy.AddMessage("nextOID candidate: " + str(nextOID)) pcArray = arcpy.Array([arcpy.Point(pDict[currentOID][0], pDict[currentOID][1]), \ arcpy.Point(pDict[nextOID][0], pDict[nextOID][1])]) bArray.add( arcpy.Point(pDict[nextOID][0], pDict[nextOID][1])) prevOID = currentOID currentOID = nextOID excludeList.append(currentOID) # arcpy.AddMessage("CurrentOID = " + str(currentOID)) steps += 1 if steps == 4: excludeList.remove(startOID) except ValueError: arcpy.AddMessage( "Zero reachable nearest neighbours at " + str(pDict[currentOID]) + " , expanding search") break # Close the boundary and test for enclosure bArray.add( arcpy.Point(pDict[startOID][0], pDict[startOID][1])) pPoly = arcpy.Polygon(bArray, sR) if pPoly.length == 0: break else: notNullGeometry = True if mPoint.within(arcpy.Polygon(bArray, sR)): enclosesPoints = True else: arcpy.AddMessage( "Hull does not enclose data, incrementing k") k += 1 # if not mPoint.within(arcpy.Polygon(bArray, sR)): arcpy.AddWarning( "Hull does not enclose data - probable cause is outlier points" ) # Insert the Polygons if (notNullGeometry and includeNull == False) or includeNull: if outCaseField > " ": insFields = [ outCaseField, "POINT_CNT", "ENCLOSED", "SHAPE@" ] else: insFields = ["POINT_CNT", "ENCLOSED", "SHAPE@"] rows = arcpy.da.InsertCursor(outFC, insFields) row = [] if outCaseField > " ": row.append(lastValue) row.append(dictCount) if notNullGeometry: row.append(enclosesPoints) row.append(arcpy.Polygon(bArray, sR)) else: row.append(-1) row.append(None) rows.insertRow(row) del row del rows elif outCaseField > " ": arcpy.AddMessage("\nExcluded Null Geometry for case value " + str(lastValue) + "!") else: arcpy.AddMessage("\nExcluded Null Geometry!")
# unit = " KILOMETERS" sr.factoryCode = 4269 sr.XYTolerance = .00000001 sr.scaleFactor = 2000 sr.create() featureList = [] for feature in OrderCoord: # For each coordinate pair, set the x,y properties and add to the Array object. for coordPair in feature: point.X = coordPair[0] point.Y = coordPair[1] sr.setDomain(point.X, point.X, point.Y, point.Y) array.add(point) if OrderType.lower() == 'point': feaERIS = arcpy.Multipoint(array, sr) elif OrderType.lower() == 'polyline': feaERIS = arcpy.Polyline(array, sr) else: feaERIS = arcpy.Polygon(array, sr) array.removeAll() # Append to the list of Polygon objects featureList.append(feaERIS) # Create a copy of the Polygon objects, by using featureList as input to the CopyFeatures tool. outshp = os.path.join(scratch, "orderGeoName.shp") #outshp = r"in_memory/orderGeoName" arcpy.CopyFeatures_management(featureList, outshp) arcpy.DefineProjection_management(outshp, srGCS83)
def from_featureclass(filename, **kwargs): """ Returns a GeoDataFrame from a feature class. Inputs: filename: full path to the feature class Optional Parameters: sql_clause: sql clause to parse data down where_clause: where statement sr: spatial reference object fields: list of fields to extract from the table """ from .. import SpatialDataFrame from arcgis.geometry import _types if HASARCPY: sql_clause = kwargs.pop('sql_clause', (None,None)) where_clause = kwargs.pop('where_clause', None) sr = kwargs.pop('sr', arcpy.Describe(filename).spatialReference or arcpy.SpatialReference(4326)) fields = kwargs.pop('fields', None) desc = arcpy.Describe(filename) if not fields: fields = [field.name for field in arcpy.ListFields(filename) \ if field.type not in ['Geometry']] if hasattr(desc, 'areaFieldName'): afn = desc.areaFieldName if afn in fields: fields.remove(afn) if hasattr(desc, 'lengthFieldName'): lfn = desc.lengthFieldName if lfn in fields: fields.remove(lfn) geom_fields = fields + ['SHAPE@'] flds = fields + ['SHAPE'] vals = [] geoms = [] geom_idx = flds.index('SHAPE') shape_type = desc.shapeType default_polygon = _types.Geometry(arcpy.Polygon(arcpy.Array([arcpy.Point(0,0)]* 3))) default_polyline = _types.Geometry(arcpy.Polyline(arcpy.Array([arcpy.Point(0,0)]* 2))) default_point = _types.Geometry(arcpy.PointGeometry(arcpy.Point())) default_multipoint = _types.Geometry(arcpy.Multipoint(arcpy.Array([arcpy.Point()]))) with arcpy.da.SearchCursor(filename, field_names=geom_fields, where_clause=where_clause, sql_clause=sql_clause, spatial_reference=sr) as rows: for row in rows: row = list(row) # Prevent curves/arcs if row[geom_idx] is None: row.pop(geom_idx) g = {} elif row[geom_idx].type in ['polyline', 'polygon']: g = _types.Geometry(row.pop(geom_idx).generalize(0)) else: g = _types.Geometry(row.pop(geom_idx)) if g == {}: if shape_type.lower() == 'point': g = default_point elif shape_type.lower() == 'polygon': g = default_polygon elif shape_type.lower() == 'polyline': g = default_point elif shape_type.lower() == 'multipoint': g = default_multipoint geoms.append(g) vals.append(row) del row del rows df = pd.DataFrame(data=vals, columns=fields) sdf = SpatialDataFrame(data=df, geometry=geoms) sdf.reset_index(drop=True, inplace=True) del df if sdf.sr is None: if sr is not None: sdf.sr = sr else: sdf.sr = sdf.geometry[sdf.geometry.first_valid_index()].spatialReference return sdf elif HASARCPY == False and \ HASPYSHP == True and\ filename.lower().find('.shp') > -1: geoms = [] records = [] reader = shapefile.Reader(filename) fields = [field[0] for field in reader.fields if field[0] != 'DeletionFlag'] for r in reader.shapeRecords(): atr = dict(zip(fields, r.record)) g = r.shape.__geo_interface__ g = _geojson_to_esrijson(g) geom = _types.Geometry(g) atr['SHAPE'] = geom records.append(atr) del atr del r, g del geom sdf = SpatialDataFrame(records) sdf.set_geometry(col='SHAPE') sdf.reset_index(inplace=True) return sdf elif HASARCPY == False and \ HASPYSHP == False and \ HASFIONA == True and \ (filename.lower().find('.shp') > -1 or \ os.path.dirname(filename).lower().find('.gdb') > -1): is_gdb = os.path.dirname(filename).lower().find('.gdb') > -1 if is_gdb: with fiona.drivers(): from arcgis.geometry import _types fp = os.path.dirname(filename) fn = os.path.basename(filename) geoms = [] atts = [] with fiona.open(path=fp, layer=fn) as source: meta = source.meta cols = list(source.schema['properties'].keys()) for idx, row in source.items(): geoms.append(_types.Geometry(row['geometry'])) atts.append(list(row['properties'].values())) del idx, row df = pd.DataFrame(data=atts, columns=cols) return SpatialDataFrame(data=df, geometry=geoms) else: with fiona.drivers(): from arcgis.geometry import _types geoms = [] atts = [] with fiona.open(path=filename) as source: meta = source.meta cols = list(source.schema['properties'].keys()) for idx, row in source.items(): geoms.append(_types.Geometry(row['geometry'])) atts.append(list(row['properties'].values())) del idx, row df = pd.DataFrame(data=atts, columns=cols) return SpatialDataFrame(data=df, geometry=geoms) return
def ReadSarmap(sGeoLocPath, sScenarioName, sFGDB): reader = SarmapReader(sGeoLocPath + os.path.sep + "OUTDATA" + os.path.sep + sScenarioName) SarMode = reader.GetSarMode() sSDEpath = r"C:\oilmap\Push2ESRI\database.sde" splt, trk, abcd_table, abcdpt, area = PrepFCs(sSDEpath) time_stamp = reader.GetSRPSetting('TimeStamp') lons = [] #list for each time step to avg for track points lats = [] trkline = arcpy.Array() start_time = None end_time = None for timestep in xrange(0, reader.time_steps): d_time = CalculateDateTime(reader._record_data['sim_time'][timestep]) if (timestep == 0): start_time = d_time elif (timestep == reader.time_steps - 1): end_time = d_time spillet_data = reader._load_timestep(timestep) lons[:] = [] lats[:] = [] abcd = arcpy.Array() xmin = 9999 ymin = 9999 xmax = -9999 ymax = -9999 areapts = arcpy.Array() vertex = ['A', 'B', 'C', 'D'] curr_vertex = 0 for spillet in spillet_data[1:]: if spillet['nwhere'] <= 10: lon = float(spillet['loc'][0]) lons.append(lon) lat = float(spillet['loc'][1]) lats.append(lat) particle_type = int(spillet[2]) particle_description = reader.GetSRPSetting( 'SAR Object' if particle_type == 1 else 'SAR Object_' + str(particle_type)) pnt = arcpy.Point() pnt.X = lon pnt.Y = lat splt_cur = arcpy.da.InsertCursor( splt, ['SHAPE@', 'DATETIME', 'SCENARIO', 'TYPE']) splt_cur.insertRow( [pnt, d_time, sScenarioName, particle_description]) del splt_cur areapts.add(pnt) xmin = min(xmin, lon) ymin = min(ymin, lat) xmax = max(xmax, lon) ymax = max(ymax, lat) elif spillet['nwhere'] == 24: lon = float(spillet['loc'][0]) lat = float(spillet['loc'][1]) abcdpnt = arcpy.Point(lon, lat) abcd.add(abcdpnt) abcdpt_cur = arcpy.da.InsertCursor( abcdpt, ['SHAPE@', 'DATETIME', 'SCENARIO', 'VERTEX']) abcdpt_cur.insertRow( [abcdpnt, d_time, sScenarioName, vertex[curr_vertex]]) del abcdpt_cur curr_vertex += 1 if (SarMode != '0'): areapoly = arcpy.Multipoint(areapts) convex = areapoly.convexHull() area_cur = arcpy.da.InsertCursor( area, ['SHAPE@', 'SCENARIO', 'DATETIME']) area_cur.insertRow([convex, sScenarioName, d_time]) del area_cur lon_avg = (xmin + xmax) / 2 lat_avg = (ymin + ymax) / 2 trkline.add(pnt) abcdbox = arcpy.Polygon(abcd) abcd_cur = arcpy.da.InsertCursor(abcd_table, ['SHAPE@', 'SCENARIO', 'DATETIME']) abcd_cur.insertRow([abcdbox, sScenarioName, d_time]) del abcd_cur interval_hrs = int(reader.GetSRPSetting('Ideltat')) / 60 original_case = reader.GetSRPSetting('OriginalCase') site_lon = float(reader.GetSRPSetting('Spill Lon')) site_lat = float(reader.GetSRPSetting('Spill Lat')) description = reader.GetSRPSetting('Description') trackline = arcpy.Polyline(trkline) trk_cur = arcpy.da.InsertCursor(trk, [ 'SHAPE@', 'START', 'END_', 'INTERVAL_HRS', 'SCENARIO', 'SCENARIO_ID', 'SITELON', 'SITELAT', 'DESCRIPTION', 'CASENAME' ]) trk_cur.insertRow([ trackline, start_time, end_time, interval_hrs, sScenarioName, sScenarioName, site_lon, site_lat, description, original_case ]) del trk_cur
outConvexHull = r"" outputJoin = r"" serviceAreas = r"" print("Variables are set.") #Append coordinates from csv in a list outageCoords = [] csvFile = open(outageXY) csvReader = csv.reader(csvFile) next(csvReader) for row in csvReader: outageCoords.append(row) #Create a multipoint geometry object from list of coordinates #Takes outageCoords and * splits the list into comma sep. values to be passed to the Point Class Constructor Method outagePoints = (arcpy.Multipoint( arcpy.Array([arcpy.Point(*coords) for coords in outageCoords]))) print("Geometry object created.") #Create outage boundary using convex hull #Use Spatial Join to identify affected areas arcpy.SpatialJoin_analysis(serviceAreas, outagePoints, outputJoin) print("Spatial join finished.") #Search join output sFields = ['Join_Count', 'ServArNu'] exp = '"Join_Count" = 1' print("Affected service areas") with arcpy.da.SearchCursor(outputJoin, sFields, exp) as sCursor: for row in sCursor: print("Service Area: {}".format(row[1]))