cjekel / piecewise_linear_fit_py

fit piecewise linear data for a specified number of line segments
MIT License
300 stars 60 forks source link

Force minimum length of segments to be greater than x #66

Open lucascibona opened 4 years ago

lucascibona commented 4 years ago

Hello,

How can I add a constraint in the outer optimization function: minimum length of each segment should be >= x?

cjekel commented 4 years ago

I think there are two ways to approach this.

  1. Add a penalty parameter to the objective function. See [1] for a reasonable penalty formulation.
  2. Use a constrained optimization algorithm.

It's fairly straight forward to just add a constraint function and use a constrained optimization algorithm (option 2). If this doesn't work for you, you may want to investigate a penalty formulation.

This jupyter notebook uses SLSQP to apply a constraint function to force a minimum line segment length. You'll need to supply a starting point (or guess) to start the optimization. If you don't know what is a good starting point, check out how I use Latin Hypercube random sampling to run multiple optimizations in the fitfast function.

A constraint function could look like:

def my_con(var):
    var = np.sort(var)
    distances = np.zeros(number_of_line_segments)
    distances[0] = var[0] - my_pwlf.break_0
    distances[-1] = my_pwlf.break_n - var[-1]
    for i in range(number_of_line_segments - 2):
        distances[i+1] = var[i+1] - var[i]
    # element must be greater or equal to 0.0
    # in a successfully optimized problem
    return np.array((distances.min() - min_length))

This is a single constraint for the minimum length of all segments. It's possible that the min() in this function will create issues with the gradient of the constraint. If you run into issues with this, you may want to investigate using a separate constraint for each line segment. That could be done by changing:

    return np.array((distances.min() - min_length))

to

    return distances - min_length

[1] Haftka, R. T. and Starnes, J. H., Jr., "Applications of a Quadratic Extended Interior Penalty Functions for Structural Optimization," AIAA Journal, Vol. 14, pp. 718-724, 1976 PDF

lucascibona commented 4 years ago

thank you for the very detailed answer -- i'll go through your suggestion asap