Skip to content

Instantly share code, notes, and snippets.

@GrovesD2
Created April 14, 2023 09:33
Show Gist options
  • Save GrovesD2/57ccd4db074734b7d300214091752abb to your computer and use it in GitHub Desktop.
Save GrovesD2/57ccd4db074734b7d300214091752abb to your computer and use it in GitHub Desktop.
import numpy as np
from scipy.optimize import minimize, LinearConstraint
def find_grad_intercept(case, x, y):
'''
Find the granient and intercept terms for the envelope trend line.
Note: case = 'above' or 'below'
'''
pos = np.argmax(y) if case == 'above' else np.argmin(y)
# Form the points for the objective function
X = x-x[pos]
Y = y-y[pos]
if case == 'above':
const = LinearConstraint(
X.reshape(-1, 1),
Y,
np.full(X.shape, np.inf),
)
else:
const = LinearConstraint(
X.reshape(-1, 1),
np.full(X.shape, -np.inf),
Y,
)
ans = minimize(
fun = lambda m: np.sum((m*X-Y)**2),
x0 = [0],
jac = lambda m: np.sum(2*X*(m*X-Y)),
method = 'SLSQP',
constraints = (const),
)
# Return the gradient (m) and the intercept (c)
return ans.x[0], y[pos]-ans.x[0]*x[pos]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment