Python code for straight line slope of a polyline (inc. straight line length, pecentage slope, and degrees slope)

6271
2
03-17-2016 05:30 AM

Python code for straight line slope of a polyline (inc. straight line length, pecentage slope, and degrees slope)

Follow these instructions to calculate the percentage and degrees slope for any polyline layer with z values.

1. Add fields to the attribute table for: a) straight line length; b) percentage slope; c) degrees slope.

2. Use the Field Calculator to compute the straight line length using this Python code. NB - if your polylines are straight, then you can omit this step and instead calculate the Length field using 'Calculate Geometry' as normal.

Code block:

import math
def GetDistance(shape):
  distance = math.sqrt((math.pow(shape.firstpoint.x - shape.lastpoint.x, 2)) + (math.pow(shape.firstpoint.y - shape.lastpoint.y, 2)))
  return distance

3. Use the Field Calculator to compute the percentage slope using this Python code. NB - if you have straight polylines then you can subsitute the normal 'Length' field for the straight line length (called Straight_L in this example).

Code block:

import math
def GetSlopePerc(shape, leng):
  ratio = (math.fabs(shape.lastpoint.z - shape.firstpoint.z))/ leng
  percentage = ratio * 100
  return percentage

4. Use the Field Calculator to compute the percentage slope using this Python code. Note that Slope_pcen is the percentage slope field.

Code block:

import math
def GetSlopeDeg(shape, percentage):
  ratio = percentage / 100
  radians = math.atan(ratio)
  degrees = radians * (180/math.pi)
  return degrees

Alternatively, you can return the slope in degrees using this maths module function:

math.degrees()

(Thanks to Neil Ayres for suggesting this alteration)

Hopefully this has been helpful! Let me know if these codes through any errors for you.

Comments

And the math module has functions

math.radians()

math.degrees()

Thanks for suggesting this. I'd not thought to put the code block in syntax format but it definitely improves the document.

Version history
Last update:
‎12-12-2021 03:43 AM
Updated by: