M, Z, NS, EW = line.split() point.Z = float(Z) * -1 point.X = XStart + float(EW) point.Y = YStart + float(NS) point.M = float(M) array.add(point) APIsave = str(x[:-4]) # Create and add polyline to shapefile workspace = os.path.dirname(lateralfc) edit = arcpy.da.Editor(workspace) edit.startEditing() edit.startOperation() cursor = arcpy.da.InsertCursor(lateralfc, ["SHAPE@", "API", "DateCreated"]) line = arcpy.Polyline(array, None, True) cursor.insertRow([line, APIsave, date]) del cursor array.removeAll() f.close() print str(APIsave) + " Lateral Created" f.close() edit.stopOperation() edit.stopEditing(True) if invalidAPIList == []: print("All files converted") else: print("These files were not converted") print invalidAPIList
def LeesSOIL(Soil): arcpy.AddMessage(" >>> ----------------------------------") arcpy.AddMessage(" >>> Uitlezen: " + Soil) arcpy.AddMessage(" >>> ----------------------------------") #--------------------------------------------------------- # ---- START ---- #--------------------------------------------------------- # Uit te lezen tabellen en structuur uitleg: # # Hier kijken welk ME_ID is Piping # tabel: main.Mechanism uit te lezen kolommen: ME_ID en ME_Name (daar waar deze = Piping die gebruiken) # # Dan hier kijken welke Segmenten bij Piping horen # tabel: main.Segment uit te lezen kolommen: SE_ID, ME_ID, SSM_ID, SE_Name ( # # in onderstaande 2 tabellen de Naam en het aantal 1D profielen uit lezen. # tabel: main.StochasticSoilProfile uit te lezen kolommen: SSM_ID en SP1D_ID # tabel: main.StochasticSoilModel uit te lezen kolommen: SSM_ID en SSM_Name(is de ondergrondmodelnaam) # # In onderstaande tabel de namen van de profielen uitlezen. # tabel: main.SoilProfile1D uit te lezen kolommen: SP1D_ID en SP1D_Name(is de segment naam) # # Nog geen foutafhandeling ingebouwd om te kijken of het wel een sqlite bestand is # import sqlite3 conn = sqlite3.connect(Soil) cursor = conn.cursor() #------------------ # Lege lijnen shape aanmaken voor lijnID = 0 LijnLijst = arcpy.Array() # de uitvoer FC oSoil_ln = "Seg_" + arcpy.Describe(Soil).file.replace(".", "_").replace( "-", "_") try: arcpy.CreateFeatureclass_management( out_path=workspace, out_name=oSoil_ln, geometry_type="POLYLINE", template="", has_m="DISABLED", has_z="DISABLED", spatial_reference= "PROJCS['RD_New',GEOGCS['GCS_Amersfoort',DATUM['D_Amersfoort',SPHEROID['Bessel_1841',6377397.155,299.1528128]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]],PROJECTION['Double_Stereographic'],PARAMETER['False_Easting',155000.0],PARAMETER['False_Northing',463000.0],PARAMETER['Central_Meridian',5.38763888888889],PARAMETER['Scale_Factor',0.9999079],PARAMETER['Latitude_Of_Origin',52.15616055555555],UNIT['Meter',1.0]];-30515500 -30279500 10000;-100000 10000;-100000 10000;0.001;0.001;0.001;IsHighPrecision" ) except: print "is er al" UitSoil = workspace + "/" + oSoil_ln try: arcpy.AddField_management(UitSoil, "SE_ID", "SHORT") except: arcpy.AddError("Kolom SE_ID bestaat al!") try: arcpy.AddField_management(UitSoil, "SE_NAME", "TEXT", "", "", 100) except: arcpy.AddError("Kolom SE_NAME bestaat al!") #------------------ # cursor openen insert_cursor = arcpy.da.InsertCursor(UitSoil, ["SHAPE@", "SE_ID", "SE_NAME"]) #------------------ MEid = 0 # Het id van Piping komt in deze variabele cursor.execute( "SELECT ME_ID, ME_Name FROM Mechanism WHERE ME_Name = 'Piping'") for row0 in cursor.fetchall(): MEid = row0[0] del row0 #------------------ StochastModel = [] # hier komt het eindmodel in. cursor.execute( "SELECT SE_ID, ME_ID, SSM_ID, SE_Name FROM Segment WHERE ME_ID = '" + str(MEid) + "' ORDER BY SSM_ID") for row1 in cursor.fetchall(): SSMlijst = [] # De lijst met nummer en modelnamen SSMlijst.append(row1[0]) SSMid = row1[2] SEid = row1[0] SEnaam = row1[3] #------------------ # de lijn uittekenen LijnLijst = arcpy.Array() cursor.execute( "SELECT SE_ID, Xworld, Yworld FROM SegmentPoints WHERE SE_ID = '" + str(SEid) + "' ORDER BY SEGP_ID") for XYrow in cursor.fetchall(): P = arcpy.Point(XYrow[1], XYrow[2]) LijnLijst.add(P) polyline = arcpy.Polyline(LijnLijst) #-- wegschrijven insert_cursor.insertRow((polyline, float(SEid), SEnaam)) LijnLijst.removeAll() #------------------ cursor.execute( "SELECT SSM_ID, SSM_Name FROM StochasticSoilModel WHERE SSM_ID = '" + str(SSMid) + "'") for row2 in cursor.fetchall(): SSMnaam = row2[1] SP1Dlijst = [] # De lijst met de 1D profielen per segment cursor.execute( "SELECT SSM_ID, SP1D_ID, Probability FROM StochasticSoilProfile WHERE SSM_ID = '" + str(SSMid) + "' ORDER BY SP1D_ID") for row3 in cursor.fetchall(): SP1D = row3[1] SP1Dk = row3[2] * 100 # de kans binnen het scenario cursor.execute( "SELECT SP1D_ID, SP1D_Name FROM SoilProfile1D WHERE SP1D_ID = '" + str(SP1D) + "'") for row4 in cursor.fetchall(): SP1Dlijst.append([row4[1], SP1Dk]) # Kans meenemen StochastModel.append([SSMnaam, SP1Dlijst]) cursor.close() del insert_cursor #--- return (StochastModel, UitSoil)
def Find_Error_Lines(path, ws, gdb): path_ARC = gdb + '\\' + 'PARCEL_ARC_EDIT' tazar = ws + '\\' + 'tazar_border' error_line = ws + '\\' + 'Errors_Line' deleteErrorCode(error_line, ["7"]) # temp Layers new_point = gdb + '\\' + 'JunctionsParcels' POINT_ARC = gdb + '\\' + 'Junctions_ARCS' temp_inter = r'in_memory\intersect' stubbern_arc_bool = Check_if_Stubbern_Arc(path, path_ARC, tazar) # Create missing pnts vertex if stubbern_arc_bool: print_arcpy_message( "Tool May have Found stubbern arc, Checking and fixing", status=1) prob_misse = gdb + '\\' + 'prob_misse' parcels = Junctions(path, new_point, "Jun_parcel") arcs = Junctions(path_ARC, POINT_ARC, "Jun_Arc") arcpy.MakeFeatureLayer_management(new_point, 'new_point_lyr') arcpy.SelectLayerByLocation_management('new_point_lyr', 'INTERSECT', POINT_ARC, '', "NEW_SELECTION", "INVERT") arcpy.SelectLayerByLocation_management('new_point_lyr', 'WITHIN_A_DISTANCE', tazar, '250 Meters', "REMOVE_FROM_SELECTION", "INVERT") arcpy.SelectLayerByLocation_management('new_point_lyr', "COMPLETELY_WITHIN", path_ARC, '', "REMOVE_FROM_SELECTION") arcpy.Select_analysis('new_point_lyr', prob_misse) Smallest_dis(prob_misse) ID_geom = { i[0]: i[1] for i in arcpy.da.SearchCursor(prob_misse, ["OBJECTID", "SHAPE@"]) } line = arcpy.CreateFeatureclass_management(gdb, 'line_new', 'POLYLINE') fields = ["KEY", "KEY2", "dis"] for i in fields: add_field(line, i) Point_cur = arcpy.SearchCursor(prob_misse) for row in Point_cur: if row.Dis != None: cursor = arcpy.InsertCursor(line, ['OBJECTID', 'KEY2', 'Dis']) array = arcpy.Array() shape = row.shape X1 = shape.centroid.X Y1 = shape.centroid.Y X2 = ID_geom[int(row.KEY2)].centroid.X Y2 = ID_geom[int(row.KEY2)].centroid.Y array.add(arcpy.Point(X1, Y1)) array.add(arcpy.Point(X2, Y2)) polyline = arcpy.Polyline(array) in_row = cursor.newRow() in_row.KEY = str(row.OBJECTID) in_row.Dis = str(row.Dis) in_row.KEY2 = str(row.KEY2) in_row.shape = polyline cursor.insertRow(in_row) del cursor arcpy.Delete_management(new_point) arcpy.Delete_management(POINT_ARC) arcpy.Delete_management(prob_misse) arcpy.MakeFeatureLayer_management(line, 'Line_del', "\"SHAPE_Length\" > 1") arcpy.SelectLayerByLocation_management('Line_del', "SHARE_A_LINE_SEGMENT_WITH", path, '', "NEW_SELECTION", "INVERT") arcpy.DeleteFeatures_management('Line_del') num_found = int(str(arcpy.GetCount_management(line))) if num_found > 0: Calc_field_value_error(line, error_line, "7", ErrorDictionary["7"]) print_arcpy_message("Tool Found: {} stubbern arcs".format( str(num_found)), status=2) else: print_arcpy_message("No stubbern arcs found", status=1)
def create_traverse_terrestrial_vector(self, stations, terrestrial_observations, output_gdb_path, output_vector_path): template_terrestrial_traverse = r'U:\scratch-workplace\control-network\data\wrk\control-network-template.gdb\terrestrial_traverse' feature_dataset_name = os.path.dirname(output_vector_path) polyline_name = os.path.basename(output_vector_path) arcpy.CreateFeatureclass_management(feature_dataset_name, polyline_name, 'POLYLINE', has_z = 'ENABLED', template = template_terrestrial_traverse) print '%s created' % output_vector_path #feature_class_definitions.add_fields(output_terrestrial_traverse_polyline_path, # feature_class_definitions.traverse_terrestrial_vector_field_definitions) with arcpy.da.InsertCursor(output_vector_path, ['SHAPE@', 'NET_TAG', 'NET_TYPE', 'OBS_TYPE', 'INSTRUMENT_PT', 'BACKSIGHT_PT', 'FORESIGHT_PT', 'HORIZ_ANGLE', 'HORIZ_ANGLE_STND_ERR', 'ZENITH_ANGLE', 'ZENITH_ANGLE_STND_ERR', 'SLOPE_DIST', 'SLOPE_DIST_STND_ERR', 'PRISM_CONSTANT', 'INSTRUMENT_HEIGHT', 'TARGET_HEIGHT']) as in_cursor: for observation in terrestrial_observations: if observation.instrument_point in stations.keys() and \ observation.backsight_point in stations.keys() and \ observation.foresight_point in stations.keys(): start_point = stations[observation.instrument_point] end_point = stations[observation.foresight_point] start_point_gis = arcpy.Point(start_point.local_easting, start_point.local_northing, start_point.local_elevation) end_point_gis = arcpy.Point(end_point.local_easting, end_point.local_northing, end_point.local_elevation) point_array = arcpy.Array() point_array.add(start_point_gis) point_array.add(end_point_gis) traverse_vector = arcpy.Polyline(point_array, template_spatial_reference) net_tag = str(datetime.now().year) net_type = 'Tertiary' obs_type = 'Terrestrial' traverse_vector.projectAs(arcpy.SpatialReference(6404)) in_cursor.insertRow([traverse_vector, net_tag, net_type, obs_type, observation.instrument_point, observation.backsight_point, observation.foresight_point, observation.horizontal_angle, observation.horizontal_angle_standard_error, observation.zenith_angle, observation.zenith_angle_standard_error, observation.slope_distance, observation.slope_distance_error, observation.prism_constant, observation.instrument_height, observation.target_height]) return
line_seg = arcpy.Array() featurelist = [] cursor = arcpy.InsertCursor(trace_outpath) feat = cursor.newRow() for i in range(1, len(coords)-1): # Set X and Y for start and end points point.X = coords[i-1][0] point.Y = coords[i-1][1] line_seg.add(point) point.X = coords[i][0] point.Y = coords[i][1] line_seg.add(point) #Create a polyline object based on the array of points polyline = arcpy.Polyline(line_seg) # Clear the array for future use line_seg.removeAll() #Append to the list of polyline objects featurelist.append(polyline) #Insert the feature feat.shape = polyline cursor.insertRow(feat) del feat del cursor
def onMouseDownMap(self, x, y, button, shift): epNew = None ep = arcpy.Point(x, y) numberOfSegments = len(GenInfo.Feature['Segments']) snappedToExistingFeature = False '''Perform the snap functionality & Save coordinates in RDF dictionary''' if numberOfSegments <> 0: for featureInfo in GenInfo.Feature['Segments']: try: startPoint = arcpy.PointGeometry( arcpy.Point(featureInfo['StartP'][0], featureInfo['StartP'][1])) except: startPoint = arcpy.PointGeometry( featureInfo['LineGeometry'].firstPoint) distanceEP = startPoint.distanceTo(ep) if 0 < distanceEP < 5: epNew = startPoint.getPart(0) snappedToExistingFeature = True if snappedToExistingFeature == False: if arcpy.Describe(GenInfo.selectLayer).shapeType == 'Polygon': ring = ReadGeometry(GenInfo.selectLayer) dis = [] for r in ring: a = arcpy.Polyline( arcpy.Array([arcpy.Point(*coords) for coords in r])) dis.append(a.distanceTo(arcpy.Point(ep.X, ep.Y))) loc = dis.index(min(dis)) polygonToPolyline = arcpy.Polyline( arcpy.Array([arcpy.Point(*coord) for coord in ring[loc]])) epNew = polygonToPolyline.snapToLine(ep).getPart() else: epNew = GenInfo.selectedFeature.snapToLine(ep).getPart() '''Visualize the point''' fc = 'Point' path = GenInfo.workpath + '\TestTD.gdb' # Start an edit session. Require the workspace edit = arcpy.da.Editor(path) # Edit session is started without an undo/redo stack for versioned data # (for second argument, use False for unversioned data) edit.startEditing(True) # Start an edit operation edit.startOperation() if epNew is not None: GenInfo.SelDict['EndP'] = (epNew.X, epNew.Y) rowValue = [(epNew.X, epNew.Y)] else: GenInfo.SelDict['EndP'] = (ep.X, ep.Y) rowValue = [(ep.X, ep.Y)] cursor = arcpy.da.InsertCursor(fc, 'SHAPE@XY') cursor.insertRow(rowValue) # Stop the edit operation. edit.stopOperation() # Stop the edit session and save the changes edit.stopEditing(True) arcpy.RefreshActiveView() if GenInfo.startRing == 1: GenInfo.SelDict['InnerRingNum'] = GenInfo.m '''Assign the component order for the matched thematic component when the selected feature is a polyline''' if arcpy.Describe(GenInfo.selectLayer).shapeType == 'Polyline': GenInfo.SelDict['SegOrder'] = GenInfo.n print GenInfo.SelDict GenInfo.n += 1 GenInfo.Feature['Segments'].append(GenInfo.SelDict) GenInfo.SelDict = { 'BaseURI': 'Inf', 'StartP': 'Inf', 'EndP': 'Inf', 'SegOrder': 'Inf', 'URI': 'Inf' }
def onMouseDownMap(self, x, y, button, shift): numberOfSegments = len(GenInfo.Feature['Segments']) spNew = None sp = arcpy.Point(x, y) '''Perform the snap functionality & Save coordinates in RDF dictionary''' if (numberOfSegments <> 0 and GenInfo.startRing == 0) or ( numberOfSegments - GenInfo.ExteriorSeg > 0 and GenInfo.startRing == 1) or (GenInfo.NextRing == 0 and GenInfo.startRing == 1): try: spNew = arcpy.Point( GenInfo.Feature['Segments'][numberOfSegments - 1]['EndP'][0], GenInfo.Feature['Segments'][numberOfSegments - 1]['EndP'][1]) except: try: spNew = GenInfo.Feature['Segments'][ numberOfSegments - 1]['LineGeometry'].lastPoint except: pass GenInfo.SelDict['StartP'] = (spNew.X, spNew.Y) if numberOfSegments == 0 or ( numberOfSegments - GenInfo.ExteriorSeg == 0 and GenInfo.startRing == 1) or (GenInfo.NextRing == 1 and GenInfo.startRing == 1): if arcpy.Describe(GenInfo.selectLayer).shapeType == 'Polygon': ring = ReadGeometry(GenInfo.selectLayer) dis = [] for r in ring: a = arcpy.Polyline( arcpy.Array([arcpy.Point(*coords) for coords in r])) dis.append(a.distanceTo(arcpy.Point(sp.X, sp.Y))) loc = dis.index(min(dis)) polygonToPolyline = arcpy.Polyline( arcpy.Array([arcpy.Point(*coord) for coord in ring[loc]])) spNew = polygonToPolyline.snapToLine(sp).getPart() else: spNew = GenInfo.selectedFeature.snapToLine(sp).getPart() GenInfo.SelDict['StartP'] = (spNew.X, spNew.Y) '''Visualize the point''' fc = 'Point' path = GenInfo.workpath + '\TestTD.gdb' # Start an edit session. Require the workspace edit = arcpy.da.Editor(path) # Edit session is started without an undo/redo stack for versioned data # (for second argument, use False for unversioned data) edit.startEditing(True) # Start an edit operation edit.startOperation() if spNew is not None: rowValue = [(spNew.X, spNew.Y)] else: GenInfo.SelDict['StartP'] = (sp.X, sp.Y) rowValue = [(sp.X, sp.Y)] cursor = arcpy.da.InsertCursor(fc, 'SHAPE@XY') cursor.insertRow(rowValue) # Stop the edit operation. edit.stopOperation() # Stop the edit session and save the changes edit.stopEditing(True) arcpy.RefreshActiveView()
def MakeERGFeatures(pProjectedPointGeometry, pWindBlowingToDirection, pInitialIsolationDistance, pProtectiveActionDistance, pMaterials, pGuideNum, pSpillSize, pTimeOfDay, pOutAreas, pOutLines, pTemplateLoc): # Creates 3 polygon features in pOutAreas:- # Initial Isolation Zone # Protective Action Zone # Combined Zone # and 3 line features in pOutLines:- # Protective Action Arc # Protective Action Radial (1) # Protective Action Radial (2) # ASSUMPTION: The wind direction is relative to grid north of the projected coordinate system of the supplied point # Convert the supplied distances into meters (if needed) sr = pProjectedPointGeometry.spatialReference metersPerUnit = sr.metersPerUnit arcpy.AddMessage("Meters per map unit: " + str(metersPerUnit)) iiDistanceInSrUnits = pInitialIsolationDistance / metersPerUnit paDistanceInSrUnits = pProtectiveActionDistance / metersPerUnit arcpy.AddMessage("IID: " + str(iiDistanceInSrUnits)) arcpy.AddMessage("PAD: " + str(paDistanceInSrUnits)) # Compute the initial isolation zone # (note the resulting polygon will contain circular arcs, which do not project well, so we will densify later) initialIsolationZone = pProjectedPointGeometry.buffer(iiDistanceInSrUnits) # Given the wind direction and the protective action distance, compute the X and Y components of the associated vector vectorX = paDistanceInSrUnits * math.sin( math.radians(float(pWindBlowingToDirection))) vectorY = paDistanceInSrUnits * math.cos( math.radians(float(pWindBlowingToDirection))) # Get the X and Y values of the spill point originX = pProjectedPointGeometry.firstPoint.X originY = pProjectedPointGeometry.firstPoint.Y # Calculate the 4 corners of the protective action zone paPoint1 = arcpy.Point(originX - vectorY / 2, originY + vectorX / 2) paPoint4 = arcpy.Point(originX + vectorY / 2, originY - vectorX / 2) paPoint2 = arcpy.Point(paPoint1.X + vectorX, paPoint1.Y + vectorY) paPoint3 = arcpy.Point(paPoint4.X + vectorX, paPoint4.Y + vectorY) # Generate the protective action zone array = arcpy.Array([paPoint1, paPoint2, paPoint3, paPoint4, paPoint1]) protectiveActionZone = arcpy.Polygon(array, sr) # Also generate an extended zone for later computation of the protective action arc (to ensure it remains single part) vectorX *= 1.5 vectorY *= 1.5 paPoint2Ext = arcpy.Point(paPoint1.X + vectorX, paPoint1.Y + vectorY) paPoint3Ext = arcpy.Point(paPoint4.X + vectorX, paPoint4.Y + vectorY) arrayExt = arcpy.Array( [paPoint1, paPoint2Ext, paPoint3Ext, paPoint4, paPoint1]) paZoneExt = arcpy.Polygon(arrayExt, sr) # arcpy.Densify_edit(initialIsolationZone, "ANGLE", "", "", "1.0") # Apply trick to densify the initial isolation zone (i.e. to remove circular arcs in case of reprojection of the result) diff = initialIsolationZone.difference(protectiveActionZone) intsct = initialIsolationZone.intersect(protectiveActionZone, 4) initialIsolationZone = diff.union(intsct) # Compute the combined zone (iiz + paz) combinedZone = diff.union(protectiveActionZone) # Compute the "protective action arc" - the arc at the limit of the protective action zone paCircle = pProjectedPointGeometry.buffer(paDistanceInSrUnits) protectiveActionArc = paZoneExt.intersect(paCircle.boundary(), 2) # Compute the "radials" - the lines connecting the edges of the initial isolation zone to the ends of the protective action arc innerArc = protectiveActionZone.intersect(initialIsolationZone.boundary(), 2) radial1Array = arcpy.Array( [innerArc.firstPoint, protectiveActionArc.firstPoint]) radial2Array = arcpy.Array( [innerArc.lastPoint, protectiveActionArc.lastPoint]) protectiveActionRadial1 = arcpy.Polyline(radial1Array, sr) protectiveActionRadial2 = arcpy.Polyline(radial2Array, sr) arcpy.AddMessage("All output geometries have been calculated") # Create the output featureclasses based on the templates outWorkspaceAreas = os.path.dirname(pOutAreas) outAreas = os.path.basename(pOutAreas) outWorkspaceLines = os.path.dirname(pOutLines) outLines = os.path.basename(pOutLines) arcpy.AddMessage("Creating output polygon Feature Class...") arcpy.CreateFeatureclass_management(outWorkspaceAreas, outAreas, "POLYGON", pTemplateLoc + "\\ERGAreas", "DISABLED", "DISABLED", sr) arcpy.AddMessage("...created") arcpy.AddMessage("Creating output line Feature Class...") arcpy.CreateFeatureclass_management(outWorkspaceLines, outLines, "POLYLINE", pTemplateLoc + "\\ERGLines", "DISABLED", "DISABLED", sr) arcpy.AddMessage("...created") # Get the current date/time dtNow = datetime.datetime.now() # Create an insert cursor on pOutAreas and insert the polygon geometries arcpy.AddMessage("Populating output polygon Feature Class...") cursor = arcpy.da.InsertCursor( pOutAreas, ("SHAPE@", "X", "Y", "ERGZone", "Materials", "SpillTimeOfDay", "SpillSize", "DateEntered", "GuideNum")) cursor.insertRow((combinedZone, originX, originY, "Combined Zone", pMaterials, pTimeOfDay, pSpillSize, dtNow, pGuideNum)) cursor.insertRow( (protectiveActionZone, originX, originY, "Protective Action Zone", pMaterials, pTimeOfDay, pSpillSize, dtNow, pGuideNum)) cursor.insertRow( (initialIsolationZone, originX, originY, "Initial Isolation Zone", pMaterials, pTimeOfDay, pSpillSize, dtNow, pGuideNum)) del cursor arcpy.AddMessage("...populated") # Create an insert cursor on pOutLines and insert the polyline geometries arcpy.AddMessage("Populating output line Feature Class...") cur = arcpy.da.InsertCursor( pOutLines, ("SHAPE@", "X", "Y", "LineType", "Materials", "SpillTimeOfDay", "SpillSize", "DateEntered", "GuideNum")) cur.insertRow((protectiveActionArc, originX, originY, "Arc", pMaterials, pTimeOfDay, pSpillSize, dtNow, pGuideNum)) cur.insertRow((protectiveActionRadial1, originX, originY, "Radial", pMaterials, pTimeOfDay, pSpillSize, dtNow, pGuideNum)) cur.insertRow((protectiveActionRadial2, originX, originY, "Radial", pMaterials, pTimeOfDay, pSpillSize, dtNow, pGuideNum)) del cur arcpy.AddMessage("...populated") return
flds = ("SHAPE@", fld_id, fld_dist, fld_id2) with arcpy.da.InsertCursor(fc_linepnt, flds) as curs: # loop over boundary for i in range(0, steps): d = i * interval line_id = i # extract point on buffer outline pnt = polyline.positionAlongLine(d, False) # create line from center to pnt on line arr = arcpy.Array() arr.removeAll arr.add(pnt_cc) arr.add(pnt.firstPoint) line = arcpy.Polyline(arr) # extract points on line for j in range(0, int(steps2)): dist = int(j * pixsize) pnt2 = line.positionAlongLine(dist, False) # add to fc in mem with line ID and eucledian distance val_id = "{0}_{1}".format(line_id, dist) curs.insertRow((pnt2, line_id, dist, val_id)) # extract DEM values fc_linepntdem = os.path.join(ws, fc_linepntdem_name) arcpy.sa.ExtractValuesToPoints(fc_linepnt, dem, fc_linepntdem, "INTERPOLATE", "VALUE_ONLY")
primary = points2 secondary = pointsCenter else: primary = pointsCenter secondary = points2 maxLength = len(primary) arcpy.AddMessage("Computing Right Centerline Vertices...") for i in range(0,maxLength-1): pt = closestPoint(primary[i],secondary) rightCenterLineVertices.append(arcpy.Point((primary[i][0]+pt[0])/2,(primary[i][1]+pt[1])/2)) # Generate the shapefiles for the computed centerline and flow paths featureList = [] centerLine = arcpy.Polyline(centerLineVertices) featureList.append(centerLine) arcpy.CopyFeatures_management(featureList, centerlineOut) arcpy.DefineProjection_management(centerlineOut, sr) featureList = [] leftCenterLine = arcpy.Polyline(leftCenterLineVertices) featureList.append(leftCenterLine) arcpy.CopyFeatures_management(featureList, leftCenterLineOut) arcpy.DefineProjection_management(leftCenterLineOut, sr) featureList = [] rightCenterLine = arcpy.Polyline(rightCenterLineVertices) featureList.append(rightCenterLine) arcpy.CopyFeatures_management(featureList, rightCenterLineOut) arcpy.DefineProjection_management(rightCenterLineOut, sr)
#creates points sc = arcpy.da.SearchCursor(fcPoly, ['SHAPE@XY']) # Get 2 centroids row = sc.next() point1 = arcpy.Point(row[0][0], row[0][1]) print('Point1: ({0},{1})'.format(row[0][0], row[0][1])) row = sc.next() point2 = arcpy.Point(row[0][0], row[0][1]) print('Point2: ({0},{1})'.format(row[0][0], row[0][1])) del (sc) except: print('An error occurred while creating points.') traceback.print_exc() del (sc) try: #creates and inserts the line cursor = arcpy.da.InsertCursor(fcLine, ['Name', 'SHAPE@']) myArray = arcpy.Array([point1, point2]) line = arcpy.Polyline(myArray) newLineArray = ['Testing ...', line] cursor.insertRow(newLineArray) print('New line inserted!') del (cursor) except: print('An error in inserting line occurred.') traceback.print_exc() del (cursor) ### Create an array and then a polyline. Then use an insert cursor.
y1 = closest_point_1[1] line_array.add(arcpy.Point(x1, y1)) endpoints.remove(closest_point_1) del closest_point_1, x1, y1 # Add second point from closest pair to line array closest_point_2 = closest_pair[1] x2 = closest_point_2[0] y2 = closest_point_2[1] line_array.add(arcpy.Point(x2, y2)) endpoints.remove(closest_point_2) del closest_point_2, x2, y2 del closest_pair # Create line using two new points polyline = arcpy.Polyline(line_array) temp_name = 'temp' + str(step_count) + '.shp' output_test = os.path.join(temp_workspace, temp_name) arcpy.CopyFeatures_management(polyline, output_test) temp_file_list.append(output_test) line_array.removeAll() step_count += 2 #print '\t\tNumber of endpoints left in', boundary_name + ':', len(endpoints) del endpoints, line_array # Update User print '\tDone comparing endpoints.' print '\tNumber of lines created for', boundary_name + ':', len( temp_file_list) print '\tMerging original lines together...'
def ReadOilmap2D(sGeoLocPath, sScenarioName, sSDEconn, modType): splt, trk, thk = PrepFCs(sSDEconn) print "Elapsed time after creating geodatabase = " + str( datetime.datetime.now() - startTime) #pystoch code to read oilmap 2d output files. reader = OMDAR(sGeoLocPath + os.path.sep + "OUTDATA" + os.path.sep + sScenarioName) #with arcpy.da.Editor(sSDEconn) as edit: splt_cur = arcpy.da.InsertCursor(splt, [ 'SHAPE@', 'DATETIME', 'MASS', 'RADIUS', 'THICKNESS', 'STATUS', 'SCENARIO' ]) # # Array = arcpy.Array() TimeSteps = [] t = 0 for block in reader.stream_record_blocks(): #Get spillet date time. if t == 0: iInitSeconds = int(block['metadata']['time']['delta_time']) - int( block['metadata']['time']['elapsed_time']) iElapsedSec = 0 else: iElapsedSec = int(block['metadata']['time']['elapsed_time']) - int( block['metadata']['time']['delta_time']) dtTimeStep = CalculateDateTime(int(iInitSeconds), int(iElapsedSec)) TimeSteps.append(dtTimeStep) lons = [] #list for each time step to avg for track points lats = [] for spillet in block['oil spillets'][1:]: lon = float(spillet[0][0]) lons.append(lon) lat = float(spillet[0][1]) lats.append(lat) status = int(spillet[2]) mass = float(spillet[3]) radius = float(spillet[4]) thickness = float(spillet[5]) #visc = float(spillet[6]) #watercont = float(spillet[7]) pnt = arcpy.Point() pnt.X = lon pnt.Y = lat #pnt.Z = splt_cur.insertRow([ pnt, dtTimeStep, mass, radius, thickness, status, sScenarioName ]) lon_avg = sum(lons) / float(len(lons)) lat_avg = sum(lats) / float(len(lats)) pnt = arcpy.Point(lon_avg, lat_avg) Array.add(pnt) t += 1 del splt_cur trk_cur = arcpy.da.InsertCursor(trk, ['SHAPE@', 'SCENARIO']) trackline = arcpy.Polyline(Array) trk_cur.insertRow([trackline, sScenarioName]) Array.removeAll() del trk_cur print "Elapsed time after creating spillets and track = " + str( datetime.datetime.now() - startTime) thk_cur = arcpy.da.InsertCursor( thk, ['SHAPE@', 'DATETIME', 'THICKNESS_MM', 'SCENARIO']) #get the starting byte position in the OMC for each time step sOMC_Path = sGeoLocPath + os.path.sep + "OUTDATA" + os.path.sep + sScenarioName + ".OMC" ts_start_pos = Get_OMC_StartPos(sOMC_Path, len(reader._record_data)) with open(sOMC_Path, "rb") as f: nVersion = struct.unpack('h', f.read(2))[0] for iRec in range(0, len(reader._record_data)): fpos = ts_start_pos[iRec] f.seek(fpos) if nVersion == 0: ncrecs4 = struct.unpack('h', f.read(2))[0] ncvals = struct.unpack('h', f.read(2))[0] else: ncrecs4 = struct.unpack('l', f.read(4))[0] imaxoil = struct.unpack('h', f.read(2))[0] jmaxoil = struct.unpack('h', f.read(2))[0] olonoil = struct.unpack('f', f.read(4))[0] olatoil = struct.unpack('f', f.read(4))[0] dlonoil = struct.unpack('f', f.read(4))[0] dlatoil = struct.unpack('f', f.read(4))[0] sTime = struct.unpack('l', f.read(4))[0] rval = struct.unpack('f', f.read(4))[0] grid_cell_data = [] for n in range(0, ncrecs4 - 1): i = struct.unpack('h', f.read(2))[0] j = struct.unpack('h', f.read(2))[0] thickness = struct.unpack('f', f.read(4))[0] grid_cell_data.append([i, j, thickness]) for n in range(0, ncrecs4 - 1): i = grid_cell_data[n][0] j = grid_cell_data[n][1] lon1 = olonoil + ((i - 1) * dlonoil) lat1 = olatoil + ((j - 1) * dlatoil) lon2 = olonoil + ((i) * dlonoil) lat2 = olatoil + ((j) * dlatoil) coordList = [[lon1, lat1], [lon1, lat2], [lon2, lat2], [lon2, lat1], [lon1, lat1]] arrayPoly = arcpy.Array() #pntObj = arcpy.Point() for coordPair in coordList: arrayPoly.add(arcpy.Point(coordPair[0], coordPair[1])) cell = arcpy.Polygon(arrayPoly, sr) thk_cur.insertRow( [cell, TimeSteps[iRec], thickness, sScenarioName]) # del thk_cur print "Elapsed time after creating thickness grid = " + str( datetime.datetime.now() - startTime)
def generate_ideal_curve_with_rsquared(radius, c_x, c_y, startX, startY, endX, endY, deltaD, thedirection, obs_polyline, max_distance): """ Generate the points for an ideal curve with radius and center calculated by the hyperfit algorithm """ ## arcpy.AddMessage("funcs.generate_ideal_curve") radsperdegree = math.pi/180. #0.0174532925199 degperrad = 180./math.pi # 57.29577951308232 #Calculate the angle using the center point, and the start and end of the observed curve's start and end points: fullcircle = 2*math.pi #6.28318530718 fullcircledeg = 360. deltarad = deltaD * radsperdegree angle_s = polar_angle(c_y, c_x, startY, startX) angle_e = polar_angle(c_y, c_x, endY, endX) ## arcpy.AddMessage("angle_e before adjustment "+str(degperrad*angle_e)) if(angle_e < angle_s and (thedirection == 1)): angle_e += fullcircle if(angle_e >= angle_s and (thedirection == -1)): angle_e -= fullcircle angle_range = abs(angle_e - angle_s) dec_nvertex = angle_range/deltarad nvertices = int(dec_nvertex) rmder = dec_nvertex - nvertices rmder_inrads = deltarad * rmder ## arcpy.AddMessage("deltarad, deltaD, dec_nvertex, nvertices, rmder=, rmder as rads, rmder as degrees ") ## arcpy.AddMessage(str(deltarad)+"," +str(deltaD)+"," +str(dec_nvertex)+"," +str(nvertices)+"," +str(rmder)+ "," + str(rmder_inrads)+ ", "+str(rmder_inrads*degperrad)) ## arcpy.AddMessage("deltaD, Radius: ") ## arcpy.AddMessage(str(deltaD)+", "+str(radius)) ## arcpy.AddMessage("center X,Y: ") ## arcpy.AddMessage(str(c_x)+", "+str(c_y)) ## arcpy.AddMessage('startX, startY, endX, endY = ') ## arcpy.AddMessage(str(startX)+" "+str(startY) +" "+str(endX)+" "+str(endY)) ## arcpy.AddMessage("angle_s(rad), angle_s(deg), angle_e(rad), angle_e(deg), angle_range(deg) ") ## arcpy.AddMessage(str(angle_s)+", "+str(angle_s*degperrad)+", " + str(angle_e)+", "+ str(angle_e*degperrad)+", "+str(angle_range*degperrad)) angles_list =[] p_angle = angle_s angles_list.append(p_angle) for i in xrange(0, nvertices): ## arcpy.AddMessage("in angle calc "+str(i)) p_angle += (deltarad * thedirection) angles_list.append(p_angle) p_angle += (rmder_inrads * thedirection) angles_list.append(p_angle) ## arcpy.AddMessage("i, angles_list[i]") ## for i in xrange(len(angles_list)): ## arcpy.AddMessage(str(i)+", "+str(angles_list[i])) x = [] y = [] isect_point_list = [] ## arcpy.AddMessage("x_ctob, y_ctob") for i in xrange(len(angles_list)): # x and y point lists for center to best fit for intersection with observered curve, where # each x and y list has the x and y values from the center to the x and y values to best-fit, respectively (Center TO Bestfit). # these are intersected with the observed curve polyline (input parameter to function) to obtain a point for r-squared: xb = math.cos(angles_list[i]) * radius + c_x yb = math.sin(angles_list[i]) * radius + c_y x.append(xb) y.append(yb) #Create a line from the center to the current best-fit vertex, for intersection with polyline. x_ctob = math.cos(angles_list[i]) * max_distance + c_x y_ctob = math.sin(angles_list[i]) * max_distance + c_y # Put the arcpy.Point objects into an array, and then convert into a polyline ctob_array = arcpy.Array([arcpy.Point(c_x,c_y),arcpy.Point(x_ctob,y_ctob)]) ctob_polyline = arcpy.Polyline(ctob_array) #Intersect the ctob_polyline (center of bestfit to max_distance) with the observed curve (obs_polyline): isect_points = ctob_polyline.intersect(obs_polyline, 1) isect_point = isect_points.getPart(0) ## ismult = isect_point.isMultipart ## arcpy.AddMessage(str(ismult)) isect_point_list.append([isect_point.X, isect_point.Y]) ## arcpy.AddMessage(str(isect_point.X)+ ", "+str(isect_point.Y)) ## arcpy.AddMessage(str(i)+", "+str(angles_list[i])+", "+str(math.cos(angles_list[i])*radius)+", "+str(math.cos(angles_list[i]) * radius + center[0])+", "+str(math.sin(angles_list[i])*radius)+", "+str(math.sin(angles_list[i]) * radius + center[1])) return isect_point_list, (zip(x,y))
def execute(self, parameters, messages): inFeatures = parameters[0].valueAsText outFeatures = parameters[1].valueAsText verticesType = parameters[2].valueAsText #messages.addMessage(verticesType) #messages.addMessage(outFeatures) dirName, fcName = os.path.split(outFeatures) inDesc = arcpy.Describe(inFeatures) #messages.addMessage(inDesc.dataType) if (inDesc.dataType == "FeatureLayer"): inDesc = inDesc.featureClass arcpy.CreateFeatureclass_management(dirName, fcName, "POINT", inFeatures, "SAME_AS_TEMPLATE", "SAME_AS_TEMPLATE", inDesc.spatialReference) fields = arcpy.ListFields(outFeatures) #fieldList = ["SHAPE@"] fieldList = [] for field in fields: #messages.addMessage("{0} is a type of {1} with a length of {2}" # .format(field.name, field.type, field.length)) if (field.type != "OID" or field.type != "Geometry"): fieldList.append(field.name) fieldList.append("SHAPE@") # for Progress step count result = arcpy.GetCount_management(inFeatures) count = int(result.getOutput(0)) arcpy.SetProgressor("step", "Inserting ...", 0, count, 1) with arcpy.da.InsertCursor(outFeatures, fieldList) as inCursor: with arcpy.da.SearchCursor(inFeatures, fieldList) as cursor: for row in cursor: for part in row[-1]: if (verticesType == "START" or verticesType == "BOTH_ENDS"): # = arcpy.Polyline(arcpy.Array(part)).firstPoint insertRow = row[:-1] + (part[0], ) inCursor.insertRow(insertRow) #messages.addMessage("始点") if (verticesType == "END" or verticesType == "BOTH_ENDS"): #insertRow[0] = arcpy.Polyline(arcpy.Array(part)).lastPoint insertRow = row[:-1] + (part[len(part) - 1], ) inCursor.insertRow(insertRow) #messages.addMessage("終点") if (verticesType == "MID"): insertRow = row[:-1] + (arcpy.Polyline( arcpy.Array(part)).positionAlongLine( 0.5, True), ) inCursor.insertRow(insertRow) #messages.addMessage("中間点") if (verticesType == "ALL"): #messages.addMessage("全部") for pnt in part: insertRow = row[:-1] + (pnt, ) #messages.addMessage( str(pnt.X) + " " + str(pnt.Y) ) inCursor.insertRow(insertRow) # step count arcpy.SetProgressorPosition()
def runScript(uploaderpk): print("Starting script") startTime = time.time() arcpy.env.overwriteOutput = True arcpy.env.cellSize = 1 # Activate spatial analyst extension if arcpy.CheckExtension("Spatial") == "Available": arcpy.CheckOutExtension("Spatial") if arcpy.CheckExtension("3D") == "Available": arcpy.CheckOutExtension("3D") # basePath = .../apps/findbestroute/workfiles/ global basePath sleep(2) basePath = os.path.join(settings.PROJECT_PATH, 'apps', 'findbestroute', 'workfiles') env.workspace = basePath sleep(2) mxd = arcpy.mapping.MapDocument(os.path.join(basePath, r'mapdocument.mxd')) onlyfiles = [] kart_path = None for file in os.listdir( os.path.join(settings.PROJECT_PATH, r"files", r"user_" + str(uploaderpk))): if file.endswith(".shp"): onlyfiles.append( os.path.join(settings.PROJECT_PATH, r"files", r"user_" + str(uploaderpk), file)) elif file.endswith(".jpg"): kart_path = os.path.join(settings.PROJECT_PATH, r"files", r"user_" + str(uploaderpk), file) for el in onlyfiles: print("File: " + el.__str__()) print("Map file: " + kart_path.__str__()) arealsymboler, linjesymboler, punktsymboler, breakBoolean = geometryType( onlyfiles) if (breakBoolean): print( "Datafiles not containing all shapefiles( either point, polyline or polygon)" ) return kart = kart_path #os.path.join(settings.PROJECT_PATH, r"apps", r"findbestroute", r"workfiles", r"inData", r"kart.jpg") #geoProcess(kart_path, arealsymboler) start = getStart(punktsymboler) destination = getDestination(punktsymboler) mask = setMask(start, destination) arcpy.env.mask = os.path.join(basePath, r"Trash", r"mask.shp") utsnitt = getExtentOfMap(linjesymboler) hoydedata = arcpy.Clip_analysis( in_features=os.path.join(basePath, r"hoydeData", r"trondheiml.shp"), clip_features=utsnitt, out_feature_class=os.path.join(basePath, r"Trash", r"hoydedata.shp"), cluster_tolerance="") #Klipper til symbolene etter mask ar = arcpy.Clip_analysis(in_features=arealsymboler, clip_features=mask, out_feature_class=os.path.join( basePath, r"Trash", r"a5"), cluster_tolerance="") ln = arcpy.Clip_analysis(in_features=linjesymboler, clip_features=mask, out_feature_class=os.path.join( basePath, r"Trash", r"a6"), cluster_tolerance="") pt = arcpy.Clip_analysis(in_features=punktsymboler, clip_features=mask, out_feature_class=os.path.join( basePath, r"Trash", r"a7"), cluster_tolerance="") #Runde ned alle symboler floorSymbols(ar) floorSymbols(ln) floorSymbols(pt) #Lage buffer paa linjer som er lik bredden de skal ha fieldnames = [field.name for field in arcpy.ListFields(ln)] if not "WIDTH" in fieldnames: arcpy.AddField_management(in_table=ln, field_name="WIDTH", field_type="DOUBLE") symbols = [ 106, 107, 201, 203, 304, 305, 307, 502, 503, 504, 505, 506, 507, 508, 509 ] width = [2, 2, 4, 4, 2, 2, 1, 6, 4, 3, 2.5, 2, 2, 2, 2] features = arcpy.UpdateCursor(ln) for feature in features: if feature.SYMBOL in symbols: n = symbols.index(feature.SYMBOL) feature.WIDTH = width[n] features.updateRow(feature) del feature, features, n ln_buff = arcpy.Buffer_analysis(in_features=ln, out_feature_class=os.path.join( basePath, r"Trash", r"a8"), buffer_distance_or_field="WIDTH", line_side="FULL", line_end_type="FLAT", dissolve_option="LIST", dissolve_field="SYMBOL") #Hente ut alle forbudte symboler forbiddenArea = arcpy.Select_analysis( in_features=ar, out_feature_class=os.path.join(basePath, r"Trash", r"a9"), where_clause= '"SYMBOL" = 202 OR "SYMBOL" = 211 OR "SYMBOL" = 301 OR "SYMBOL" = 302 OR "SYMBOL" = 307 OR "SYMBOL" = 415 OR "SYMBOL" = 526 OR "SYMBOL" = 527 OR "SYMBOL" = 528 OR "SYMBOL" = 709' ) forbiddenLineBuff = arcpy.Select_analysis( in_features=ln_buff, out_feature_class=os.path.join(basePath, r"Trash", r"b1"), where_clause= '"SYMBOL" = 201 OR "SYMBOL" = 307 OR "SYMBOL" = 521 OR "SYMBOL" = 524 OR "SYMBOL" = 528 OR "SYMBOL" = 534 OR "SYMBOL" = 709' ) #Hente ut alle passerbare symboler passableArea = arcpy.Select_analysis( in_features=ar, out_feature_class=os.path.join(basePath, r"Trash", r"b2"), where_clause= '"SYMBOL" <> 202 AND "SYMBOL" <> 211 AND "SYMBOL" <> 301 AND "SYMBOL" <> 302 AND "SYMBOL" <> 307 AND "SYMBOL" <> 415 AND "SYMBOL" <> 526 AND "SYMBOL" <> 527 AND "SYMBOL" <> 528 AND "SYMBOL" <> 601 AND "SYMBOL" <> 709' ) passableLineBuff = arcpy.Select_analysis( in_features=ln_buff, out_feature_class=os.path.join(basePath, r"Trash", r"b3"), where_clause= '"SYMBOL" <> 201 AND "SYMBOL" <> 307 AND "SYMBOL" <> 521 AND "SYMBOL" <> 524 AND "SYMBOL" <> 528 AND "SYMBOL" <> 534 AND "SYMBOL" <> 709' ) #Lage skogflater area = arcpy.Update_analysis(in_features=passableArea, update_features=forbiddenArea, out_feature_class=os.path.join( basePath, r"Trash", r"b4")) forest = arcpy.Erase_analysis(in_features=mask, erase_features=area, out_feature_class=os.path.join( basePath, r"Trash", r"b5")) arcpy.AddField_management(in_table=forest, field_name="SYMBOL", field_type="DOUBLE") features = arcpy.UpdateCursor(forest) for feature in features: feature.SYMBOL = 405 features.updateRow(feature) del feature, features #Lage kartet i ArcMap area1 = arcpy.Erase_analysis(in_features=passableArea, erase_features=forbiddenArea, out_feature_class=os.path.join( basePath, r"Trash", r"b6")) area2 = arcpy.Erase_analysis(in_features=area1, erase_features=forbiddenLineBuff, out_feature_class=os.path.join( basePath, r"Trash", r"b7")) passable1 = arcpy.Update_analysis(in_features=area2, update_features=forest, out_feature_class=os.path.join( basePath, r"Trash", r"b8")) mapped = arcpy.Update_analysis(in_features=passable1, update_features=passableLineBuff, out_feature_class=os.path.join( basePath, r"Trash", r"b9")) #Sette kostnad paa alle flater setCost(mapped) print('hey') costRaster = arcpy.FeatureToRaster_conversion( mapped, "COST", os.path.join(basePath, r"Results", r"CostRaster.tif")) #Lage sloperaster #create a TIN of the area tin = arcpy.CreateTin_3d( out_tin=os.path.join(basePath, r"Results", r"TIN"), spatial_reference="#", in_features=os.path.join(basePath, r"Trash", r"hoydedata.shp") + " HOEYDE masspoints") # Replace a layer/table view name with a path to a dataset (which can be a layer file) or create the layer/table view within the script # The following inputs are layers or table views: "hoydeTIN" tinRaster = arcpy.TinRaster_3d(in_tin=os.path.join(basePath, r"Results", r"TIN"), out_raster=os.path.join( basePath, r"Results", "hRaster"), data_type="FLOAT", method="LINEAR", sample_distance="CELLSIZE 1", z_factor="1") # Replace a layer/table view name with a path to a dataset (which can be a layer file) or create the layer/table view within the script # The following inputs are layers or table views: "hraster" slope = arcpy.Slope_3d(in_raster=os.path.join(basePath, r"Results", r"hRaster"), out_raster=os.path.join(basePath, r"Results", r"slope"), output_measurement="DEGREE", z_factor="1") # Reklassifisering av slope reMapRange = RemapRange([[0, 0.5, 100], [0.5, 1, 101], [1, 2, 102], [2, 3, 103], [3, 4, 104], [4, 5, 105], [5, 6, 106], [6, 7, 107], [7, 8, 108], [8, 9, 109], [9, 10, 110], [10, 11, 111], [11, 12, 112], [12, 13, 113], [13, 14, 114], [14, 15, 115], [15, 16, 116], [16, 17, 117], [17, 18, 118], [18, 19, 119], [19, 20, 120], [20, 90, 150]]) slope_reclass = Reclassify(in_raster=os.path.join(basePath, r"Results", r"slope"), reclass_field="VALUE", remap=reMapRange) slope_reclass.save(os.path.join(basePath, r"Results", r"slopeReclass")) # Rasterkalkulator som lager raster som tar hensyn til hoyde i kostnadsrasteret finalCostRaster = Raster( os.path.join(basePath, r"Results", r"CostRaster.tif")) * ( Raster(os.path.join(basePath, r"Results", r"slopeReclass")) / 100) #Regne ut leastcostpath cdr = arcpy.sa.CostDistance(start, finalCostRaster) cdr.save(os.path.join(basePath, r"Results", r"costDistance")) cbr = arcpy.sa.CostBackLink(start, finalCostRaster) cbr.save(os.path.join(basePath, r"Results", r"Costback")) cp = arcpy.sa.CostPath(destination, cdr, cbr, "EACH_CELL") cp.save(os.path.join(basePath, r"Results", r"costpath")) #Gjore om til polygon med litt bredde arcpy.RasterToPolygon_conversion( in_raster=os.path.join(basePath, r"Results", r"costpath"), out_polygon_features=os.path.join(basePath, r"Results", r"cpPoly.shp"), simplify="SIMPLIFY") arcpy.Buffer_analysis(in_features=os.path.join(basePath, r"Results", r"cpPoly.shp"), out_feature_class=os.path.join( basePath, r"Results", r"LCP.shp"), buffer_distance_or_field="2", line_side="FULL", line_end_type="FLAT", dissolve_option="LIST") df = arcpy.mapping.ListDataFrames(mxd, "*")[0] for lyr in arcpy.mapping.ListLayers(mxd, "", df): arcpy.mapping.RemoveLayer(df, lyr) print("Deleted lyr's in mxd") #Legge til i ArcMap templateLayer = arcpy.mapping.Layer( os.path.join(basePath, r"Template", r"colorTemplate.lyr")) df = arcpy.mapping.ListDataFrames(mxd, "*")[0] newlayer = arcpy.mapping.Layer( os.path.join(basePath, r"Results", r"LCP.shp")) newlayer.transparency = 50 """ PROBLEMBARN RETT UNDER """ arcpy.ApplySymbologyFromLayer_management(in_layer=newlayer, in_symbology_layer=templateLayer) # in_symbology_layer = os.path.join(basePath, r"Template", r"colorTemplate.lyr")) """ PROBLEMBARN RETT OVER """ arcpy.mapping.AddLayer(df, newlayer, "BOTTOM") arcpy.MakeRasterLayer_management(in_raster=kart, out_rasterlayer=os.path.join( basePath, r"Results", r"rasterkart")) mapLayer = arcpy.mapping.Layer( os.path.join(basePath, r"Results", r"rasterkart")) arcpy.mapping.AddLayer(df, mapLayer, "BOTTOM") # Lage postsirkler og linje og legge til dette i ArcGIS points = arcpy.CreateFeatureclass_management(out_path=os.path.join( basePath, r"Trash"), out_name="points", geometry_type="POINT") del destination start = getStart(pt) destination = getDestination(pt) features = arcpy.UpdateCursor(start) for feature in features: startX = feature.POINT_X startY = feature.POINT_Y features = arcpy.UpdateCursor(destination) for feature in features: destX = feature.POINT_X destY = feature.POINT_Y cursor = arcpy.da.InsertCursor(points, ("fid", "SHAPE@XY")) cursor.insertRow((1, (startX, startY))) cursor.insertRow((2, (destX, destY))) del destination outerCircle = arcpy.CreateFeatureclass_management(out_path=os.path.join( basePath, r"Trash"), out_name="circles1.shp", geometry_type="POLYGON") innerCircle = arcpy.CreateFeatureclass_management(out_path=os.path.join( basePath, r"Trash"), out_name="circles2.shp", geometry_type="POLYGON") circle = arcpy.CreateFeatureclass_management( out_path=os.path.join(basePath, r"Trash"), out_name="circles.shp", geometry_type="POLYGON", ) arcpy.Buffer_analysis(points, outerCircle, 40) arcpy.Buffer_analysis(points, innerCircle, 35) arcpy.Erase_analysis(outerCircle, innerCircle, circle) symLayer = arcpy.mapping.Layer( os.path.join(basePath, r"Template", r"color2.lyr")) circleLayer = arcpy.mapping.Layer( os.path.join(basePath, r"Trash", r"circles.shp")) arcpy.ApplySymbologyFromLayer_management(in_layer=circleLayer, in_symbology_layer=symLayer) arcpy.mapping.AddLayer(data_frame=df, add_layer=circleLayer, add_position="TOP") # Lage postlinje lines = arcpy.CreateFeatureclass_management(out_path=os.path.join( basePath, r"Trash"), out_name="line.shp", geometry_type="POLYGON") directionX = (destX - startX) / ( math.sqrt(math.pow(destX - startX, 2) + math.pow(destY - startY, 2))) directionY = (destY - startY) / ( math.sqrt(math.pow(destX - startX, 2) + math.pow(destY - startY, 2))) features = [] features.append( arcpy.Polyline( arcpy.Array([ arcpy.Point(startX + 45 * directionX, startY + 45 * directionY), arcpy.Point(destX - 45 * directionX, destY - 45 * directionY) ]))) lineFeat = arcpy.CopyFeatures_management( features, os.path.join(basePath, r"Trash", r"lines.shp")) arcpy.Buffer_analysis(in_features=lineFeat, out_feature_class=lines, buffer_distance_or_field=2.5, line_end_type="FLAT") lineLayer = arcpy.mapping.Layer( os.path.join(basePath, r"Trash", r"line.shp")) arcpy.ApplySymbologyFromLayer_management(in_layer=lineLayer, in_symbology_layer=symLayer) arcpy.mapping.AddLayer(data_frame=df, add_layer=lineLayer, add_position="TOP") mxd.save() #Skrive ut bilde av veivalg B = df.extent.XMax - df.extent.XMin H = df.extent.YMax - df.extent.YMin filename = str(uploaderpk) + "_" + time.strftime( "%d-%m-%Y") + "_" + time.strftime("%H-%M-%S") + ".png" relative_path_string = os.path.join(r"Dump", filename) print("hurr " + settings.PROJECT_PATH) print("durr " + relative_path_string) out_path = os.path.join(settings.PROJECT_PATH, "files", r"Dump", filename) print(out_path) arcpy.mapping.ExportToPNG(map_document=mxd, out_png=out_path, data_frame=df, df_export_width=int(3 * B), df_export_height=int(3 * H), resolution=225) print("Finished making image") #relative_path = os.path.join(r"Dump", "MapLCP.png") img = Image() img.uploader = PathUser.objects.get(pk=uploaderpk) img.bilde = relative_path_string img.save() folder = os.path.join(basePath, r"Trash") for file in os.listdir(folder): filepath = os.path.join(folder, file) try: if os.path.isfile(filepath): print "Removing " + filepath os.remove(filepath) elif os.path.isdir(filepath): print "Removing " + filepath shutil.rmtree(filepath) except Exception as e: print(e) folder = os.path.join(basePath, r"Results") for file in os.listdir(folder): filepath = os.path.join(folder, file) try: if os.path.isfile(filepath): print "Removing " + filepath os.remove(filepath) elif os.path.isdir(filepath): print "Removing " + filepath shutil.rmtree(filepath) except Exception as e: print(e) delete_user_uploads.delay(uploaderpk) end = time.time() print(end - startTime)
if linecursor is None : arcpy.AddError("Could not obtain update cursor on " + str(inTrackLines)) ft = next(linecursor) arcpy.AddMessage("Resetting times/values for next track.") if ft is not None : ft[0] = loweststart ft[1] = highestfinish #Debug: # arcpy.AddMessage("Resetting shape for next track. Shape field: " + shapefieldname) # if pointCount != ptarray.count : # arcpy.AddMessage("Shape has unexpected point count: " + str(pointCount) + " vs. " + str(ptarray.count)) try : outPoly = arcpy.Polyline(ptarray) ft[2] = outPoly except Exception as err: import traceback arcpy.AddError(traceback.format_exception_only(type(err), err)[0].rstrip()) linecursor.updateRow(ft) #finally, update all points with the Track IDs affected to the new Track ID arcpy.AddMessage("Updating track points where " + changedtrackids) if (sys.version_info.major < 3) : ptcursor = arcpy.UpdateCursor(inTrackPoints, changedtrackids) else : ptcursor = arcpy.gp.UpdateCursor(inTrackPoints, changedtrackids) for feat in ptcursor :
data = ingest_od_data(source_data_table, 'O_X', 'O_Y', 'D_X', 'D_Y') # This list will store all of the Polyline objects polylines = [] for start, end in data: # Find the distance between the two locations length = distance(start[0], start[1], end[0], end[1]) # Create points along a Bezier curve bez_verts = bezier_vertices_quadratic(length, 12) # Use the points from the Bezier curve to create vertices in geographic space gis_verts = arc_points([start, end], length, bez_verts) # Create a Polyline arcpy object made up of Point arcpy objects points_array = arcpy.Array() for vertex in gis_verts: points_array.append(arcpy.Point(vertex[0], vertex[1], vertex[2])) polyline = arcpy.Polyline(points_array, sr, True) polylines.append(polyline) # Set up the empty feature class that will store the arcs out_gdb = r'C:\GIS_DATA\example.gdb' # REPLACE WITH THE PATH TO YOUR GEODATABASE arcpy.CreateFeatureclass_management(out_gdb, 'multiplearcs', 'POLYLINE', '', 'DISABLED', 'ENABLED', sr) with arcpy.da.InsertCursor(os.path.join(out_gdb, 'multiplearcs'), ['SHAPE@']) as cur: for polyline in polylines: cur.insertRow([polyline])
def onLine(self, line_geometry): fc = 'Line' deleteID = str(GenInfo.numFea) + str(GenInfo.n) path = GenInfo.workpath + '\TestTD.gdb' numberOfSegments = len(GenInfo.Feature['Segments']) lineCoordinates = line_geometry.getPart(0) sp = lineCoordinates[0] ep = lineCoordinates[len(lineCoordinates) - 1] # if numberOfSegments==0: '''Perform the snap functionality''' print[point for point in lineCoordinates] if (numberOfSegments <> 0 and GenInfo.startRing == 0) or ( numberOfSegments - GenInfo.ExteriorSeg > 0 and GenInfo.startRing == 1) or (GenInfo.NextRing == 0 and GenInfo.startRing == 1): try: lineCoordinates[0] = arcpy.Point( GenInfo.Feature['Segments'][numberOfSegments - 1]['EndP'][0], GenInfo.Feature['Segments'][numberOfSegments - 1]['EndP'][1]) except: try: lineCoordinates[0] = GenInfo.Feature['Segments'][ numberOfSegments - 1]['LineGeometry'].lastPoint except: pass for featureInfo in GenInfo.Feature['Segments']: try: startPoint = arcpy.PointGeometry( arcpy.Point(featureInfo['StartP'][0], featureInfo['StartP'][1])) except: startPoint = arcpy.PointGeometry( featureInfo['LineGeometry'].firstPoint) distanceEP = startPoint.distanceTo(ep) if 0 < distanceEP < 5: # del lineCoordinates[-1] lineCoordinates.append(startPoint.getPart(0)) if numberOfSegments == 0 or ( numberOfSegments - GenInfo.ExteriorSeg == 0 and GenInfo.startRing == 1) or (GenInfo.NextRing == 1 and GenInfo.startRing == 1): minDistanceSP, closestFeatureSP = 5, None minDistanceEP, closestFeatureEP = 5, None spGeo = arcpy.PointGeometry(sp) epGeo = arcpy.PointGeometry(ep) for feature in GenInfo.allLayersFeatures: distanceSP = feature.distanceTo(sp) if 0 < distanceSP < 5: print 'SP distance -->', distanceSP try: print 'we are in SP try' if distanceSP < minDistanceSP: minDistanceSP = distanceSP closestFeatureSP = feature except: print 'we are in SP exception' minDistanceSP = distanceSP closestFeatureSP = featur distanceEP = feature.distanceTo(ep) if 0 < distanceEP < 5: print 'EP distance -->', distanceEP try: print 'we are in EP try' if distanceEP < minDistanceEP: minDistanceEP = distanceEP closestFeatureEP = feature except: print 'we are in EP exception' minDistanceEP = distanceEP closestFeatureEP = feature if closestFeatureSP is not None: spNew = closestFeatureSP.snapToLine(sp).getPart(0) lineCoordinates[0] = spNew if closestFeatureEP is not None: epNew = closestFeatureEP.snapToLine(ep).getPart(0) lineCoordinates.append(epNew) line_geometry = arcpy.Polyline( arcpy.Array([point for point in lineCoordinates]), GenInfo.spatialReference) '''Visualize the line''' edit = arcpy.da.Editor(path) edit.startEditing(True) edit.startOperation() cur = arcpy.da.InsertCursor(fc, ['SHAPE@', 'DeleteID']) cur.insertRow((line_geometry, deleteID)) edit.stopOperation() edit.stopEditing(True) arcpy.RefreshActiveView() '''Transform the absolute coordinates to relative coordinates''' reCoords = relativeCoor(lineCoordinates) re_line_geometry = arcpy.Polyline( arcpy.Array([arcpy.Point(*coords) for coords in reCoords])) '''Save coordinates of line_geometry''' GenInfo.LineDict['LineGeometry'] = re_line_geometry GenInfo.LineDict['SegOrder'] = GenInfo.n for row in arcpy.SearchCursor('Domain', fields='URIDomain'): domain = row.getValue('URIDomain') GenInfo.LineDict['URI'] = domain + str(uuid.uuid4()) if GenInfo.startRing == 1: GenInfo.LineDict['InnerRingNum'] = GenInfo.m GenInfo.n += 1 print GenInfo.LineDict GenInfo.Feature['Segments'].append(GenInfo.LineDict) GenInfo.LineDict = { 'LineGeometry': 'Inf', 'SegOrder': 'Inf', 'URI': 'Inf' }
def UpStreamRoute(DEMfil, WatershedFile, HillslpFile, StreamFile, FlowDirFile, RillExtDir, UpStreamRouteFile, UpStreamShp): stream = ReadRaster(StreamFile).data nrows, ncols = stream.shape nodata = ReadRaster(StreamFile).noDataValue geotrans = ReadRaster(StreamFile).geotrans hillslp = ReadRaster(HillslpFile).data flowdir = ReadRaster(FlowDirFile).data watershed = ReadRaster(WatershedFile).data demfil = ReadRaster(DEMfil).data UpStream = numpy.ones((nrows, ncols)) UpStream = UpStream * -9999 #UpStreamShp = RillExtDir + os.sep + "UpStream.shp" StreamPts = [] for i in range(nrows): for j in range(ncols): if (stream[i][j] != nodata): StreamPts.append((i, j)) boundCells = [] for pt in StreamPts: curBoundCells = [] row, col = pt cWatershed = watershed[row][col] UpStreamCell(row, col, flowdir, stream, watershed, cWatershed, nodata, curBoundCells) boundCells.extend(curBoundCells) BoundRaster = numpy.ones((nrows, ncols)) BoundRaster = BoundRaster * -9999 segement_info = [] #segeLength_info = [] # A list that will hold each of the Polyline objects f = open(UpStreamRouteFile, 'w') ## write the single stream route to txt by line arcpy.gp.overwriteOutput = 1 segements = [] ## Generating ArcGIS polyline for cell in boundCells: BoundRaster[cell[0]][cell[1]] = 1 curSege = SingleDownstream(cell, flowdir, stream, nodata) # curSegeLen = [] # curSegeLen.append(1) # for i in range(1,len(curSege)): # if flowdir[curSege[i][0]][curSege[i][1]] in [2,8,32,128]: # curSegeLen.append(curSegeLen[i-1] + math.sqrt(2)) # else: # curSegeLen.append(curSegeLen[i-1] + 1) #segeLength_info.append(curSegeLen) #segement_info.append(curSege) f.write(str(curSege)) f.write('\n') for grid in curSege: row = grid[0] col = grid[1] grid[0] = geotrans[0] + (col + 0.5) * geotrans[1] grid[1] = geotrans[3] - (row + 0.5) * geotrans[1] segements.append( arcpy.Polyline( arcpy.Array([arcpy.Point(*coords) for coords in curSege]))) WriteAscFile(RillExtDir + os.sep + "BoundCell.asc", BoundRaster, ncols, nrows, geotrans, -9999) f.close() arcpy.CopyFeatures_management(segements, UpStreamShp)
start_time = time.time() Astar(graph1, start, end, pop, 'l') end_time = time.time() print "Czas dzialania algorytmu: " + str(end_time - start_time) #tworzenie warstwy z wyznaczona trasa arcpy.Delete_management("navigation.shp") out_path = arcpy.env.workspace out_name = "navigation.shp" geometry_type = "POLYLINE" feature_class = arcpy.CreateFeatureclass_management(out_path, out_name, geometry_type, skjz, "DISABLED", "DISABLED", skjz) #array = arcpy.Array() array2 = arcpy.Array() with arcpy.da.InsertCursor(feature_class, ["SHAPE@"]) as cursor: i = end.getID() while i != None: my_node = graph1.get_node(i) array2.add(arcpy.Point(my_node.getX(), my_node.getY())) i = pop[i] #array.add(arcpy.Point(x_end, y_end)) #array.add(arcpy.Point(x_start, y_start)) #cursor.insertRow([arcpy.Polyline(array)]) cursor.insertRow([arcpy.Polyline(array2)])
def RotateFeatureClass(inputFC, outputFC, angle=0, pivot_point=None): """Rotate Feature Class inputFC Input features outputFC Output feature class angle Angle to rotate, in degrees pivot_point X,Y coordinates (as space-separated string) Default is lower-left of inputFC As the output feature class no longer has a "real" xy locations, after rotation, it no coordinate system defined. """ def RotateXY(x, y, xc=0, yc=0, angle=0, units="DEGREES"): """Rotate an xy cooordinate about a specified origin x,y xy coordinates xc,yc center of rotation angle angle units "DEGREES" (default) or "RADIANS" """ x = x - xc y = y - yc # make angle clockwise (like Rotate_management) angle = angle * -1 if units == "DEGREES": angle = math.radians(angle) xr = (x * math.cos(angle)) - (y * math.sin(angle)) + xc yr = (x * math.sin(angle)) + (y * math.cos(angle)) + yc return xr, yr # temp names for cleanup env_file = None lyrFC, lyrTmp = [None] * 2 # layers tmpFC = None # temp dataset try: # process parameters try: xcen, ycen = [float(xy) for xy in pivot_point.split()] pivot_point = xcen, ycen except: # if pivot point was not specified, get it from # the lower-left corner of the feature class ext = arcpy.Describe(inputFC).extent xcen, ycen = ext.XMin, ext.YMin pivot_point = xcen, ycen angle = float(angle) # set up environment env_file = arcpy.CreateScratchName("xxenv", ".xml", "file", os.environ["TEMP"]) arcpy.gp.SaveSettings(env_file) WKS = env.workspace if not WKS: if os.path.dirname(outputFC): WKS = os.path.dirname(outputFC) else: WKS = os.path.dirname(arcpy.Describe(inputFC).catalogPath) env.workspace = env.scratchWorkspace = WKS # Disable any GP environment clips arcpy.ClearEnvironment("extent") # get feature class properties lyrFC = 'lyrFC' arcpy.MakeFeatureLayer_management(inputFC, lyrFC) dFC = arcpy.Describe(lyrFC) shpField = dFC.shapeFieldName shpType = dFC.shapeType # create temp feature class tmpFC = arcpy.CreateScratchName("xxfc", "", "featureclass") # Create Feature Class using inputFC as template (so will have "Grid" field) arcpy.CreateFeatureclass_management(os.path.dirname(tmpFC), os.path.basename(tmpFC), shpType, inputFC) lyrTmp = 'lyrTmp' arcpy.MakeFeatureLayer_management(tmpFC, lyrTmp) ## WORKAROUND: removed below because it was creating a schema lock until Pro/arcpy exited ## set up grid field #gridField = "Grid" #arcpy.AddField_management(lyrTmp, gridField, "TEXT") #arcpy.DeleteField_management(lyrTmp, 'ID') # rotate the feature class coordinates for each feature, and each feature part # open read and write cursors updateFields = ['SHAPE@', 'Grid'] arcpy.AddMessage('Rotating temporary dataset') parts = arcpy.Array() rings = arcpy.Array() ring = arcpy.Array() with arcpy.da.SearchCursor(lyrFC, updateFields) as inRows,\ arcpy.da.InsertCursor(lyrTmp, updateFields) as outRows: for inRow in inRows: shp = inRow[0] # SHAPE p = 0 for part in shp: for pnt in part: if pnt: x, y = RotateXY(pnt.X, pnt.Y, xcen, ycen, angle) ring.add(arcpy.Point(x, y, pnt.ID)) else: # if we have a ring, save it if len(ring) > 0: rings.add(ring) ring.removeAll() # we have our last ring, add it rings.add(ring) ring.removeAll() # if only one, remove nesting if len(rings) == 1: rings = rings.getObject(0) parts.add(rings) rings.removeAll() p += 1 # if only one, remove nesting if len(parts) == 1: parts = parts.getObject(0) if dFC.shapeType == "Polyline": shp = arcpy.Polyline(parts) else: shp = arcpy.Polygon(parts) parts.removeAll() gridValue = inRow[1] # GRID string outRows.insertRow([shp, gridValue]) # write row to output arcpy.AddMessage('Merging temporary, rotated dataset with output') env.qualifiedFieldNames = False arcpy.Merge_management(lyrTmp, outputFC) except MsgError as xmsg: arcpy.AddError(str(xmsg)) except arcpy.ExecuteError: tbinfo = traceback.format_tb(sys.exc_info()[2])[0] arcpy.AddError(tbinfo.strip()) arcpy.AddError(arcpy.GetMessages()) numMsg = arcpy.GetMessageCount() for i in range(0, numMsg): arcpy.AddReturnMessage(i) except Exception as xmsg: tbinfo = traceback.format_tb(sys.exc_info()[2])[0] arcpy.AddError(tbinfo + str(xmsg)) finally: # reset environment if env_file: arcpy.gp.LoadSettings(env_file) # Clean up temp files for f in [lyrFC, lyrTmp, tmpFC, env_file]: try: if f and arcpy.Exists(f): arcpy.Delete_management(f) except: pass # return pivot point try: pivot_point = "{0} {1}".format(*pivot_point) except: pivot_point = None return pivot_point
def create_traverse_gps_vector(self, stations, gps_observations, network_level_to_process, output_gdb_path, output_vector_path): template_gps_traverse = r'U:\scratch-workplace\control-network\data\wrk\control-network-template.gdb\gps_traverse' feature_dataset_name = os.path.dirname(output_vector_path) polyline_name = os.path.basename(output_vector_path) arcpy.CreateFeatureclass_management(feature_dataset_name, polyline_name, 'POLYLINE', has_z = 'ENABLED', template = template_gps_traverse) print '%s created' % output_vector_path #feature_class_definitions.add_fields(output_gps_traverse_polyline_path, # feature_class_definitions.traverse_gps_vector_field_definitions) with arcpy.da.InsertCursor(output_vector_path, ['SHAPE@', 'NET_TAG', 'NET_TYPE', 'OBS_TYPE', 'FROM_STATION', 'TO_STATION', 'ECEF_DX', 'ECEF_DY', 'ECEF_DZ', 'COVAR_XX' , 'COVAR_XY', 'COVAR_XZ' , 'COVAR_YY', 'COVAR_YZ', 'COVAR_ZZ', 'FROM_ANT_HT', 'TO_ANT_HT', 'PROCESS', 'RATIO', 'RMS', 'REF_VAR', 'START_TIME', 'END_TIME']) as in_cursor: for observation in gps_observations: if observation.from_station in stations.keys() and \ observation.to_station in stations.keys(): if network_level != None: if network_level.upper() == network_level_to_process.upper(): start_point = stations[observation.from_station] end_point = stations[observation.to_station] start_point_gis = arcpy.Point(start_point.local_easting, start_point.local_northing, start_point.local_elevation) end_point_gis = arcpy.Point(end_point.local_easting, end_point.local_northing, end_point.local_elevation) point_array = arcpy.Array() point_array.add(start_point_gis) point_array.add(end_point_gis) traverse_vector = arcpy.Polyline(point_array, template_spatial_reference) traverse_vector.projectAs(arcpy.SpatialReference(6404)) in_cursor.insertRow([traverse_vector, 'NA', network_level_to_process, 'GPS', observation.from_station, observation.to_station, observation.ecef_dx, observation.ecef_dy, observation.ecef_dz, observation.covariance_xx, observation.covariance_xy, observation.covariance_xz, observation.covariance_yy, observation.covariance_yz, observation.covariance_zz, observation.from_antenna_height, observation.to_antenna_height, observation.status, observation.ratio, observation.rms, observation.ref_var, observation.start_datetime, observation.end_datetime]) return
curSfc = arcpy.da.SearchCursor(fc,["SHAPE@XY","FID"]) def retFID(X): sql = (""""FID" = {0}""").format(X) arcpy.AddMessage("Creating line for"+sql) cur= arcpy.da.SearchCursor(fc,["FID","SHAPE@XY"],sql) for i in cur: return i[1] del cur #=====================Create polyine=============================# for m,n in pair: coordS = retFID(m) coordE = retFID(n) array = arcpy.Array([arcpy.Point(coordS[0], coordS[1]),arcpy.Point(coordE[0], coordE[1])]) polyline = arcpy.Polyline(array) curI.insertRow([polyline]) array.removeAll() del curI,curSfc arcpy.Delete_management(distance) try: shutil.rmtree(r"C:\deleteit") except: pass print "Completed Line Generation"
insert = arcpy.da.InsertCursor(diagonals, ["SHAPE@", "RNDID"]) offset = 500.0 # 1/2 km offsets for row in rows: rndPtOID = row[0] rndPt = row[1] # if I'm right this is how we add a multipart line feature diagArray1 = arcpy.Array([ arcpy.Point(rndPt[0] - offset, rndPt[1] + offset), arcpy.Point(rndPt[0] + offset, rndPt[1] - offset) ]) diagArray2 = arcpy.Array([ arcpy.Point(rndPt[0] - offset, rndPt[1] - offset), arcpy.Point(rndPt[0] + offset, rndPt[1] + offset) ]) diagArray = arcpy.Array([diagArray1, diagArray2]) diagLine = arcpy.Polyline(diagArray) insert.insertRow([diagLine, rndPtOID]) del insert del rows # Intersect diagonals with contours intersects = os.path.join(scratch, "intersects") arcpy.AddMessage( str(tileNum) + " Intersecting diagonals with contours...") arcpy.Intersect_analysis([diagonals, inputContours], intersects, "ONLY_FID", "#", "point") deleteme.append(intersects) # for some reason Intersect makes multipoints intersectSingle = os.path.join(scratch, "intersectSingle") arcpy.MultipartToSinglepart_management(intersects, intersectSingle) deleteme.append(intersectSingle)
"SHAPE_Length > 0") # <---- Create query for SHAPE_Length > 0 for u_curs in u_curs_BlockCenterline: #Iterate through each polyline feature in BlockCenterline. print u_curs[2] feat = u_curs[1] point = arcpy.Point() array = arcpy.Array() for part in feat: #Create an array of points in each polyline feature. for pnt in part: point.X = pnt.X point.Y = pnt.Y array.add(point) pline = arcpy.Polyline( array) #Create a polyline object from the array of points. print "pline created." u_curs[0] = NorthAzimuth( pline) #Pass the polyline object to the NorthAzimuth function. """Added to account for Alley (AA) rotation set to 0""" if "-AA-" in u_curs[2]: u_curs[0] = int("0") if "-RA-" in u_curs[2]: u_curs[0] = int("0") print "North Azimuth = " + str(u_curs[0]) u_curs_BlockCenterline.updateRow(u_curs) array.removeAll() #Reset to an empty array for next iteration of the loop.
def RotateFeatureClass(inputFC, outputFC, angle=0, pivot_point=None): """Rotate Feature Class inputFC Input features outputFC Output feature class angle Angle to rotate, in degrees pivot_point X,Y coordinates (as space-separated string) Default is lower-left of inputFC As the output feature class no longer has a "real" xy locations, after rotation, it no coordinate system defined. """ def RotateXY(x, y, xc=0, yc=0, angle=0, units="DEGREES"): """Rotate an xy cooordinate about a specified origin x,y xy coordinates xc,yc center of rotation angle angle units "DEGREES" (default) or "RADIANS" """ x = x - xc y = y - yc # make angle clockwise (like Rotate_management) angle = angle * -1 if units == "DEGREES": angle = math.radians(angle) xr = (x * math.cos(angle)) - (y * math.sin(angle)) + xc yr = (x * math.sin(angle)) + (y * math.cos(angle)) + yc return xr, yr # temp names for cleanup env_file = None lyrFC, lyrTmp, lyrOut = [None] * 3 # layers tmpFC = None # temp dataset Row, Rows, oRow, oRows = [None] * 4 # cursors try: # process parameters try: xcen, ycen = [float(xy) for xy in pivot_point.split()] pivot_point = xcen, ycen except: # if pivot point was not specified, get it from # the lower-left corner of the feature class ext = arcpy.Describe(inputFC).extent xcen, ycen = ext.XMin, ext.YMin pivot_point = xcen, ycen angle = float(angle) # set up environment env_file = arcpy.CreateScratchName("xxenv",".xml","file", os.environ["TEMP"]) arcpy.SaveSettings(env_file) WKS = env.workspace if not WKS: if os.path.dirname(outputFC): WKS = os.path.dirname(outputFC) else: WKS = os.path.dirname( arcpy.Describe(inputFC).catalogPath) env.workspace = env.scratchWorkspace = WKS # Disable any GP environment clips arcpy.ClearEnvironment("extent") # get feature class properties lyrFC = 'lyrFC' arcpy.MakeFeatureLayer_management(inputFC, lyrFC) dFC = arcpy.Describe(lyrFC) shpField = dFC.shapeFieldName shpType = dFC.shapeType # create temp feature class tmpFC = arcpy.CreateScratchName("xxfc", "", "featureclass") arcpy.CreateFeatureclass_management(os.path.dirname(tmpFC), os.path.basename(tmpFC), shpType) lyrTmp = 'lyrTmp' arcpy.MakeFeatureLayer_management(tmpFC, lyrTmp) # set up grid field gridField = "Grid" arcpy.AddField_management(lyrTmp, gridField, "TEXT") arcpy.DeleteField_management(lyrTmp, 'ID') # rotate the feature class coordinates # open read and write cursors Rows = arcpy.SearchCursor(lyrFC, "", "", "%s;%s;" % (shpField,'Grid')) oRows = arcpy.InsertCursor(lyrTmp) arcpy.AddMessage("Opened search cursor") parts = arcpy.Array() rings = arcpy.Array() ring = arcpy.Array() for Row in Rows: shp = Row.getValue(shpField) p = 0 for part in shp: for pnt in part: if pnt: x, y = RotateXY(pnt.X, pnt.Y, xcen, ycen, angle) ring.add(arcpy.Point(x, y, pnt.ID)) else: # if we have a ring, save it if len(ring) > 0: rings.add(ring) ring.removeAll() # we have our last ring, add it rings.add(ring) ring.removeAll() # if only one, remove nesting if len(rings) == 1: rings = rings.getObject(0) parts.add(rings) rings.removeAll() p += 1 # if only one, remove nesting if len(parts) == 1: parts = parts.getObject(0) if dFC.shapeType == "Polyline": shp = arcpy.Polyline(parts) else: shp = arcpy.Polygon(parts) parts.removeAll() oRow = oRows.newRow() oRow.setValue(shpField, shp) oRow.setValue('Grid', Row.getValue('Grid')) oRows.insertRow(oRow) del oRow, oRows # close write cursor (ensure buffer written) oRow, oRows = None, None # restore variables for cleanup env.qualifiedFieldNames = False arcpy.Merge_management(lyrTmp, outputFC) lyrOut = 'lyrOut' arcpy.MakeFeatureLayer_management(outputFC, lyrOut) except MsgError as xmsg: arcpy.AddError(str(xmsg)) except arcpy.ExecuteError: tbinfo = traceback.format_tb(sys.exc_info()[2])[0] arcpy.AddError(tbinfo.strip()) arcpy.AddError(arcpy.GetMessages()) numMsg = arcpy.GetMessageCount() for i in range(0, numMsg): arcpy.AddReturnMessage(i) except Exception as xmsg: tbinfo = traceback.format_tb(sys.exc_info()[2])[0] arcpy.AddError(tbinfo + str(xmsg)) finally: # reset environment if env_file: arcpy.LoadSettings(env_file) # Clean up temp files for f in [lyrFC, lyrTmp, lyrOut, tmpFC, env_file]: try: if f: arcpy.Delete_management(f) except: pass # delete cursors try: for c in [Row, Rows, oRow, oRows]: del c except: pass # return pivot point try: pivot_point = "{0} {1}".format(*pivot_point) except: pivot_point = None return pivot_point
# writes geometries from the list of coordinate pairs import csv import arcpy # Set up input and output variables for the script gpsTrack = open("C:\\data\\Geog485\\gps_track.txt", "r") polylineFC = "C:\\data\\Geog485\\tracklines.shp" spatialRef = arcpy.Describe(polylineFC).spatialReference # Set up CSV reader and process the header csvReader = csv.reader(gpsTrack) header = csvReader.next() latIndex = header.index("lat") lonIndex = header.index("long") # Create an empty array object vertexArray = arcpy.Array() # Loop through the lines in the file and get each coordinate for row in csvReader: lat = row[latIndex] lon = row[lonIndex] # Make a point from the coordinate and add it to the array vertex = arcpy.Point(lon,lat) vertexArray.add(vertex) # Write the array to the feature class as a polyline feature with arcpy.da.InsertCursor(polylineFC, ("SHAPE@",)) as cursor: polyline = arcpy.Polyline(vertexArray, spatialRef) cursor.insertRow((polyline,))
def linemiddlepoint_point(): """ メソッド名 : linemiddlepoint_point 概要 : ラインの中間点からポイントへ変換 """ try: arcpy.AddMessage(u"処理開始:") in_line_fc = arcpy.GetParameterAsText(0) out_pt_fc = arcpy.GetParameterAsText(1) # ワークスペース wstype = arcpy.Describe(os.path.dirname(out_pt_fc)).workspacetype # ワークスペースにすでに同一のフィーチャクラス名がないかチェック if arcpy.Exists(out_pt_fc): raise AlreadyExistError # カーソル作成に使用するフィールド情報を create_fieldinfo 関数を用いて取得 search_fields_name, search_fields_type, use_fields_name, spref = create_fieldinfo(in_line_fc, out_pt_fc) # 2021.03.19: 追記 - 座標系をインプットから取得 #Polyline 作成時の引数に、座標系を指定していないと、ジオメトリが空になり、multiLine.positionAlongLine で例外が発生する場合がある spref = arcpy.Describe(in_line_fc).spatialReference # 2021.03.19: 変更 - 例外発生時にロックが残ってしまうので、with に変更 # フィーチャクラスの検索カーソル作成 #incur = arcpy.da.SearchCursor(in_line_fc, search_fields_name) # フィーチャクラスの挿入カーソル作成 #outcur = arcpy.da.InsertCursor(out_pt_fc, use_fields_name) with arcpy.da.SearchCursor(in_line_fc, search_fields_name) as incur: with arcpy.da.InsertCursor(out_pt_fc, use_fields_name) as outcur: i = 0 num = int(arcpy.GetCount_management(in_line_fc).getOutput(0)) # フィーチャ(ジオメトリ)の数 for inrow in incur: i = i + 1 if (i == 1) or (i == num) or (i % 1000 == 1): s = u"{0}/{1}の処理中・・・".format(i, num) arcpy.AddMessage(s) newValue = [] # 出力がShape ファイルの場合、NULL 値を格納できないため # フィールドのタイプに合わせて、空白や 0 を格納する if wstype == "FileSystem": for j, value in enumerate(inrow): if value == None: if search_fields_type[j] == "String": newValue.append("") elif search_fields_type[j] in ["Double", "Integer", "Single", "SmallInteger"]: newValue.append(0) else: newValue.append(value) else: newValue.append(value) # GDB は NULL 値を格納可能 else: newValue = list(inrow) # パートの数 for part in inrow[-1]: # マルチラインに対してそれぞれ中間点を取るためにパートからラインを生成する(パートを考慮する必要がなければ inrow[-1] に対して中間点を取ればよい) multiLine = arcpy.Polyline( arcpy.Array([coords for coords in part]),spref) # 2021.03.19: Poline 作成時の空間参照を指定に変更 # arcpy.Array([coords for coords in part])) # ジオメトリにラインの中間点ポイントを格納 newValue[-1] = multiLine.positionAlongLine(0.5,True) # リストからタプルに変換してインサート outcur.insertRow(tuple(newValue)) # # 2021.03.19: with に変更したので不要 # del outcur # del incur arcpy.AddMessage(u"処理終了:") except AlreadyExistError: arcpy.AddError(u"{0}はすでに存在しています".format(out_pt_fc)) except arcpy.ExecuteError: arcpy.AddError(arcpy.GetMessages(2)) except Exception as e: arcpy.AddError(e.args[0])
# If the elk SN isn't in the dictionary: if not elk in elk_dictionary: # Create a new Array object & add the point to it, put the array into the dictionary using the SN coord_array = arcpy.Array() coord_array.add(coords) elk_dictionary[elk] = coord_array else: # Retrieve the existing Array and add the new point for that elk coord_array = elk_dictionary[elk] coord_array.add(coords) except: arcpy.AddMessage('Dictionary setup and/or population failed') try: # Loop through the elk in the dictionary to... for key in elk_dictionary: # Create an insert cursor with arcpy.da.InsertCursor(feature_class, update_fields) as cursor: # Create a polyline polyline = arcpy.Polyline(elk_dictionary[key], spatial_ref) row = (str(key), polyline) # Insert a new row into the feature class for each elk cursor.insertRow(row) except: arcpy.AddMessage('Inserting the records into a polyline failed') arcpy.AddMessage(arcpy.GetMessages(2)) arcpy.AddMessage(arcpy.GetMessages(3))