Field calculator expressions with numpy

137
0
04-01-2025 09:13 AM
DanPatterson
MVP Esteemed Contributor

A followup to the recent einsum post, but with a field calculator twist

 

# ---- a numeric field, python expression which uses the shape field to return the longest edge on the perimeter

longest_seg(!Shape!)

# ---- the code block -----

import json
import numpy as np
#
def longest_seg(a):
    """Longest edge"""
    v = json.loads(a.JSON)
    r = v['rings']
    a = np.array(r).squeeze()
    a = a[0] if a.ndim > 2 else a
    diff = a[1:] - a[:-1]
    ret = np.sqrt(np.einsum('ij,ij->i', diff, diff))
    val = np.max(ret)
    return val

 

lines 12-13 :  really? having to convert to JSON format just to get at the array values?

line 14 :  the json format assumes a multipolygon so a nested, nested set of nests of values... numpy squeeze() gets rid of all the extra nesting

line 15 :  a check, but used for dimensions > 2, it will take the first part (the outer ring of the first shape)

lines 16-17 :  einsum .... read the previous article

line 18:  you will get an array of the segment lengths forming the perimeter... this demo is using the max, so modify the code if you want the minimum or the average or the 3rd from the end, etc etc.  Just dont' over-fluff field calculator code to try and do everything

line 19  return the value

 

There really has to be a better way of converting an arcpy shape into another format which can be used without having to use cursors and deal with the featureclass rather than the feature itself.  like make __geo_interface__ read the shape without having to use that in cursors.

 


... sort of retired...
Tags (3)
0 Kudos
0 Replies