def test__verify_not_aligned(self):
        import bezier

        edge0 = bezier.Curve(np.asfortranarray([[0.0], [0.0]]), 1)
        edge1 = bezier.Curve(self.NODES1, 2)
        with self.assertRaises(ValueError):
            self._make_one(edge0, edge1)
    def test_convergence(self):
        import bezier

        nodes1 = np.asfortranarray(
            [[0.0, 0.25, 0.5, 0.75, 1.0], [0.0, 1.0, -0.75, 1.0, 0.0]]
        )
        curve1 = bezier.Curve(nodes1, degree=4)
        # Vertical line forces a unique solution.
        nodes2 = np.asfortranarray([[0.5, 0.5], [0.0, 1.0]])
        curve2 = bezier.Curve(nodes2, degree=1)
        num_guess = 4
        parameters = np.zeros((2, num_guess), order="F")
        # NOTE: This means our "first" guess is (s, t) = (0, 0).
        for guess in range(1, num_guess):
            prev_s, prev_t = parameters[:, guess - 1]
            parameters[:, guess] = self._call_function_under_test(
                prev_s, nodes1, prev_t, nodes2
            )
        expected = np.asfortranarray(
            [[0.0, 0.5, 0.5, 0.5], [0.0, 2.0, 0.21875, 0.21875]]
        )
        self.assertEqual(parameters, expected)
        # Make sure that we've actually converged.
        exact_s, exact_t = parameters[:, -1]
        self.assertEqual(curve1.evaluate(exact_s), curve2.evaluate(exact_t))
Beispiel #3
0
def drawPath(map1, G, points):

    #compute shortest paths for all points
    path = []
    for i in range(0, len(points) - 1):
        path.append(
            nx.shortest_path(G,
                             source=len(map1[0]) * points[i][0] + points[i][1],
                             target=len(map1[0]) * points[i + 1][0] +
                             points[i + 1][1]))

    paths_draw = []
    for i in range(0, len(path)):
        paths_draw.append(np.reshape(map1[:, :, 0],
                                     (len(map1) * len(map1[1]))))
        paths_draw[i][path[i]] = 150
        paths_draw[i] = np.reshape(paths_draw[i], (len(map1), len(map1[1])))

    plt.ioff()
    plt.figure(figsize=(10, 10))
    nodes = np.asfortranarray([
        [0.0],
        [0.0],
    ])

    curve = bezier.Curve(nodes, degree=2)
    ax = curve.plot(num_pts=256)

    #Draw all bezier curves one by one on the same plot
    for i in range(0, len(path)):

        controlX = np.zeros(len(path[i]))
        controlY = np.zeros(len(path[i]))

        for j in range(0, len(path[i])):
            controlY[j] = len(map1) - path[i][j] / len(map1[0])
            controlX[j] = path[i][j] % len(map1[0])

        nodes = np.asfortranarray([
            controlX,
            controlY,
        ])
        curve = bezier.Curve(nodes, degree=2)
        normalizedCurve = curve.nodes
        normalizedCurve[0] = normalizedCurve[0] / len(map1[0])
        normalizedCurve[1] = normalizedCurve[1] / len(map1)

        #color of path
        c0 = (255 - 244) * i / len(path) + 244
        c1 = (237 - 160) * i / len(path) + 160
        c2 = (160 - 101) * i / len(path) + 101

        #curves on same plot
        bezier.Curve(normalizedCurve, degree=10).plot(
            num_pts=256, ax=ax, color=[c0 / 255.0, c1 / 255.0, c2 / 255.0])

    #Save the image
    plt.axis(xmin=0, ymin=0, xmax=1, ymax=1)
    ax.set_axis_off()
    plt.savefig("./flaskr/map/sPath.jpg", frameon=True, bbox_inches='tight')
Beispiel #4
0
def image1():
    figure = plt.figure()
    ax = figure.gca()

    curve1 = bezier.Curve(COEFFS1, degree=2, _copy=False)
    curve2 = bezier.Curve(COEFFS2, degree=2, _copy=False)

    curve1.plot(256, ax=ax, color=plot_utils.BLUE)
    ax.lines[-1].set_label("$b_0(s)$")
    curve2.plot(256, ax=ax, color=plot_utils.GREEN)
    ax.lines[-1].set_label("$b_1(t)$")
    ax.plot(
        [0.0],
        [1.0],
        marker="o",
        markersize=4.0,
        color="black",
        linestyle="none",
    )

    ax.legend(fontsize=plot_utils.TEXT_SIZE)
    ax.tick_params(labelsize=plot_utils.TICK_SIZE)
    ax.axis("scaled")

    figure.set_size_inches(5.4, 1.6)
    figure.subplots_adjust(
        left=0.05, bottom=0.09, right=0.99, top=0.99, wspace=0.2, hspace=0.2
    )
    filename = "tangent_intersection.pdf"
    path = plot_utils.get_path("slides", filename)
    figure.savefig(path)
    print("Saved {}".format(filename))
    plt.close(figure)
Beispiel #5
0
def extend_curve(curve_point_list, base_value, x_or_y, apply_extend=True):
    """ Extends the curve to the given value.

    Args:
        curve_point_list:: [RPoint, RPoint, RPoint, RPoint]
            4 RPoint objects forming a cubic bezier curve. The order is
            [(start point), (control point1), (control point2), (end point)].
            The extension works from the end point.
        base_value:: int
            The coordinate value of how far you want to extend. The curve
            will extend to this value.
        x_or_y:: str
            If base_value is an x coordinate value, type 'x'.
            If it is an y coordinate value,  type 'y'.
        apply_extend:: bool (default is True)
            If it is True, the change is applied. Input False if you
            do not want to apply the changes.

    Returns:
        nodes:: 2x4 numpy.ndarray (float)
            The coordinate values of the result of the extension. The rows
            represent the coordinates(x, y) and the columns represent 4 points
            that form a cubic bezier curve. For example:

            [[start_point_x, control_point_1_x, control_point_2_x, end_point_x]
             [start_point_y, control_point_1_y, control_point_2_y, end_point_y]]

    """
    if len(curve_point_list) != 4:
        raise _InputError('curve_point_list: ' + str(curve_point_list), \
                         "The number of data is not correct. Need 4 RPoint objects in the list")

    curve_x = [float(point.x) for point in curve_point_list]
    curve_y = [float(point.y) for point in curve_point_list]
    base_value = float(base_value)
    nodes = np.asfortranarray([curve_x, curve_y])
    curve = bezier.Curve(nodes, degree=3)
    new_curve = curve.specialize(0, 2.5)

    x_or_y = _make_lower_string(x_or_y)
    if x_or_y == 'y':
        nodes = np.asfortranarray([[0., 1000.], [base_value, base_value]])
    elif x_or_y == 'x':
        nodes = np.asfortranarray([[base_value, base_value], [0., 1000.]])
    else:
        raise _InputError("x_or_y: " + x_or_y, "Put 'x' or 'y'")

    line = bezier.Curve(nodes, degree=1)
    s_vals = new_curve.intersect(line)[0, :]
    point = new_curve.evaluate(s_vals[0])
    rate = new_curve.locate(point)
    result_curve = new_curve.specialize(0, rate)

    if apply_extend:
        for i in range(4):
            curve_point_list[i].position = (result_curve.nodes[0, i],
                                            result_curve.nodes[1, i])

    return result_curve.nodes
    def _get_quadratics():
        import bezier

        nodes1 = np.asfortranarray([[0.0, 0.5, 1.0], [0.0, 1.0, 0.0]])
        nodes2 = np.asfortranarray([[1.0, 0.5, 0.0], [0.75, -0.25, 0.75]])
        curve1 = bezier.Curve(nodes1, degree=2)
        curve2 = bezier.Curve(nodes2, degree=2)
        return curve1, curve2
Beispiel #7
0
    def test__verify_bad_dimension(self):
        import bezier

        nodes0 = np.asfortranarray([[1.0, 2.0], [1.0, 2.0]])
        edge0 = bezier.Curve(nodes0, 1)
        edge1 = bezier.Curve(self.NODES1, 2)
        with self.assertRaises(ValueError):
            self._make_one(edge0, edge1)
    def test_constructor(self):
        import bezier

        edge0 = bezier.Curve(self.NODES0, 2)
        edge1 = bezier.Curve(self.NODES1, 2)
        curved_poly = self._make_one(edge0, edge1)
        self.assertEqual(curved_poly._edges, (edge0, edge1))
        self.assertEqual(curved_poly._num_sides, 2)
Beispiel #9
0
    def test_constructor_with_metadata(self):
        import bezier

        edge0 = bezier.Curve(self.NODES0, 2)
        edge1 = bezier.Curve(self.NODES1, 2)
        metadata = ((0, 0.0, 0.5), (4, 0.5, 1.0))
        curved_poly = self._make_one(edge0, edge1, metadata=metadata)
        self.assertEqual(curved_poly._edges, (edge0, edge1))
        self.assertEqual(curved_poly._num_sides, 2)
        self.assertEqual(curved_poly._metadata, metadata)
Beispiel #10
0
def get_curve_scribble(region, min_srb=2, max_srb=4, sort=True):
    # Draw random curves
    num_lines = np.random.randint(min_srb, max_srb)

    scribbles = []
    lengths = []
    eval_pts = np.linspace(0.0, 1.0, 1024)
    if sort:
        # Generate more anyway, pick the best k at last
        num_gen = 10
    else:
        num_gen = num_lines
    for _ in range(num_gen):
        region_indices = np.argwhere(region)
        include_idx = np.random.choice(region_indices.shape[0],
                                       size=3,
                                       replace=False)
        y_nodes = np.asfortranarray([
            [0.0, 0.5, 1.0],
            region_indices[include_idx, 0],
        ])
        x_nodes = np.asfortranarray([
            [0.0, 0.5, 1.0],
            region_indices[include_idx, 1],
        ])
        x_curve = bezier.Curve(x_nodes, degree=2)
        y_curve = bezier.Curve(y_nodes, degree=2)
        x_pts = x_curve.evaluate_multi(eval_pts)
        y_pts = y_curve.evaluate_multi(eval_pts)

        this_scribble = np.zeros_like(region)
        pts = np.stack([x_pts[1, :], y_pts[1, :]], 1)
        pts = pts.reshape((-1, 1, 2)).astype(np.int32)
        this_scribble = cv2.polylines(this_scribble, [pts],
                                      isClosed=False,
                                      color=(1),
                                      thickness=3)

        # Mask away path outside the allowed region, allow some error in labeling
        allowed_error = np.random.randint(3, 7)
        allowed_region = cv2.dilate(region, disk_kernel(allowed_error))
        this_scribble = this_scribble * allowed_region

        scribbles.append(this_scribble)
        lengths.append(this_scribble.sum())

    # Sort according to length, we want the long lines
    scribbles = [
        x for _, x in sorted(
            zip(lengths, scribbles), key=lambda pair: pair[0], reverse=True)
    ]
    scribble = sum(scribbles[:num_lines])

    return (scribble > 0.5).astype(np.uint8)
def get_envelope(t_note_length,
                 sample_rate,
                 audio_length,
                 attack_percent=1.0,
                 attack_slope=0.5,
                 release_percent=25.0,
                 release_slope=0.5):
    """Create an attack sustain release amplitude envelope."""
    i_attack = int(sample_rate * audio_length * (attack_percent / 100))

    i_release = int(sample_rate * audio_length * (release_percent / 100))

    i_tot = int(sample_rate * audio_length)

    envelope = np.ones(i_tot)

    def expand_slope(slope):
        if (slope <= 0.5):
            slope = ((slope * 2)**2) / 2
        else:
            slope = 1 - ((((1 - slope) * 2)**2) / 2)
        return slope

    # Bezier curve attack
    a_slope = expand_slope(float(attack_slope))
    a_curve_point = 1 - a_slope
    a_nodes = np.asfortranarray([[0.0, a_curve_point, 1.0],
                                 [0.0, a_slope, 1.0]])
    a_curve = bezier.Curve(a_nodes, degree=2)
    a_samples = np.linspace(0.0, 1.0, i_attack)
    envelope[:i_attack] = a_curve.evaluate_multi(a_samples)[1]

    # Bezier curve release
    release_slope = 1 - release_slope
    r_slope = expand_slope(float(release_slope))
    r_curve_point = r_slope
    r_nodes = np.asfortranarray([[0.0, r_curve_point, 1.0],
                                 [1.0, r_slope, 0.0]])
    r_curve = bezier.Curve(r_nodes, degree=2)
    r_samples = np.linspace(0.0, 1.0, i_release)
    envelope[-i_release:i_tot] = r_curve.evaluate_multi(r_samples)[1]
    """# Linear attack
  envelope[:i_attack] = np.linspace(0.0, 1.0, i_attack)
  # Linear release
  envelope[-i_release:i_tot] = np.linspace(1.0, 0.0, i_release)"""

    envelope = np.expand_dims(envelope, axis=1)
    envelope = np.concatenate((envelope, envelope), axis=1)
    return envelope
Beispiel #12
0
def image4():
    figure, all_axes = plt.subplots(2, 7)
    all_axes = all_axes.flatten()

    nodes15 = np.asfortranarray([[0.25, 0.625, 1.0], [0.625, 0.25, 1.0]])
    curve15 = bezier.Curve(nodes15, degree=2)
    nodes25 = np.asfortranarray([[0.0, 0.25, 0.75, 1.0], [0.5, 1.0, 1.5, 0.5]])
    curve25 = bezier.Curve(nodes25, degree=3)

    color1 = plot_utils.BLUE
    curve15.plot(256, ax=all_axes[0], color=color1)
    color2 = plot_utils.GREEN
    curve25.plot(256, ax=all_axes[0], color=color2)

    choices1 = [1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1]
    choices2 = [1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1]
    first = curve15
    second = curve25
    for i in range(13):
        ax = all_axes[i + 1]
        index1 = choices1[i]
        index2 = choices2[i]
        first = first.subdivide()[index1]
        second = second.subdivide()[index2]
        first.plot(256, ax=ax, color=color1)
        second.plot(256, ax=ax, color=color2)
        # After splitting, put the bounding box on the previous axis.
        prev_ax = all_axes[i]
        add_patch(first, prev_ax, color1)
        add_patch(second, prev_ax, color2)

    for ax in all_axes:
        ax.axis("equal")
        ax.set_xticklabels([])
        ax.set_yticklabels([])

    figure.set_size_inches(6.4, 2.4)
    figure.subplots_adjust(left=0.01,
                           bottom=0.01,
                           right=0.99,
                           top=0.99,
                           wspace=0.06,
                           hspace=0.04)
    filename = "subdivision_linearized.pdf"
    path = plot_utils.get_path("bezier-intersection", filename)
    figure.savefig(path)
    print("Saved {}".format(filename))
    plt.close(figure)
Beispiel #13
0
 def get_bezier(self, pnts):
             
     
     try:
         import bezier as bz
     except:
         print('To run this function, \'bezier\' sould be installed.')
         return 
     
     #to well-bended curve
     v1=(pnts[1]-pnts[0])/np.linalg.norm(pnts[1]-pnts[0])
     v2=(pnts[2]-pnts[3])/np.linalg.norm(pnts[2]-pnts[3])   
     pnts[1]=pnts[1]+self.bending_factor*v1
     pnts[2]=pnts[2]+self.bending_factor*v2
     
     x=pnts[:,0].tolist(); y=pnts[:,1].tolist(); z=pnts[:,2].tolist(); 
        
     nodes = np.asfortranarray([x,y,z])
     curve = bz.Curve(nodes, degree=2)    
     stp=self.connect_step
     steps=np.arange(0+stp, 1-stp, stp)
     
     new_pnts=[]
     for i in steps:    
         new_pnts.append(np.ravel(curve.evaluate(i)))
     
     return np.array(new_pnts)    
Beispiel #14
0
def LineString_to_jittered_bezier(ls,
                                  n_midpoints=1,
                                  xbias=0.,
                                  xstd=0.,
                                  ybias=0.,
                                  ystd=0.,
                                  normalized=True,
                                  n_eval_points=50):
    if normalized == True:
        xbias = xbias * ls.length
        xstd = xstd * ls.length
        ybias = ybias * ls.length
        ystd = ystd * ls.length

    jitter_ls = add_jittered_midpoints(
        ls,
        n_midpoints=n_midpoints,
        xbias=xbias,
        xstd=xstd,
        ybias=ybias,
        ystd=ystd,
    )
    curve1 = bezier.Curve(np.asfortranarray(jitter_ls).T,
                          degree=n_midpoints + 1)
    bez = curve1.evaluate_multi(np.linspace(0., 1., n_eval_points))
    return sg.asLineString(bez.T)
Beispiel #15
0
 def __calcBezier(self):
     for i in range(int(self._endIdx / self._degree)):
         if self._endList[i * self._degree][2] < 0:
             self._endList[i * self._degree][2] += 2 * pi
         for j in range(1, self._degree + 1):
             delta = self._endList[i * self._degree +
                                   j][2] - self._endList[i * self._degree +
                                                         j - 1][2]
             if fabs(delta) > fabs(delta + 2 * pi):
                 self._endList[i * self._degree + j][2] += 2 * pi
         curve = bezier.Curve(
             self._endList[i * self._degree:(i + 1) * self._degree + 1, :],
             degree=self._degree)
         s_vals = np.linspace(0.0, 1.0, self._sampling)
         if i == 0:
             self._bezierList = curve.evaluate_multi(s_vals)
         else:
             self._bezierList = np.concatenate(
                 (self._bezierList, curve.evaluate_multi(s_vals)))
         for j in range(self._degree + 1):
             if self._endList[i * self._degree + j][2] >= pi:
                 self._endList[i * self._degree + j][2] -= 2 * pi
         for j in range(self._sampling):
             if self._bezierList[i * self._sampling + j][2] >= pi:
                 self._bezierList[i * self._sampling + j][2] -= 2 * pi
    def layer2curves(self, layer, contours=None):
        if contours is None:
            contours = []
        for path in layer.paths:
            contour = []
            for segment in path.segments:
                pts = []
                degree = 3
                if len(segment.points) <= 1:
                    continue
                if segment.type == "line":
                    pt0 = self.double((segment.points[0].x, segment.points[0].y))
                    pt1 = self.double((segment.points[1].x, segment.points[1].y))
                    pts = [pt0, pt0, pt1, pt1]
                elif segment.type == "qcurve":
                    pts = [self.double((point.x, point.y)) for point in segment.points]
                    degree = 2
                elif segment.type == "curve":
                    pts = [self.double((point.x, point.y)) for point in segment.points]
                else:
                    continue
                nodes = np.asfortranarray(pts)
                curve = bezier.Curve(nodes, degree=degree)
                contour.append(curve)
            contours.append(contour)

        for component in layer.components:
            contours = self.layer2curves(Glyphs.font.glyphs[component.componentName].layers[0], contours)
        return contours
def bezier_trajectory(start,
                      end,
                      dt,
                      max_v=0.4,
                      end_derivative_scale=0.5,
                      ramp=3):
    """
    Computes a bezier fit to the start and end conditions, and returns a
    sequence of points that smoothly coneys the robot to the desired target
    configuration.
    """
    x0, y0, th0 = start
    x1, y1, th1 = end
    r = end_derivative_scale
    qs = np.array(
        [
            [x0, y0],
            [x0 + r * np.cos(th0), y0 + r * np.sin(th0)],
            [x1 - r * np.cos(th1), y1 - r * np.sin(th1)],
            [x1, y1],
        ],
        dtype=np.float64,
    )
    bezier_curve = bezier.Curve(qs.T, degree=3)
    T = int(np.ceil(bezier_curve.length / dt / max_v))
    s = get_ramp(ramp, T)
    pts = bezier_curve.evaluate_multi(s).T
    return s, pts, bezier_curve
Beispiel #18
0
def intersect_by_x(curve, xs: np.ndarray):
    ys = []

    for x in xs:
        # 交点を求める為のX線上の直線
        line1 = bezier.Curve(np.asfortranarray([[x, x], [-9999999999, 9999999999]]), degree=1)

        try:
            # 交点を求める(高精度は求めない)
            intersections = curve.intersect(line1, _verify=False)

            # tからyを求め直す
            s_vals = np.asfortranarray(intersections[0, :])

            # 評価する
            es = curve.evaluate_multi(s_vals)
            
            # 値が取れている場合、その値を設定する
            if es.shape == (2, 1):
                ys.append(es[1][0])
            # 取れていない場合、無視
            else:
                ys.append(0)
        except:
            # エラーが起きた場合、無視
            ys.append(0)
    
    return np.array(ys, dtype=np.float)
Beispiel #19
0
def drawCurve(beg, ctrl, end, step):
    turtle.penup()
    turtle.goto(*beg)
    turtle.pendown()
    nodes = [
        [beg[0], ctrl[0], end[0]],
        [beg[1], ctrl[1], end[1]],
    ]
    curve = bezier.Curve(nodes, degree=2)

    interval = 1.0 / step
    progress = interval

    for i in range(step):
        arr = curve.evaluate(progress)
        pt = (arr[0][0], arr[1][0])
        turtle.goto(*pt)
        progress += interval

    turtle.penup()
    for pt in (beg, ctrl, end):
        print(pt)
        turtle.goto(*pt)
        turtle.stamp()
    turtle.pendown()
def plot_binvals(bin_centerpoints,
                 bin_vals,
                 tumor_short,
                 label,
                 vert_line_at_x=None):

    curve, xnorm = binvals_fit(bin_centerpoints, bin_vals)
    xvals = [c / xnorm for c in bin_centerpoints]
    plt.scatter(xvals, bin_vals, marker="x", alpha=0.5)
    plt.title("{}  - {}".format(tumor_short, label))
    plt.ylabel('fraction of donors with mutation in sample')
    plt.xlabel('cdna length')
    ax = plt.gca()
    curve.plot(num_pts=256, ax=ax, color='red')

    if vert_line_at_x:
        x = vert_line_at_x / xnorm
        plt.ylim([0.0, 0.3])
        vertical_line = bezier.Curve(np.asfortranarray([[float(x),
                                                         float(x)],
                                                        [0.0, 0.75]]),
                                     degree=1)
        vertical_line.plot(num_pts=25, ax=ax, color='red')

    plt.show()
Beispiel #21
0
 def curveTo(self, *points):
     pts = [self.double(self.__currentPoint)]
     pts.extend([self.double(pt) for pt in points])
     nodes = np.asfortranarray(pts)
     curve = bezier.Curve(nodes, degree=self.degree)
     self.current_contour.append(curve)
     self.__currentPoint = points[-1]
Beispiel #22
0
 def _calc_curve_override(self, curve: Curve):
     if self.side_offset is None:
         self.curve_override = None
     else:
         nodes = curve.curve.nodes
         nodes[:, 0] = list(self.position)
         self.curve_override = bezier.Curve(nodes, degree=2)
def plot_line(points):
    points = np.array(points, dtype=int).T
    curve = bezier.Curve(points, degree=points.shape[1] - 1)
    s_vals = np.linspace(0.0, 1.0, 100)  # 100 is the num of pionts
    data = curve.evaluate_multi(s_vals)
    data = tuple(data.T)
    return data
Beispiel #24
0
 def _qCurveToOne(self, pt1, pt2):
     pts = [self.double(self.__currentPoint)]
     pts.append(self.double(pt1))
     pts.append(self.double(pt2))
     nodes = np.asfortranarray(pts)
     curve = bezier.Curve(nodes, degree=self.degree)
     self.current_contour.append(curve)
Beispiel #25
0
def _get_bezier_curve(x1, x2):
	pi, ei = x1
	pf, ef = x2
	p1 = pi + D_1 * ei
	p2 = pf - D_1 * ef
	nodes = np.concatenate([pi, p1, p2, pf], axis=1)
	return bezier.Curve(nodes, degree=3)
Beispiel #26
0
def plot_glif(glyph_path, show_points=True):
    """ Plotting .glif XML format file in UFO font data.

    Args:
        glyph_path:: str
    """
    class _Point:
        def __init__(self, x, y, type_):
            self.x = x
            self.y = y
            self.type = type_
    # subplot = plt.subplot(xlim=(0, xml_glyph.find('advance').attrib['width']), 
                          # ylim=(0, 1000)) # TODO: Needs modify
    xml_glyph = et.parse(glyph_path).getroot()
    contours = xml_glyph.find('outline').getchildren()
    curve_points = [_Point(p.attrib['x'], p.attrib['y'], p.attrib.get('type')) \
                    for p in contours[0].getchildren()[:4]]
    nodes = np.asfortranarray([
        [float(p.x) for p in curve_points],
        [float(p.y) for p in curve_points]])
    subplot = bezier.Curve(nodes, degree=3).plot(100) # TODO: width
    for contour in contours:
        points = [_Point(p.attrib['x'], p.attrib['y'], p.attrib.get('type')) \
                  for p in contour.getchildren()]
        for idx, point in enumerate(points):
            if point.type == 'line':
                plot_line(subplot, [points[idx+i] for i in range(-1, 1)], show_points)
            elif point.type == 'curve':
                plot_curve(subplot, [points[idx+i] for i in range(-3, 1)], show_points)
            else:
                continue
    plt.show()
def compute_edge_shape(location_nextlocs, location_prototype):
    fmov = list()
    weight = list()
    for lid1 in location_nextlocs:
        for lid2 in location_nextlocs[lid1]:
            s = location_prototype[lid1]
            e = location_prototype[lid2]
            gap = 0.05 * abs(e[1] - s[1]) / 0.05
            nodes = np.asfortranarray([
                [
                    s[1], (s[1] + e[1]) / 2 + np.random.choice([gap, -gap]),
                    e[1]
                ],
                [
                    s[0], (s[0] + e[0]) / 2 + np.random.choice([gap, -gap]),
                    e[0]
                ],
            ])
            curve = bezier.Curve(nodes, degree=2)
            val = curve.evaluate_multi(np.linspace(0.0, 1.0, 10))
            x_val = val[0]
            y_val = val[1]
            mov = list()
            for xv, yv in zip(x_val, y_val):
                mov.append([xv, yv])

            fmov.append(mov)
            weight.append(np.log(location_nextlocs[lid1][lid2] * 10))
    return fmov, weight
def curve_value_at_x(curve, x):
    #  strategy = bezier.curve.IntersectionStrategy.ALGEBRAIC fails with
    #  The only degrees supported at this time are 0, 1, 2, 3 and 4 (degree=11)

    # crashing on arbitrarty intersection points - never figured out why
    # File "src/bezier/_speedup.pyx", line 485, in bezier._speedup.curve_intersections
    # ValueError: Curve intersection failed to converge to approximately linear subdivisions after 20 iterations.
    # solved by renormalizing the x-range to [0, 1.0] interval

    strategy = bezier.curve.IntersectionStrategy.GEOMETRIC
    vertical_line = bezier.Curve(np.asfortranarray([[float(x),
                                                     float(x)], [-0.75,
                                                                 0.75]]),
                                 degree=1)
    intersections = curve.intersect(
        vertical_line,
        strategy=strategy)  # why is this plural?  why two parameters?
    s_vals = np.asfortranarray(intersections[0, :])
    point = curve.evaluate_multi(s_vals)
    # point is given as [[x],[y]]

    if point.size == 2:
        return point[1][0]
    else:
        return None
def binvals_fit(bin_centerpoints, bin_vals):
    # decimation - Bezier chokes on too many points
    superbin_size = int(len(bin_centerpoints) / 20)
    x = [0]
    y = [0]
    for i in range(0, len(bin_centerpoints), superbin_size):
        n = len(bin_centerpoints[i:i + superbin_size])
        x.append(sum(bin_centerpoints[i:i + superbin_size]) / n)
        y.append(sum(bin_vals[i:i + superbin_size]) / n)

    xnorm = x[
        -1]  # bezier apparently does not like really big numbers (as in 10^5)
    x = [e / xnorm for e in x]

    nodes = np.asfortranarray([x, y])
    curve = bezier.Curve(nodes, degree=2)

    # plt.scatter(x, y)
    # plt.title("test")
    # plt.ylabel('fraction of donors with mutation in sample')
    # plt.xlabel('cdna length')
    # ax = plt.gca()
    # curve.plot(num_pts=256, ax=ax, color = 'red')
    # plt.ylim([0.0, 0.32])
    # p = [float(x[-2]/2), float(161745)/norm]
    # vertical_line = bezier.Curve(np.asfortranarray([[float(p[0]), float(p[0])],[0.0, 0.75]]), degree=1)
    # vertical_line.plot(num_pts=25, ax=ax, color = 'red')
    # vertical_line = bezier.Curve(np.asfortranarray([[float(p[1]), float(p[1])],[0.0, 0.75]]), degree=1)
    # vertical_line.plot(num_pts=25, ax=ax, color = 'blue')
    # plt.show()
    # print(" %d   %.3f" % (p[0]*norm, curve_value_at_x (curve, p[0])) )
    # print(" %d   %.3f" % (p[1]*norm, curve_value_at_x (curve, p[1])) )
    # exit()

    return curve, xnorm
Beispiel #30
0
def main():

    # x = [0.0, 1.0, 2.0, 3.0]
    # y = [0.0, 1.0, 2.0, 3.0]
    # ps = [1.0, 2.0]

    # this will crash with
    # File "src/bezier/_speedup.pyx", line 485, in bezier._speedup.curve_intersections
    # ValueError: Curve intersection failed to converge to approximately linear subdivisions after 20 iterations.
    x = [0.0, 69708.0, 204470.0, 339500.0]
    y = [0.000, 0.052, 0.141, 0.214]
    ps = [237685.0, 161745.0]

    # this, however, works
    norm = x[-1]
    x = [e / norm for e in x]
    ps = [p / norm for p in ps]

    nodes = np.asfortranarray([x, y])
    curve = bezier.Curve(nodes, degree=2)

    plt.scatter(x, y)
    plt.title("test")
    plt.ylabel('x')
    plt.xlabel('y')
    ax = plt.gca()
    curve.plot(num_pts=256, ax=ax, color='red')
    plt.ylim([0.0, y[-1] * 1.1])

    vertical_lines = []
    for p in ps:
        vertical_lines.append(
            bezier.Curve(np.asfortranarray([[float(p), float(p)], [0.0, 5.0]]),
                         degree=1))

    for vl in vertical_lines:
        vl.plot(num_pts=25, ax=ax, color='red')
    plt.show()

    for vl in vertical_lines:
        intersections = curve.intersect(vl)
        s_vals = np.asfortranarray(intersections[0, :])
        point = curve.evaluate_multi(s_vals)
        if point.size == 2:
            print(" >> ", point[1][0])
        else:
            print(" >> ", "no return")