Exemple #1
0
def linetoCut(outPoint):

    bearingFeature = os.path.join(
        scratch, 'bearingFeature.shp')  #r"in_memory/bearingFeature"#
    arcpy.BearingDistanceToLine_management(outPoint[:-4] + ".dbf",
                                           r"in_memory/tB", 'POINT_X',
                                           "POINT_Y", 'BearingD', 'FEET',
                                           'Angle', 'DEGREES', 'GEODESIC', "",
                                           srGCS83)
    arcpy.BearingDistanceToLine_management(outPoint[:-4] + ".dbf",
                                           r"in_memory/tBB", 'POINT_X',
                                           "POINT_Y", 'BearingD', 'FEET',
                                           'Angle1', 'DEGREES', 'GEODESIC', "",
                                           srGCS83)

    arcpy.Merge_management(["in_memory/tB", "in_memory/tBB"], bearingFeature)
    rows = arcpy.da.SearchCursor(bearingFeature, ['Shape@'])
    for row in rows:
        BearingLine.append([[row[0].firstPoint.X, row[0].firstPoint.Y],
                            [row[0].lastPoint.X, row[0].lastPoint.Y]])
    del rows

    if OrderType.lower() == 'point':
        temp1 = r"in_memory/bearingFeature"  #os.path.join(scratch,'bearingFeature.shp')#
        arcpy.Dissolve_management(bearingFeature,
                                  temp1,
                                  dissolve_field="Angle;Angle1")
        bearingFeature = temp1
    arcpy.MakeFeatureLayer_management(bearingFeature, 'bearingFeature')
    com = tuple(
        itertools.combinations(
            [r[0] for r in arcpy.da.SearchCursor(bearingFeature, ["OID@"])],
            2))
    comlist = []
    for i in range(len(com)):
        id1 = com[i][0]
        id2 = com[i][1]
        arcpy.SelectLayerByAttribute_management(
            'bearingFeature', "NEW_SELECTION",
            '"FID" =%s OR "FID" = %s ' % (id1, id2))
        temp = os.path.join("in_memory", 'com' + str(i))
        arcpy.Dissolve_management('bearingFeature', temp)
        comlist.append(temp)
    arcpy.Merge_management(comlist, "in_memory/cut")

    lines = {}
    with arcpy.da.SearchCursor("in_memory/cut", ["SHAPE@", "OID@"]) as lcursor:
        for line in lcursor:
            if (line[0].firstPoint.X, line[0].firstPoint.Y,
                    line[0].lastPoint.X,
                    line[0].lastPoint.Y) not in lines.keys():
                lines[(line[0].firstPoint.X, line[0].firstPoint.Y,
                       line[0].lastPoint.X, line[0].lastPoint.Y)] = (line[0],
                                                                     line[1])
    del lcursor
    arcpy.CopyFeatures_management("in_memory/cut",
                                  os.path.join(scratch, "cutline.shp"))
    return lines.values()
Exemple #2
0
    def makeRadials(self, numRadials):
        ''' make geodesic radials from number of radials '''
        segmentAngle = 360.0 / float(numRadials)
        segmentAngleList = []
        a = 0.0
        while a < 360.0:
            segmentAngleList.append(a)
            a += segmentAngle

        fields = {
            'x': 'DOUBLE',
            'y': 'DOUBLE',
            'Bearing': 'DOUBLE',
            'Range': 'DOUBLE'
        }
        tab = self._makeTempTable("radTable", fields)
        cursor = arcpy.da.InsertCursor(tab, ['x', 'y', 'Bearing', 'Range'])
        for i in self.center:
            pt = i.firstPoint
            for r in segmentAngleList:
                cursor.insertRow([pt.X, pt.Y, r, self.ringMax])
        del cursor
        self.deleteme.append(tab)
        outRadialFeatures = os.path.join("in_memory", "outRadials")
        arcpy.BearingDistanceToLine_management(tab, outRadialFeatures, 'x',
                                               'y', 'Range',
                                               self.distanceUnits, 'Bearing',
                                               "DEGREES", "GEODESIC", "#",
                                               self.sr)
        self.deleteme.append(outRadialFeatures)
        self.radialFeatures = outRadialFeatures
        return outRadialFeatures
Exemple #3
0
def calculatePerpendicularAngles(inputFeatureClass, outputFCLines, angleField,
                                 maxDistance, fieldID):

    #tempPoints = "in_memory\\TempPoints" #C:\\GIS\\StreamNetworkConfinementOutputGeodatabase01.gdb
    fcAngleLines0 = "in_memory\\Angle0"
    fcAngleLines180 = "in_memory\\Angle180"
    fcAngleMerge = "in_memory\\AngleMerge"

    #resetData(tempPoints)
    #arcpy.CopyFeatures_management(inputFeatureClass,tempPoints)
    arcpy.AddField_management(inputFeatureClass, "Angle0", "Double")
    arcpy.AddField_management(inputFeatureClass, "Angle180", "Double")
    arcpy.AddField_management(inputFeatureClass, "AngleDistance", "Double")

    arcpy.CalculateField_management(inputFeatureClass, "Angle0",
                                    "( !" + angleField + "! - 90 )*(-1)",
                                    "PYTHON")
    arcpy.CalculateField_management(inputFeatureClass, "Angle180",
                                    "!Angle0!+180", "PYTHON")
    arcpy.CalculateField_management(inputFeatureClass, "AngleDistance",
                                    str(maxDistance / 2), "PYTHON")

    #arcpy.AddXY_management(inputFeatureClass)

    resetData(fcAngleLines0)
    resetData(fcAngleLines180)
    arcpy.BearingDistanceToLine_management(inputFeatureClass, fcAngleLines0,
                                           "POINT_X", "POINT_Y",
                                           "AngleDistance", "#", "Angle0",
                                           "DEGREES", "GEODESIC", fieldID)
    arcpy.BearingDistanceToLine_management(inputFeatureClass, fcAngleLines180,
                                           "POINT_X", "POINT_Y",
                                           "AngleDistance", "#", "Angle180",
                                           "DEGREES", "GEODESIC", fieldID)

    resetData(fcAngleMerge)
    arcpy.Merge_management([fcAngleLines180, fcAngleLines0], fcAngleMerge)

    resetData(outputFCLines)
    arcpy.UnsplitLine_management(fcAngleMerge, outputFCLines, fieldID)

    return
Exemple #4
0
    def strikeToLine(self, xytable):
        """ Convert strike tabular data to shapefile polyline
        Input: xytable
            xytable: tabular data contain x and y coordinates
        Output: outdir
            outdir: directory or folder of output shapefile polyline
        """
        # Set coordinate system of future shapefile
        prj, outdir = self.prj, self.outdir

        # Import csv file already calculated by dirToAz method
        pt = "/Input/DirazCalculated.csv"  # don't use pandas DataFrame as an input data
        # A dataframe that contain the caracteristic of different output shp file
        ft = pd.DataFrame(
            [['ln', 'lnc', 'dipln', 'merge'], ['stk', 'stk', 'dipaz', 'merge'],
             ['St1.shp', 'St2.shp', 'DipAzimut.shp', 'St_Strike.shp']],
            columns=['Measure1', 'Measure2', 'DipAz', 'Strike'])
        for i in range(len(ft) + 1):
            if 'merge' == ft.iloc[0, i]:
                arcpy.Merge_management(
                    [outdir + ft.iloc[2, 0], outdir + ft.iloc[2, 1]],
                    outdir + ft.iloc[2, 3])
                arcpy.Dissolve_management(outdir + ft.iloc[2, 3],
                                          outdir + "Direction.shp", "id", "",
                                          "MULTI_PART", "DISSOLVE_LINES")
                print '--- Your tabular data is converted in shapefile successfully !---'
            else:
                arcpy.BearingDistanceToLine_management(
                    in_table=pt,
                    out_featureclass=outdir + ft.iloc[2, i],
                    x_field='x',
                    y_field='y',
                    distance_field=ft.iloc[0, i],
                    distance_units="METERS",
                    bearing_field=ft.iloc[1, i],
                    bearing_units="DEGREES",
                    line_type="GEODESIC",
                    id_field='id',
                    spatial_reference=prj)
        return
Exemple #5
0
        row[8] = Azline2(row[4])
        #Set distance to the length of the transect divided by 2, the transect scripts creates the length on either side of the streamline
        #So if the input width it 30 ft, it will create 30 ft on each side (=60 ft), we only want the total to be 30 ft
        row[10] = row[9] / 2
        iter2 = iter2 + 1
        arcpy.SetProgressorPosition()
        updateRows.updateRow(row)
    del updateRows
    del row

    #Generate Azline1 and Azline2
    Azline1 = "Azline1"
    Azline2 = "Azline2"
    #Hard-coded as FEET below, I don't think I need to change that.
    arcpy.BearingDistanceToLine_management(LineSplit, Azline1, "X_mid",
                                           "Y_mid", "Distance", "FEET",
                                           "AziLine_1", "DEGREES", "GEODESIC",
                                           "LineID", spatial_reference)
    arcpy.BearingDistanceToLine_management(LineSplit, Azline2, "X_mid",
                                           "Y_mid", "Distance", "FEET",
                                           "AziLine_2", "DEGREES", "GEODESIC",
                                           "LineID", spatial_reference)

    #Create Azline and append Azline1 and Azline2
    Azline = "Azline"
    arcpy.CreateFeatureclass_management(General_GDB, "Azline", "POLYLINE", "",
                                        "", "", spatial_reference)
    arcpy.AddField_management(Azline, "LineID", "DOUBLE")
    arcpy.Append_management([Azline1, Azline2], Azline, "NO_TEST")

    #Dissolve Azline
    Azline_Dissolve = "Azline_Dissolve"
Exemple #6
0
def tableToLineOfBearing(inputTable, inputCoordinateFormat, inputXField,
                         inputYField, inputBearingUnits, inputBearingField,
                         inputDistanceUnits, inputDistanceField,
                         outputLineFeatures, inputLineType,
                         inputSpatialReference):
    '''
    Tool method for converting a table of starting points, bearings, and distances
    to line features.
    
    inputTable - input table, each row will be a separate line feature in output
    inputCoordinateFormat - coordinate notation format of input vertices
    inputXField - field in inputTable for vertex x-coordinate, or full coordinate
    inputYField - field in inputTable for vertex y-coordinate, or None
    inputBearingUnits -
    inputBearingField -
    inputDistanceUnits -
    inputDistanceField -
    outputLineFeatures - polyline feature class to create
    inputLineType - 
    inputSpatialReference - spatial reference of input coordinates
    
    returns polyline feature class
    
    inputCoordinateFormat must be one of the following:
    * DD_1: Both longitude and latitude values are in a single field. Two values are separated by a space, a comma, or a slash.
    * DD_2: Longitude and latitude values are in two separate fields.
    * DDM_1: Both longitude and latitude values are in a single field. Two values are separated by a space, a comma, or a slash.
    * DDM_2: Longitude and latitude values are in two separate fields.
    * DMS_1: Both longitude and latitude values are in a single field. Two values are separated by a space, a comma, or a slash.
    * DMS_2: Longitude and latitude values are in two separate fields.
    * GARS: Global Area Reference System. Based on latitude and longitude, it divides and subdivides the world into cells.
    * GEOREF: World Geographic Reference System. A grid-based system that divides the world into 15-degree quadrangles and then subdivides into smaller quadrangles.
    * UTM_ZONES: The letter N or S after the UTM zone number designates only North or South hemisphere.
    * UTM_BANDS: The letter after the UTM zone number designates one of the 20 latitude bands. N or S does not designate a hemisphere.
    * USNG: United States National Grid. Almost exactly the same as MGRS but uses North American Datum 1983 (NAD83) as its datum.
    * MGRS: Military Grid Reference System. Follows the UTM coordinates and divides the world into 6-degree longitude and 20 latitude bands, but MGRS then further subdivides the grid zones into smaller 100,000-meter grids. These 100,000-meter grids are then divided into 10,000-meter, 1,000-meter, 100-meter, 10-meter, and 1-meter grids.
    
    inputBearingUnits must be one of the following:
    * DEGREES
    * MILS
    * RADS
    * GRAD
    
    inputDistanceUnits must be one of the following:
    * METERS
    * KILOMETERS
    * MILES
    * NAUTICAL_MILES
    * FEET
    * US_SURVEY_FEET
    
    inputLineType must be one of the following:
    * GEODESIC:
    * GREAT_CIRCLE:
    * RHUMB_LINE:
    * NORMAL_SECTION:
    
    '''
    try:
        env.overwriteOutput = True

        deleteme = []
        joinFieldName = "JoinID"
        scratch = '%scratchGDB%'
        if env.scratchWorkspace:
            scratch = env.scratchWorkspace

        inputSpatialReference = _checkSpatialRef(inputSpatialReference)

        copyRows = os.path.join(scratch, "copyRows")
        arcpy.CopyRows_management(inputTable, copyRows)
        originalTableFieldNames = _tableFieldNames(inputTable,
                                                   joinExcludeFields)
        addUniqueRowID(copyRows, joinFieldName)

        arcpy.AddMessage("Formatting start point...")
        copyCCN = os.path.join(scratch, "copyCCN")
        arcpy.ConvertCoordinateNotation_management(copyRows, copyCCN,
                                                   inputXField, inputYField,
                                                   inputCoordinateFormat,
                                                   "DD_NUMERIC", joinFieldName,
                                                   inputSpatialReference)

        arcpy.AddMessage("Creating lines as {0}...".format(inputLineType))
        arcpy.BearingDistanceToLine_management(
            copyCCN, outputLineFeatures, "DDLon", "DDLat", inputDistanceField,
            inputDistanceUnits, inputBearingField, inputBearingUnits,
            inputLineType, joinFieldName, inputSpatialReference)

        #Join original table fields to output
        arcpy.AddMessage(
            "Joining fields from input table to output line features...")
        arcpy.JoinField_management(outputLineFeatures, joinFieldName, copyRows,
                                   joinFieldName, originalTableFieldNames)
        arcpy.DeleteField_management(outputLineFeatures, [joinFieldName])

        return outputLineFeatures

    except arcpy.ExecuteError:
        # Get the tool error messages
        msgs = arcpy.GetMessages()
        arcpy.AddError(msgs)
        print(msgs)

    except:
        # Get the traceback object
        tb = sys.exc_info()[2]
        tbinfo = traceback.format_tb(tb)[0]

        # Concatenate information together concerning the error into a message string
        pymsg = "PYTHON ERRORS:\nTraceback info:\n" + tbinfo + "\nError Info:\n" + str(
            sys.exc_info()[1])
        msgs = "ArcPy ERRORS:\n" + arcpy.GetMessages() + "\n"

        # Return python error messages for use in script tool or Python Window
        arcpy.AddError(pymsg)
        arcpy.AddError(msgs)

        # Print Python error messages for use in Python / Python Window
        print(pymsg + "\n")
        print(msgs)

    finally:
        if len(deleteme) > 0:
            # cleanup intermediate datasets
            if debug == True:
                arcpy.AddMessage("Removing intermediate datasets...")
            for i in deleteme:
                if debug == True: arcpy.AddMessage("Removing: " + str(i))
                arcpy.Delete_management(i)
            if debug == True: arcpy.AddMessage("Done")
                addRow.RingID = y
                addRows.insertRow(addRow)
            y += 1
        del addRow
        del addRows
        del getRow
        del getRows

        results = arcpy.GetCount_management(tempRadialTable)

        # build ellipses
        arcpy.AddMessage("Constructing " + str(results) +
                         " radial features ...")
        arcpy.BearingDistanceToLine_management(tempRadialTable, outputRadials,
                                               "POINT_X", "POINT_Y", "Range",
                                               distanceUnits, "Azimuth",
                                               bearingUnits, "RHUMB_LINE",
                                               "RingID", inputCentersSR)

        # Join fields
        tempRadialTableOIDFieldName = arcpy.Describe(
            tempRadialTable).OIDFieldName
        radialOIDFieldName = arcpy.Describe(outputRadials).OIDFieldName
        #arcpy.JoinField_management(outputRadials,radialOIDFieldName,tempRadialTable,tempRadialTableOIDFieldName,["Azimuth","Range","RingID"])

    else:
        arcpy.AddMessage("Zero radials to build ...")

    # set output
    arcpy.SetParameter(3, outputRings)
    if buildRadials == True:
Exemple #8
0
# Set local variables
## Were using a Concatenate to make the path of the folderpath
## This combines the filename and filepath so the OS can read it.
line_1 = os.path.join(str(TempDir), "line_1.shp")
line_2 = os.path.join(str(TempDir), "line_2.shp")
line_3 = os.path.join(str(TempDir), "line_3.shp")
lines = os.path.join(str(TempDir), "ObservationLines.shp")
startpoint_1 = os.path.join(str(TempDir), "ObsPoint1")
startpoint_2 = os.path.join(str(TempDir), "ObsPoint2")
startpoint_3 = os.path.join(str(TempDir), "ObsPoint3")
startpoints = os.path.join(str(TempDir), "ObservationPoints.shp")

# Create lines and points
## Process: bearings and distances to lines
arcpy.BearingDistanceToLine_management(filepath, line_1, "lon1", "lat1",
                                       "dist", "METERS", "az1", "DEGREES",
                                       "GEODESIC", "", wgs)
arcpy.BearingDistanceToLine_management(filepath, line_2, "lon2", "lat2",
                                       "dist", "METERS", "az2", "DEGREES",
                                       "GEODESIC", "", wgs)
arcpy.BearingDistanceToLine_management(filepath, line_3, "lon3", "lat3",
                                       "dist", "METERS", "az3", "DEGREES",
                                       "GEODESIC", "", wgs)

## Make XY Event Layers: creating of start points in WGS84 using inputed data
arcpy.MakeXYEventLayer_management(filepath, "lon1", "lat1", startpoint_1, wgs,
                                  "")
arcpy.MakeXYEventLayer_management(filepath, "lon2", "lat2", startpoint_2, wgs,
                                  "")
arcpy.MakeXYEventLayer_management(filepath, "lon3", "lat3", startpoint_3, wgs,
                                  "")
def generate_transects(workspacePath, lineFL, splitType,
                       distanceBetweenTransects, transectWidth, widthUnit,
                       outputFC):
    import arcpy
    import math

    #Set environments
    arcpy.env.overwriteOutput = True
    arcpy.env.XYResolution = "0.00001 Meters"
    arcpy.env.XYTolerance = "0.0001 Meters"

    # Set local variables
    arcpy.env.workspace = workspacePath
    Lines = lineFL
    SplitType = splitType
    DistanceSplit = float(distanceBetweenTransects)
    TransecLength = transectWidth
    TransecLength_Unit = widthUnit
    OutputTransect = outputFC

    # Def splitline module
    ###START SPLIT LINE CODE IN A SAME DISTANCE### Source: http://nodedangles.wordpress.com/2011/05/01/quick-dirty-arcpy-batch-splitting-polylines-to-a-specific-length/
    def splitline(inFC, FCName, alongDist):

        OutDir = arcpy.env.workspace
        outFCName = FCName
        outFC = OutDir + "/" + outFCName

        def distPoint(p1, p2):
            calc1 = p1.X - p2.X
            calc2 = p1.Y - p2.Y

            return math.sqrt((calc1**2) + (calc2**2))

        def midpoint(prevpoint, nextpoint, targetDist, totalDist):
            newX = prevpoint.X + ((nextpoint.X - prevpoint.X) *
                                  (targetDist / totalDist))
            newY = prevpoint.Y + ((nextpoint.Y - prevpoint.Y) *
                                  (targetDist / totalDist))
            return arcpy.Point(newX, newY)

        def splitShape(feat, splitDist):
            # Count the number of points in the current multipart feature
            #
            partcount = feat.partCount
            partnum = 0
            # Enter while loop for each part in the feature (if a singlepart feature
            # this will occur only once)
            #
            lineArray = arcpy.Array()

            while partnum < partcount:
                # Print the part number
                #
                #print "Part " + str(partnum) + ":"
                part = feat.getPart(partnum)
                #print part.count

                totalDist = 0

                pnt = part.next()
                pntcount = 0

                prevpoint = None
                shapelist = []

                # Enter while loop for each vertex
                #
                while pnt:

                    if not (prevpoint is None):
                        thisDist = distPoint(prevpoint, pnt)
                        maxAdditionalDist = splitDist - totalDist

                        #print thisDist, totalDist, maxAdditionalDist

                        if (totalDist + thisDist) > splitDist:
                            while (totalDist + thisDist) > splitDist:
                                maxAdditionalDist = splitDist - totalDist
                                #print thisDist, totalDist, maxAdditionalDist
                                newpoint = midpoint(prevpoint, pnt,
                                                    maxAdditionalDist,
                                                    thisDist)
                                lineArray.add(newpoint)
                                shapelist.append(lineArray)

                                lineArray = arcpy.Array()
                                lineArray.add(newpoint)
                                prevpoint = newpoint
                                thisDist = distPoint(prevpoint, pnt)
                                totalDist = 0

                            lineArray.add(pnt)
                            totalDist += thisDist
                        else:
                            totalDist += thisDist
                            lineArray.add(pnt)
                            #shapelist.append(lineArray)
                    else:
                        lineArray.add(pnt)
                        totalDist = 0

                    prevpoint = pnt
                    pntcount += 1

                    pnt = part.next()

                    # If pnt is null, either the part is finished or there is an
                    #   interior ring
                    #
                    if not pnt:
                        pnt = part.next()
                        #if pnt:
                        #print "Interior Ring:"
                partnum += 1

            if (lineArray.count > 1):
                shapelist.append(lineArray)

            return shapelist

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

        arcpy.Copy_management(inFC, outFC)

        #origDesc = arcpy.Describe(inFC)
        #sR = origDesc.spatialReference

        #revDesc = arcpy.Describe(outFC)
        #revDesc.ShapeFieldName

        deleterows = arcpy.UpdateCursor(outFC)
        for iDRow in deleterows:
            deleterows.deleteRow(iDRow)

        try:
            del iDRow
            del deleterows
        except:
            pass

        inputRows = arcpy.SearchCursor(inFC)
        outputRows = arcpy.InsertCursor(outFC)
        fields = arcpy.ListFields(inFC)

        numRecords = int(arcpy.GetCount_management(inFC).getOutput(0))
        OnePercentThreshold = numRecords // 100

        #printit(numRecords)

        iCounter = 0
        iCounter2 = 0

        for iInRow in inputRows:
            inGeom = iInRow.shape
            iCounter += 1
            iCounter2 += 1
            if (iCounter2 > (OnePercentThreshold + 0)):
                #printit("Processing Record "+str(iCounter) + " of "+ str(numRecords))
                iCounter2 = 0

            if (inGeom.length > alongDist):
                shapeList = splitShape(iInRow.shape, alongDist)

                for itmp in shapeList:
                    newRow = outputRows.newRow()
                    for ifield in fields:
                        if (ifield.editable):
                            newRow.setValue(ifield.name,
                                            iInRow.getValue(ifield.name))
                    newRow.shape = itmp
                    outputRows.insertRow(newRow)
            else:
                outputRows.insertRow(iInRow)

        del inputRows
        del outputRows

        #printit("Done!")

    ###END SPLIT LINE CODE IN A SAME DISTANCE###

    # Create "General" file geodatabase
    WorkFolder = arcpy.env.workspace
    General_GDB = WorkFolder + "\General.gdb"
    arcpy.CreateFileGDB_management(WorkFolder, "General", "CURRENT")
    arcpy.env.workspace = General_GDB

    #Unsplit Line
    LineDissolve = "LineDissolve"
    arcpy.Dissolve_management(Lines, LineDissolve, "", "", "SINGLE_PART")
    LineSplit = "LineSplit"

    #Split Line
    if SplitType == "Split at approximate distance":
        splitline(LineDissolve, LineSplit, DistanceSplit)
    else:
        arcpy.SplitLine_management(LineDissolve, LineSplit)

    #Add fields to LineSplit
    FieldsNames = [
        "LineID", "Direction", "Azimuth", "X_mid", "Y_mid", "AziLine_1",
        "AziLine_2", "Distance"
    ]
    for fn in FieldsNames:
        arcpy.AddField_management(LineSplit, fn, "DOUBLE")

    #Calculate Fields
    CodeBlock_Direction = """def GetAzimuthPolyline(shape):
     radian = math.atan((shape.lastpoint.x - shape.firstpoint.x)/(shape.lastpoint.y - shape.firstpoint.y))
     degrees = radian * 180 / math.pi
     return degrees"""

    CodeBlock_Azimuth = """def Azimuth(direction):
     if direction < 0:
      azimuth = direction + 360
      return azimuth
     else:
      return direction"""
    CodeBlock_NULLS = """def findNulls(fieldValue):
        if fieldValue is None:
            return 0
        elif fieldValue is not None:
            return fieldValue"""
    arcpy.CalculateField_management(LineSplit, "LineID", "!OBJECTID!",
                                    "PYTHON_9.3")
    arcpy.CalculateField_management(LineSplit, "Direction",
                                    "GetAzimuthPolyline(!Shape!)",
                                    "PYTHON_9.3", CodeBlock_Direction)
    arcpy.CalculateField_management(LineSplit, "Direction",
                                    "findNulls(!Direction!)", "PYTHON_9.3",
                                    CodeBlock_NULLS)
    arcpy.CalculateField_management(LineSplit, "Azimuth",
                                    "Azimuth(!Direction!)", "PYTHON_9.3",
                                    CodeBlock_Azimuth)
    arcpy.CalculateField_management(
        LineSplit, "X_mid", "!Shape!.positionAlongLine(0.5,True).firstPoint.X",
        "PYTHON_9.3")
    arcpy.CalculateField_management(
        LineSplit, "Y_mid", "!Shape!.positionAlongLine(0.5,True).firstPoint.Y",
        "PYTHON_9.3")
    CodeBlock_AziLine1 = """def Azline1(azimuth):
     az1 = azimuth + 90
     if az1 > 360:
      az1-=360
      return az1
     else:
      return az1"""
    CodeBlock_AziLine2 = """def Azline2(azimuth):
     az2 = azimuth - 90
     if az2 < 0:
      az2+=360
      return az2
     else:
      return az2"""
    arcpy.CalculateField_management(LineSplit, "AziLine_1",
                                    "Azline1(!Azimuth!)", "PYTHON_9.3",
                                    CodeBlock_AziLine1)
    arcpy.CalculateField_management(LineSplit, "AziLine_2",
                                    "Azline2(!Azimuth!)", "PYTHON_9.3",
                                    CodeBlock_AziLine2)
    arcpy.CalculateField_management(LineSplit, "Distance", TransecLength,
                                    "PYTHON_9.3")

    #Generate Azline1 and Azline2
    spatial_reference = arcpy.Describe(Lines).spatialReference
    Azline1 = "Azline1"
    Azline2 = "Azline2"
    arcpy.BearingDistanceToLine_management(LineSplit, Azline1, "X_mid",
                                           "Y_mid", "Distance",
                                           TransecLength_Unit, "AziLine_1",
                                           "DEGREES", "GEODESIC", "LineID",
                                           spatial_reference)
    arcpy.BearingDistanceToLine_management(LineSplit, Azline2, "X_mid",
                                           "Y_mid", "Distance",
                                           TransecLength_Unit, "AziLine_2",
                                           "DEGREES", "GEODESIC", "LineID",
                                           spatial_reference)

    #Create Azline and append Azline1 and Azline2
    Azline = "Azline"
    arcpy.CreateFeatureclass_management(arcpy.env.workspace, "Azline",
                                        "POLYLINE", "", "", "",
                                        spatial_reference)
    arcpy.AddField_management(Azline, "LineID", "DOUBLE")
    arcpy.Append_management([Azline1, Azline2], Azline, "NO_TEST")

    #Dissolve Azline
    Azline_Dissolve = "Azline_Dissolve"
    arcpy.Dissolve_management(Azline, Azline_Dissolve, "LineID", "",
                              "SINGLE_PART")

    #Add Fields to Azline_Dissolve
    FieldsNames2 = ["x_start", "y_start", "x_end", "y_end"]
    for fn2 in FieldsNames2:
        arcpy.AddField_management(Azline_Dissolve, fn2, "DOUBLE")

    #Calculate Azline_Dissolve fields
    arcpy.CalculateField_management(
        Azline_Dissolve, "x_start",
        "!Shape!.positionAlongLine(0,True).firstPoint.X", "PYTHON_9.3")
    arcpy.CalculateField_management(
        Azline_Dissolve, "y_start",
        "!Shape!.positionAlongLine(0,True).firstPoint.Y", "PYTHON_9.3")
    arcpy.CalculateField_management(
        Azline_Dissolve, "x_end",
        "!Shape!.positionAlongLine(1,True).firstPoint.X", "PYTHON_9.3")
    arcpy.CalculateField_management(
        Azline_Dissolve, "y_end",
        "!Shape!.positionAlongLine(1,True).firstPoint.Y", "PYTHON_9.3")

    #Generate output file
    arcpy.XYToLine_management(Azline_Dissolve, OutputTransect, "x_start",
                              "y_start", "x_end", "y_end", "", "",
                              spatial_reference)

    #Delete General.gdb
    arcpy.Delete_management(General_GDB)
def XSLayout(output_workspace, flowline, split_type, transect_spacing,
             transect_width, transect_width_unit):

    # Set environment variables
    arcpy.env.overwriteOutput = True
    arcpy.env.XYResolution = "0.00001 Meters"
    arcpy.env.XYTolerance = "0.0001 Meters"

    # Create "General" file geodatabase
    WorkFolder = os.path.dirname(output_workspace)
    General_GDB = WorkFolder + "\General.gdb"
    arcpy.CreateFileGDB_management(WorkFolder, "General", "CURRENT")
    arcpy.env.workspace = General_GDB

    # List parameter values
    arcpy.AddMessage("Output Workspace: {}".format(output_workspace))
    arcpy.AddMessage("Workfolder: {}".format(WorkFolder))
    arcpy.AddMessage("Flowline: "
                     "{}".format(arcpy.Describe(flowline).baseName))
    arcpy.AddMessage("Split Type: {}".format(split_type))
    arcpy.AddMessage("XS Spacing: {}".format(transect_spacing))
    arcpy.AddMessage("XS Width: {}".format(transect_width))
    arcpy.AddMessage("XS Width Units: {}".format(transect_width_unit))

    #Unsplit Line
    LineDissolve = "LineDissolve"
    arcpy.Dissolve_management(flowline, LineDissolve, "", "", "SINGLE_PART")
    LineSplit = "LineSplit"

    #Split Line
    if split_type == "Split at approximate distance":
        splitline(LineDissolve, LineSplit, transect_spacing)
    else:
        arcpy.SplitLine_management(LineDissolve, LineSplit)

    #Add fields to LineSplit
    FieldsNames = [
        "LineID", "Direction", "Azimuth", "X_mid", "Y_mid", "AziLine_1",
        "AziLine_2", "Distance"
    ]
    for fn in FieldsNames:
        arcpy.AddField_management(LineSplit, fn, "DOUBLE")

    #Calculate Fields
    CodeBlock_Direction = """def GetAzimuthPolyline(shape):
     radian = math.atan((shape.lastpoint.x - shape.firstpoint.x)/(shape.lastpoint.y - shape.firstpoint.y))
     degrees = radian * 180 / math.pi
     return degrees"""

    CodeBlock_Azimuth = """def Azimuth(direction):
     if direction < 0:
      azimuth = direction + 360
      return azimuth
     else:
      return direction"""
    CodeBlock_NULLS = """def findNulls(fieldValue):
        if fieldValue is None:
            return 0
        elif fieldValue is not None:
            return fieldValue"""
    arcpy.CalculateField_management(LineSplit, "LineID", "!OBJECTID!",
                                    "PYTHON_9.3")
    arcpy.CalculateField_management(LineSplit, "Direction",
                                    "GetAzimuthPolyline(!Shape!)",
                                    "PYTHON_9.3", CodeBlock_Direction)
    arcpy.CalculateField_management(LineSplit, "Direction",
                                    "findNulls(!Direction!)", "PYTHON_9.3",
                                    CodeBlock_NULLS)
    arcpy.CalculateField_management(LineSplit, "Azimuth",
                                    "Azimuth(!Direction!)", "PYTHON_9.3",
                                    CodeBlock_Azimuth)
    arcpy.CalculateField_management(
        LineSplit, "X_mid", "!Shape!.positionAlongLine(0.5,True).firstPoint.X",
        "PYTHON_9.3")
    arcpy.CalculateField_management(
        LineSplit, "Y_mid", "!Shape!.positionAlongLine(0.5,True).firstPoint.Y",
        "PYTHON_9.3")
    CodeBlock_AziLine1 = """def Azline1(azimuth):
     az1 = azimuth + 90
     if az1 > 360:
      az1-=360
      return az1
     else:
      return az1"""
    CodeBlock_AziLine2 = """def Azline2(azimuth):
     az2 = azimuth - 90
     if az2 < 0:
      az2+=360
      return az2
     else:
      return az2"""
    arcpy.CalculateField_management(LineSplit, "AziLine_1",
                                    "Azline1(!Azimuth!)", "PYTHON_9.3",
                                    CodeBlock_AziLine1)
    arcpy.CalculateField_management(LineSplit, "AziLine_2",
                                    "Azline2(!Azimuth!)", "PYTHON_9.3",
                                    CodeBlock_AziLine2)
    arcpy.CalculateField_management(LineSplit, "Distance", transect_width,
                                    "PYTHON_9.3")

    #Generate Azline1 and Azline2
    spatial_reference = arcpy.Describe(flowline).spatialReference
    Azline1 = "Azline1"
    Azline2 = "Azline2"
    arcpy.BearingDistanceToLine_management(LineSplit, Azline1, "X_mid",
                                           "Y_mid", "Distance",
                                           transect_width_unit, "AziLine_1",
                                           "DEGREES", "GEODESIC", "LineID",
                                           spatial_reference)
    arcpy.BearingDistanceToLine_management(LineSplit, Azline2, "X_mid",
                                           "Y_mid", "Distance",
                                           transect_width_unit, "AziLine_2",
                                           "DEGREES", "GEODESIC", "LineID",
                                           spatial_reference)

    #Create Azline and append Azline1 and Azline2
    Azline = "Azline"
    arcpy.CreateFeatureclass_management(arcpy.env.workspace, "Azline",
                                        "POLYLINE", "", "", "",
                                        spatial_reference)
    arcpy.AddField_management(Azline, "LineID", "DOUBLE")
    arcpy.Append_management([Azline1, Azline2], Azline, "NO_TEST")

    #Dissolve Azline
    Azline_Dissolve = "Azline_Dissolve"
    arcpy.Dissolve_management(Azline, Azline_Dissolve, "LineID", "",
                              "SINGLE_PART")

    #Add Fields to Azline_Dissolve
    FieldsNames2 = ["x_start", "y_start", "x_end", "y_end"]
    for fn2 in FieldsNames2:
        arcpy.AddField_management(Azline_Dissolve, fn2, "DOUBLE")

    #Calculate Azline_Dissolve fields
    arcpy.CalculateField_management(
        Azline_Dissolve, "x_start",
        "!Shape!.positionAlongLine(0,True).firstPoint.X", "PYTHON_9.3")
    arcpy.CalculateField_management(
        Azline_Dissolve, "y_start",
        "!Shape!.positionAlongLine(0,True).firstPoint.Y", "PYTHON_9.3")
    arcpy.CalculateField_management(
        Azline_Dissolve, "x_end",
        "!Shape!.positionAlongLine(1,True).firstPoint.X", "PYTHON_9.3")
    arcpy.CalculateField_management(
        Azline_Dissolve, "y_end",
        "!Shape!.positionAlongLine(1,True).firstPoint.Y", "PYTHON_9.3")

    #Generate output file
    out_transect_name = "xs_{}_{}".format(int(round(transect_spacing)),
                                          int(round(transect_width)))
    output_transect = os.path.join(output_workspace, out_transect_name)
    arcpy.XYToLine_management(Azline_Dissolve, output_transect, "x_start",
                              "y_start", "x_end", "y_end", "", "",
                              spatial_reference)

    # Create `Seq` field
    arcpy.AddField_management(in_table=output_transect,
                              field_name="Seq",
                              field_type="SHORT")
    arcpy.CalculateField_management(in_table=output_transect,
                                    field="Seq",
                                    expression="!OID!",
                                    expression_type="PYTHON_9.3")

    # Set the ReachName field
    unique_reaches = set(
        row[0] for row in arcpy.da.SearchCursor(flowline, "ReachName"))
    reach_name = list(unique_reaches)[0]
    arcpy.AddField_management(in_table=output_transect,
                              field_name="ReachName",
                              field_type="TEXT")
    arcpy.CalculateField_management(in_table=output_transect,
                                    field="ReachName",
                                    expression="'" + reach_name + "'",
                                    expression_type="PYTHON_9.3")

    # Return
    arcpy.SetParameter(6, output_transect)

    # Cleanup
    arcpy.Delete_management(General_GDB)
Exemple #11
0
Structure_Pt = arcpy.GetParameterAsText(0)

# Local variables:
Structure_Direction_Reelle_1 = ""
Structure_Direction_Reelle_2 = ""
Structure_Direction_Reelle_Merge = "D:\\Managem\\TriK_2019\\Orpaillage\\Output\\Output.gdb\\Merge"
Structure_Direction_Reelle_shp = "D:\\Managem\\TriK_2019\\Hassan\\Exploration_2019\\Structure\\Structure_Direction_Reelle.shp"
Structure_Pendage_Reelle = "D:\\Managem\\TriK_2019\\Hassan\\Exploration_2019\\Structure\\Structure_Pendage_Reelle.shp"
Structure_Direction_Visible_1 = ""
Structure_Direction_Visible_2 = ""
Structure_Direction_Visible_Merge = "D:\\Managem\\TriK_2019\\Orpaillage\\Output\\Output.gdb\\Merge1"
Structure_Direction_Visible_shp = "D:\\Managem\\TriK_2019\\Hassan\\Exploration_2019\\Structure\\Structure_Direction_Visible.shp"
Structure_Pendage_Visible = "D:\\Managem\\TriK_2019\\Hassan\\Exploration_2019\\Structure\\Structure_Pendage_Visible.shp"

# Process: Bearing Direction Reelle +
arcpy.BearingDistanceToLine_management(Structure_Pt, Structure_Direction_Reelle_1, "X_UTM", "Y_UTM", "Longueur", "9001", "Strike", "9102", "0", "Identifer", "PROJCS['WGS_1984_UTM_Zone_29N',GEOGCS['GCS_WGS_1984',DATUM['D_WGS_1984',SPHEROID['WGS_1984',6378137.0,298.257223563]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]],PROJECTION['Transverse_Mercator'],PARAMETER['False_Easting',500000.0],PARAMETER['False_Northing',0.0],PARAMETER['Central_Meridian',-9.0],PARAMETER['Scale_Factor',0.9996],PARAMETER['Latitude_Of_Origin',0.0],UNIT['Meter',1.0]];-5120900 -9998100 450445547.391054;-100000 10000;-100000 10000;0.001;0.001;0.001;IsHighPrecision")

# Process: Bearing Direction Reelle -
arcpy.BearingDistanceToLine_management(Structure_Pt, Structure_Direction_Reelle_2, "X_UTM", "Y_UTM", "Long_Comp", "9001", "Strike", "9102", "0", "Identifer", "PROJCS['WGS_1984_UTM_Zone_29N',GEOGCS['GCS_WGS_1984',DATUM['D_WGS_1984',SPHEROID['WGS_1984',6378137.0,298.257223563]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]],PROJECTION['Transverse_Mercator'],PARAMETER['False_Easting',500000.0],PARAMETER['False_Northing',0.0],PARAMETER['Central_Meridian',-9.0],PARAMETER['Scale_Factor',0.9996],PARAMETER['Latitude_Of_Origin',0.0],UNIT['Meter',1.0]];-5120900 -9998100 450445547.391054;-100000 10000;-100000 10000;0.001;0.001;0.001;IsHighPrecision")

# Process: Merge Direction Reelle
arcpy.Merge_management("'';''", Structure_Direction_Reelle_Merge, "Identifer \"Identifer\" true true false 0 Text 0 0 ,First,#,D:\\Managem\\TriK_2019\\Hassan\\Cartographie.gdb\\Structure_Pt_BearingDistance,Identifer,-1,-1,D:\\Managem\\TriK_2019\\Hassan\\Cartographie.gdb\\Structure_Pt_BearingDistance,Identifer,-1,-1;X_UTM \"X_UTM\" true true false 0 Double 0 0 ,First,#,D:\\Managem\\TriK_2019\\Hassan\\Cartographie.gdb\\Structure_Pt_BearingDistance,X_UTM,-1,-1,D:\\Managem\\TriK_2019\\Hassan\\Cartographie.gdb\\Structure_Pt_BearingDistance,X_UTM,-1,-1;Y_UTM \"Y_UTM\" true true false 0 Double 0 0 ,First,#,D:\\Managem\\TriK_2019\\Hassan\\Cartographie.gdb\\Structure_Pt_BearingDistance,Y_UTM,-1,-1,D:\\Managem\\TriK_2019\\Hassan\\Cartographie.gdb\\Structure_Pt_BearingDistance,Y_UTM,-1,-1;Longueur \"Longueur\" true true false 0 Double 0 0 ,First,#,D:\\Managem\\TriK_2019\\Hassan\\Cartographie.gdb\\Structure_Pt_BearingDistance,Longueur,-1,-1;Strike \"Strike\" true true false 0 Double 0 0 ,First,#,D:\\Managem\\TriK_2019\\Hassan\\Cartographie.gdb\\Structure_Pt_BearingDistance,Strike,-1,-1,D:\\Managem\\TriK_2019\\Hassan\\Cartographie.gdb\\Structure_Pt_BearingDistance,Strike,-1,-1;Long_Comp \"Long_Comp\" true true false 0 Double 0 0 ,First,#,D:\\Managem\\TriK_2019\\Hassan\\Cartographie.gdb\\Structure_Pt_BearingDistance,Long_Comp,-1,-1")

# Process: Dissolve Direction Reelle
arcpy.Dissolve_management(Structure_Direction_Reelle_Merge, Structure_Direction_Reelle_shp, "Identifer", "", "MULTI_PART", "DISSOLVE_LINES")

# Process: Bearing Pendage Reelle
arcpy.BearingDistanceToLine_management(Structure_Pt, Structure_Pendage_Reelle, "X_UTM", "Y_UTM", "L_Pd_Dir", "9001", "Pd_Dir", "9102", "0", "Identifer", "PROJCS['WGS_1984_UTM_Zone_29N',GEOGCS['GCS_WGS_1984',DATUM['D_WGS_1984',SPHEROID['WGS_1984',6378137.0,298.257223563]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]],PROJECTION['Transverse_Mercator'],PARAMETER['False_Easting',500000.0],PARAMETER['False_Northing',0.0],PARAMETER['Central_Meridian',-9.0],PARAMETER['Scale_Factor',0.9996],PARAMETER['Latitude_Of_Origin',0.0],UNIT['Meter',1.0]];-5120900 -9998100 450445547.391054;-100000 10000;-100000 10000;0.001;0.001;0.001;IsHighPrecision")

# Process: Bearing Direction Visible +
arcpy.BearingDistanceToLine_management(Structure_Pt, Structure_Direction_Visible_1, "X_UTM", "Y_UTM", "Long_Vue", "9001", "Strike", "9102", "0", "Identifer", "PROJCS['WGS_1984_UTM_Zone_29N',GEOGCS['GCS_WGS_1984',DATUM['D_WGS_1984',SPHEROID['WGS_1984',6378137.0,298.257223563]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]],PROJECTION['Transverse_Mercator'],PARAMETER['False_Easting',500000.0],PARAMETER['False_Northing',0.0],PARAMETER['Central_Meridian',-9.0],PARAMETER['Scale_Factor',0.9996],PARAMETER['Latitude_Of_Origin',0.0],UNIT['Meter',1.0]];-5120900 -9998100 450445547.391054;-100000 10000;-100000 10000;0.001;0.001;0.001;IsHighPrecision")
Exemple #12
0
##### 1. extract wind (I used raster data) #####
fn = extract_wind(False,wind,source,0,0,0)

##### 2. defined distance #####
dn = def_dist(source,500)

##### 3. create virtual downiwnd trajectory #####
# re-define arcpy environemnt
arcpy.env.workspace =r"D:\DPRIE_Test\DPRIE.gdb"
road = "road"
DPRIPs = "DPRIP"
bl = "bearline"
# define the spatial reference
sr = arcpy.SpatialReference(54002) #WKID of equidistant cylinderical
bl_path = arcpy.BearingDistanceToLine_management(source, bl, 'X', 'Y',
                                       dn,"METERS",fn, "DEGREES",'GEODESIC',spatial_reference = sr)
print ("creating virtual downiwnd trajectory....")

##### 4. find all DPRIPs #####
dps_path = arcpy.Intersect_analysis ([road, bl],DPRIPs, "", "", 'POINT')

##### 5.find nearest DPRIPs for each source, calculate nearest downiwnd distance #####
# record coordinates of nearest DPRIPs
print ("calculating DPRIPs....")
ID_list,D_wind,Int_x,Int_y,SX,SY = find_n_DPRIP(source,DPRIPs)

# output results to .csv file 
d = {"source_X":SX,"source_Y":SY,"source_ID":ID_list,
    "Downwind_dist":D_wind,"p_x":Int_x,"p_y":Int_y}

df = pd.DataFrame(data=d,columns = ["source_ID","source_X","source_Y",