簡體   English   中英

自動減少分段功能組件-Pyomo

[英]Automatically reduce piecewise function components - Pyomo

在pyomo中,我有一個通過pyomo.environ.Piecewise定義的分段線性約束。 我不斷收到以下警告

Piecewise component '<component name>' has detected slopes of consecutive piecewise segments to be within <tolerance> of one another. Refer to the Piecewise help documentation for information on how to disable this warning.

我知道我可以增加公差並擺脫警告,但是我想知道是否存在一種通用方法(通過Pyomo或numpy)來減少“分段”的數量(如果兩個連續的斜率都低於給定的公差)。

我顯然可以自己實現,但是我想避免重新發明輪子。

好的,這就是我的想法。 絕對沒有針對性能進行優化,但是我的情況取決於幾點。 它還缺乏對輸入的更多驗證(例如, x被排序並且是唯一的)。

def reduce_piecewise(x, y, abs_tol):
    """
    Remove unnecessary points from piece-wise curve.

    Points are remove if the slopes of consecutive segments
    differ by less than `abs_tol`.

    x points must be sorted and unique.
    Consecutive y points can be the same though!

    Parameters
    ----------
    x : List[float]
        Points along x-axis.
    y : List[float]
    abs_tol : float
        Tolerance between consecutive segments.

    Returns
    -------
    (np.array, np.array)
        x and y points - reduced.
    """
    if not len(x) == len(y):
        raise ValueError("x and y must have same shape")

    x_reduced = [x[0]]
    y_reduced = [y[0]]

    for i in range(1, len(x) - 1):
        left_slope  = (y[i] - y_reduced[-1])/(x[i] - x_reduced[-1])
        right_slope = (y[i+1] - y[i])/(x[i+1] - x[i])
        if abs(right_slope - left_slope) > abs_tol:
            x_reduced.append(x[i])
            y_reduced.append(y[i])

    x_reduced.append(x[-1])
    y_reduced.append(y[-1])

    return np.array(x_reduced), np.array(y_reduced)

以下是一些示例:

>>> x = np.array([0, 1, 2, 3])
>>> y = np.array([0, 1, 2, 3])
>>> reduce_piecewise(x, y, 0.01)
(array([0, 3]), array([0, 3]))
>>> x = np.array([0, 1, 2, 3, 4, 5])
>>> y = np.array([0, 2, -1, 3, 4.001, 5]) # 4.001 should be removed
>>> reduce_piecewise(x, y, 0.01)
(array([0, 1, 2, 3, 5]), array([ 0.,  2., -1.,  3.,  5.]))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM