# -*- coding: utf-8 -*- import numpy as np # --------------- # User settings # -------------- def staircase_from_line(i0, i1, j0, j1): """Make an optimal staircase polyline given the end points""" swapXY = False if abs(i1-i0) < abs(j0-j1): # Mostly vertical i0, i1, j0, j1 = j0, j1, i0, i1 swapXY = True # Find integer points X0 and Y0 on line if i0 < i1: X0 = list(range(i0, i1+1)) elif i0 > i1: X0 = list(range(i0, i1-1, -1)) else: # i0 = i1 and j0 = j1 raise ValueError("Section reduced to a point") slope = float(j1-j0) / (i1-i0) Y0 = [j0 + slope*(x-i0) for x in X0] # sign = -1 if Y0 is decreasing, otherwise sign = 1 sign = 1 if Y0[-1] < Y0[0]: # Decreasing Y sign = -1 # Make lists of positions along staircase X, Y = [i0], [j0] for i in range(len(X0)-1): y = Y[-1] # Last point on list so far x0, y0 = X0[i], Y0[i] # Present point along line x1, y1 = X0[i+1], Y0[i+1] # Next point along line if abs(y-y0) + abs(y-y1) > abs(y+sign-y0) + abs(y+sign-y1): # jump X.append(x0) Y.append(y+sign) X.append(x1) Y.append(y+sign) else: # Ordinary append X.append(x1) Y.append(y) # Possible jump to last point # Assumes Y0[-1] if Y[-1] != j1: X.append(i1) Y.append(j1) if swapXY: X, Y = Y, X return np.array(X), np.array(Y) # --------------------------------