|
| 1 | +from . import LinearRegression |
| 2 | + |
| 3 | +linear_min_r2 = 0.9 |
| 4 | + |
| 5 | + |
| 6 | +class Curve: |
| 7 | + def __init__(self, start, end, cb): |
| 8 | + """Takes complex numbers for start, end, and list of 4 Bezier control points""" |
| 9 | + self.start = start |
| 10 | + self.end = end |
| 11 | + assert cb is None or len(cb) == 4 |
| 12 | + self.cb = cb |
| 13 | + |
| 14 | + def __str__(self): |
| 15 | + control = "[" + (str(self.cb) if self.cb is not None else "None") + "]" |
| 16 | + return str(self.start) + ", " + control + ", " + str(self.end) |
| 17 | + |
| 18 | + @staticmethod |
| 19 | + def is_linear(points, threshold=linear_min_r2): |
| 20 | + """ |
| 21 | + Returns a boolean indicating whether a list of complex points is linear. |
| 22 | +
|
| 23 | + Takes a list of complex points and optional minimum R**2 threshold for linear regression. |
| 24 | + """ |
| 25 | + r2 = LinearRegression.coefficients(points)[2] |
| 26 | + return r2 > threshold |
| 27 | + |
| 28 | + def cubic_bezier_coordinates(self, t): |
| 29 | + """ |
| 30 | + Returns a complex number representing the point along the cubic bezier curve. |
| 31 | +
|
| 32 | + Takes parametric parameter t where 0 <= t <= 1 |
| 33 | + """ |
| 34 | + x = Curve._cubic_bezier(self._cb("real"), t) |
| 35 | + y = Curve._cubic_bezier(self._cb("imag"), t) |
| 36 | + return complex(x, y) |
| 37 | + |
| 38 | + def _cb(self, prop): |
| 39 | + return [getattr(x, prop) for x in self.cb] |
| 40 | + |
| 41 | + @staticmethod |
| 42 | + def _cubic_bezier(p, t): |
| 43 | + """ |
| 44 | + Returns a float representing the point along the cubic bezier curve in the given dimension. |
| 45 | +
|
| 46 | + Takes ordered list of 4 control points [P0, P1, P2, P3] and parametric parameter t where 0 <= t <= 1 |
| 47 | +
|
| 48 | + implements explicit form of https://en.wikipedia.org/wiki/B%C3%A9zier_curve#Cubic_B%C3%A9zier_curves |
| 49 | + """ |
| 50 | + assert 0 <= t <= 1 |
| 51 | + return ( |
| 52 | + (((1.0 - t) ** 3) * p[0]) |
| 53 | + + (3.0 * t * ((1.0 - t) ** 2) * p[1]) |
| 54 | + + (3.0 * (t ** 2) * (1.0 - t) * p[2]) |
| 55 | + + ((t ** 3) * p[3]) |
| 56 | + ) |
0 commit comments