-
Notifications
You must be signed in to change notification settings - Fork 541
CSpline - Fix segment function and add utils to constrain parameter calculations #3593
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
eslickj
wants to merge
6
commits into
Pyomo:main
Choose a base branch
from
eslickj:cspline_linear_extrap
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
90b745a
Fix segment function and add utils for contraints.
8f5538a
Delete unused args
9792cb4
Fix import
59d116f
Merge branch 'main' of https://github.com/pyomo/pyomo into cspline_li…
d16d1f7
Fixes for review
f94d3ab
Merge branch 'main' into cspline_linear_extrap
mrmundt File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -161,6 +161,32 @@ def get_parameters_from_file(self, fptr): | |
self.a3 = np.array(self.a3) | ||
self.a4 = np.array(self.a4) | ||
|
||
def add_linear_extrapolation_segments(self): | ||
"""Add a segment on the front and back of the cspline so that | ||
any extrapolation will be linear.""" | ||
# We need to add a knot for a linear segment on the beginning and | ||
# end. Since the first and last segment will be used for extrapolation, | ||
# and we want them to be linear, it doesn't really matter how far out | ||
# the knots are. To try to be roughly in line with the data scale we | ||
# just use the distance from the first to the last knot. | ||
dist = self.knots[-1] - self.knots[0] | ||
x = np.array([self.knots[0], self.knots[-1]]) | ||
y = self.f(x) | ||
m = self.dfdx(x) | ||
b = y - m * x | ||
k = np.array([self.knots[0] - dist, self.knots[-1] + dist]) | ||
|
||
self.knots = np.insert(self.knots, 0, k[0]) | ||
self.a1 = np.insert(self.a1, 0, b[0]) | ||
self.a2 = np.insert(self.a2, 0, m[0]) | ||
self.a3 = np.insert(self.a3, 0, 0) | ||
self.a4 = np.insert(self.a4, 0, 0) | ||
self.knots = np.append(self.knots, k[1]) | ||
self.a1 = np.append(self.a1, b[1]) | ||
self.a2 = np.append(self.a2, m[1]) | ||
self.a3 = np.append(self.a3, 0) | ||
self.a4 = np.append(self.a4, 0) | ||
|
||
def write_parameters(self, fptr): | ||
"""Write parameters to a file""" | ||
assert self.valid | ||
|
@@ -180,11 +206,19 @@ def segment(self, x): | |
array of integers is returned otherwise return an integer | ||
""" | ||
s = np.searchsorted(self.knots, x) | ||
# If x is past the last knot, use the last segment | ||
# this could happen just due to round-off even if | ||
# you don't intend to extrapolate | ||
s[s >= self.n_segments] = self.n_segments - 1 | ||
return s | ||
if isinstance(s, np.ndarray): | ||
# if x is before the first knot use the first segment | ||
s[s <= 0] = 1 | ||
# if x is after the last knot use last segment to extrapolate | ||
s[s >= len(self.knots)] = len(self.knots) - 1 | ||
else: | ||
if s <= 0: | ||
# if x is before the first knot use the first segment | ||
return 0 | ||
if s >= len(self.knots): | ||
# if x is after the last knot use last segment to extrapolate | ||
return len(self.knots) - 2 | ||
return s - 1 | ||
|
||
def f(self, x): | ||
"""Get f(x) | ||
|
@@ -198,6 +232,18 @@ def f(self, x): | |
s = self.segment(x) | ||
return self.a1[s] + self.a2[s] * x + self.a3[s] * x**2 + self.a4[s] * x**3 | ||
|
||
def dfdx(self, x): | ||
"""Get d/dx(f(x)) | ||
|
||
Args: | ||
x: location, numpy array float | ||
|
||
Returns: | ||
df/dx numpy array if x is numpy array or float | ||
""" | ||
s = self.segment(x) | ||
return self.a2[s] + 2 * self.a3[s] * x + 3 * self.a4[s] * x**2 | ||
|
||
|
||
def cubic_parameters_model( | ||
x_data, | ||
|
@@ -286,7 +332,7 @@ def yxx_eqn(blk, s): | |
def ydiff(blk, d): | ||
s = idx[d - 1] + 1 | ||
if s >= m.seg_idx.last(): | ||
s -= 1 | ||
s = m.seg_idx.last() | ||
return m.y_data[d] - _f_cubic(m.x_data[d], m.alpha, s) | ||
|
||
if objective_form: | ||
|
@@ -313,3 +359,71 @@ def yxx_endpoint_eqn(blk, s): | |
else: | ||
j = s | ||
return _fxx_cubic(m.x[j], m.alpha, s) == 0 | ||
|
||
|
||
def add_decreasing_constraints(m, tol=0): | ||
"""If the objective form of the parameter calculation is used, the | ||
data and the spline don't need to match exactly, and we can add | ||
constraints on the derivatives that they are negative at the knots. | ||
|
||
This doesn't necessarily mean the cubic spline function is always | ||
decreasing, since the segments are cubic, but you can either check the | ||
resulting curve or pair it with convex or concave constraints. | ||
""" | ||
|
||
@m.Constraint(m.knt_idx) | ||
def yx_ineq(blk, k): | ||
if k >= len(m.knt_idx): | ||
s = k - 1 | ||
else: | ||
s = k | ||
return _fx_cubic(m.x[k], m.alpha, s) <= -tol | ||
Comment on lines
+375
to
+380
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. It would be good for these functions to be declared at the module scope so that they would be picklable. Given the use of the class _yx_ineq(object):
def __init__(self, tol):
self.tol = tol
def __call__(self, m, k):
if k >= len(m.knt_idx):
s = k - 1
else:
s = k
return _fx_cubic(m.x[k], m.alpha, s) <= -self.tol
def add_decreasing_constraints(m, tol=0):
m.yx_ineq = Constraint(m.knt_idx, rule=_yx_ineq(tol)) |
||
|
||
|
||
def add_concave_constraints(m, tol=0): | ||
"""If the objective form of the parameter calculation is used, the | ||
data and the spline don't need to match exactly, and we can add | ||
constraints on the second derivatives that they are always negative. | ||
""" | ||
|
||
@m.Constraint(m.knt_idx) | ||
def yxx_ineq(blk, k): | ||
if k >= len(m.knt_idx): | ||
s = k - 1 | ||
else: | ||
s = k | ||
return _fxx_cubic(m.x[k], m.alpha, s) <= -tol | ||
|
||
|
||
def add_increasing_constraints(m, tol=0): | ||
"""If the objective form of the parameter calculation is used, the | ||
data and the spline don't need to match exactly, and we can add | ||
constraints on the derivatives that they are positive at the knots. | ||
|
||
This doesn't necessarily mean the cubic spline function is always | ||
increasing, since the segments are cubic, but you can either check the | ||
resulting curve or pair it with convex or concave constraints. | ||
""" | ||
|
||
@m.Constraint(m.knt_idx) | ||
def yx_ineq(blk, k): | ||
if k >= len(m.knt_idx): | ||
s = k - 1 | ||
else: | ||
s = k | ||
return _fx_cubic(m.x[k], m.alpha, s) >= tol | ||
|
||
|
||
def add_convex_constraints(m, tol=0): | ||
"""If the objective form of the parameter calculation is used, the | ||
data and the spline don't need to match exactly, and we can add | ||
constraints on the second derivatives that they are always positive. | ||
""" | ||
|
||
@m.Constraint(m.knt_idx) | ||
def yxx_ineq(blk, k): | ||
if k >= len(m.knt_idx): | ||
s = k - 1 | ||
else: | ||
s = k | ||
return _fxx_cubic(m.x[k], m.alpha, s) >= tol |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
These functions assume that
m
has a setknt_idx
, and that they can create components with specific hardcoded names. This feels like these should be methods on a custom Block class that disallows users to create components so you don't have to worry about conflicts and know that the required attributes are present.