repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
sequencelengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
sequencelengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
dhermes/bezier
docs/make_images.py
surface_subdivide1
def surface_subdivide1(): """Image for :meth`.Surface.subdivide` docstring.""" if NO_IMAGES: return surface = bezier.Surface.from_nodes( np.asfortranarray([[0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]) ) surf_a, surf_b, surf_c, surf_d = surface.subdivide() figure, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2) for ax in (ax1, ax2, ax3, ax4): surface.plot(2, ax=ax) surf_a.plot(2, ax=ax1) ax1.text( 1.0 / 6.0, 1.0 / 6.0, r"$A$", fontsize=20, verticalalignment="center", horizontalalignment="center", ) surf_b.plot(2, ax=ax2) ax2.text( 1.0 / 3.0, 1.0 / 3.0, r"$B$", fontsize=20, verticalalignment="center", horizontalalignment="center", ) surf_c.plot(2, ax=ax3) ax3.text( 2.0 / 3.0, 1.0 / 6.0, r"$C$", fontsize=20, verticalalignment="center", horizontalalignment="center", ) surf_d.plot(2, ax=ax4) ax4.text( 1.0 / 6.0, 2.0 / 3.0, r"$D$", fontsize=20, verticalalignment="center", horizontalalignment="center", ) for ax in (ax1, ax2, ax3, ax4): ax.axis("scaled") save_image(figure, "surface_subdivide1")
python
def surface_subdivide1(): """Image for :meth`.Surface.subdivide` docstring.""" if NO_IMAGES: return surface = bezier.Surface.from_nodes( np.asfortranarray([[0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]) ) surf_a, surf_b, surf_c, surf_d = surface.subdivide() figure, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2) for ax in (ax1, ax2, ax3, ax4): surface.plot(2, ax=ax) surf_a.plot(2, ax=ax1) ax1.text( 1.0 / 6.0, 1.0 / 6.0, r"$A$", fontsize=20, verticalalignment="center", horizontalalignment="center", ) surf_b.plot(2, ax=ax2) ax2.text( 1.0 / 3.0, 1.0 / 3.0, r"$B$", fontsize=20, verticalalignment="center", horizontalalignment="center", ) surf_c.plot(2, ax=ax3) ax3.text( 2.0 / 3.0, 1.0 / 6.0, r"$C$", fontsize=20, verticalalignment="center", horizontalalignment="center", ) surf_d.plot(2, ax=ax4) ax4.text( 1.0 / 6.0, 2.0 / 3.0, r"$D$", fontsize=20, verticalalignment="center", horizontalalignment="center", ) for ax in (ax1, ax2, ax3, ax4): ax.axis("scaled") save_image(figure, "surface_subdivide1")
[ "def", "surface_subdivide1", "(", ")", ":", "if", "NO_IMAGES", ":", "return", "surface", "=", "bezier", ".", "Surface", ".", "from_nodes", "(", "np", ".", "asfortranarray", "(", "[", "[", "0.0", ",", "1.0", ",", "0.0", "]", ",", "[", "0.0", ",", "0.0", ",", "1.0", "]", "]", ")", ")", "surf_a", ",", "surf_b", ",", "surf_c", ",", "surf_d", "=", "surface", ".", "subdivide", "(", ")", "figure", ",", "(", "(", "ax1", ",", "ax2", ")", ",", "(", "ax3", ",", "ax4", ")", ")", "=", "plt", ".", "subplots", "(", "2", ",", "2", ")", "for", "ax", "in", "(", "ax1", ",", "ax2", ",", "ax3", ",", "ax4", ")", ":", "surface", ".", "plot", "(", "2", ",", "ax", "=", "ax", ")", "surf_a", ".", "plot", "(", "2", ",", "ax", "=", "ax1", ")", "ax1", ".", "text", "(", "1.0", "/", "6.0", ",", "1.0", "/", "6.0", ",", "r\"$A$\"", ",", "fontsize", "=", "20", ",", "verticalalignment", "=", "\"center\"", ",", "horizontalalignment", "=", "\"center\"", ",", ")", "surf_b", ".", "plot", "(", "2", ",", "ax", "=", "ax2", ")", "ax2", ".", "text", "(", "1.0", "/", "3.0", ",", "1.0", "/", "3.0", ",", "r\"$B$\"", ",", "fontsize", "=", "20", ",", "verticalalignment", "=", "\"center\"", ",", "horizontalalignment", "=", "\"center\"", ",", ")", "surf_c", ".", "plot", "(", "2", ",", "ax", "=", "ax3", ")", "ax3", ".", "text", "(", "2.0", "/", "3.0", ",", "1.0", "/", "6.0", ",", "r\"$C$\"", ",", "fontsize", "=", "20", ",", "verticalalignment", "=", "\"center\"", ",", "horizontalalignment", "=", "\"center\"", ",", ")", "surf_d", ".", "plot", "(", "2", ",", "ax", "=", "ax4", ")", "ax4", ".", "text", "(", "1.0", "/", "6.0", ",", "2.0", "/", "3.0", ",", "r\"$D$\"", ",", "fontsize", "=", "20", ",", "verticalalignment", "=", "\"center\"", ",", "horizontalalignment", "=", "\"center\"", ",", ")", "for", "ax", "in", "(", "ax1", ",", "ax2", ",", "ax3", ",", "ax4", ")", ":", "ax", ".", "axis", "(", "\"scaled\"", ")", "save_image", "(", "figure", ",", "\"surface_subdivide1\"", ")" ]
Image for :meth`.Surface.subdivide` docstring.
[ "Image", "for", ":", "meth", ".", "Surface", ".", "subdivide", "docstring", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/docs/make_images.py#L535-L585
dhermes/bezier
docs/make_images.py
surface_subdivide2
def surface_subdivide2(surface, sub_surface_b): """Image for :meth`.Surface.subdivide` docstring.""" if NO_IMAGES: return # Plot set-up. figure = plt.figure() ax = figure.gca() colors = seaborn.husl_palette(6) N = 128 s_vals = np.linspace(0.0, 1.0, N + 1) # Add edges from surface. add_edges(ax, surface, s_vals, colors[4]) # Now do the same for surface B. add_edges(ax, sub_surface_b, s_vals, colors[0]) # Add the control points polygon for the original surface. nodes = surface._nodes[:, (0, 2, 4, 5, 0)] add_patch(ax, nodes, colors[2], with_nodes=False) # Add the control points polygon for the sub-surface. nodes = sub_surface_b._nodes[:, (0, 1, 2, 5, 3, 0)] add_patch(ax, nodes, colors[1], with_nodes=False) # Plot **all** the nodes. sub_nodes = sub_surface_b._nodes ax.plot( sub_nodes[0, :], sub_nodes[1, :], color="black", linestyle="None", marker="o", ) # Take those same points and add the boundary. ax.plot(nodes[0, :], nodes[1, :], color="black", linestyle="dashed") ax.axis("scaled") ax.set_xlim(-1.125, 2.125) ax.set_ylim(-0.125, 4.125) save_image(ax.figure, "surface_subdivide2")
python
def surface_subdivide2(surface, sub_surface_b): """Image for :meth`.Surface.subdivide` docstring.""" if NO_IMAGES: return # Plot set-up. figure = plt.figure() ax = figure.gca() colors = seaborn.husl_palette(6) N = 128 s_vals = np.linspace(0.0, 1.0, N + 1) # Add edges from surface. add_edges(ax, surface, s_vals, colors[4]) # Now do the same for surface B. add_edges(ax, sub_surface_b, s_vals, colors[0]) # Add the control points polygon for the original surface. nodes = surface._nodes[:, (0, 2, 4, 5, 0)] add_patch(ax, nodes, colors[2], with_nodes=False) # Add the control points polygon for the sub-surface. nodes = sub_surface_b._nodes[:, (0, 1, 2, 5, 3, 0)] add_patch(ax, nodes, colors[1], with_nodes=False) # Plot **all** the nodes. sub_nodes = sub_surface_b._nodes ax.plot( sub_nodes[0, :], sub_nodes[1, :], color="black", linestyle="None", marker="o", ) # Take those same points and add the boundary. ax.plot(nodes[0, :], nodes[1, :], color="black", linestyle="dashed") ax.axis("scaled") ax.set_xlim(-1.125, 2.125) ax.set_ylim(-0.125, 4.125) save_image(ax.figure, "surface_subdivide2")
[ "def", "surface_subdivide2", "(", "surface", ",", "sub_surface_b", ")", ":", "if", "NO_IMAGES", ":", "return", "# Plot set-up.", "figure", "=", "plt", ".", "figure", "(", ")", "ax", "=", "figure", ".", "gca", "(", ")", "colors", "=", "seaborn", ".", "husl_palette", "(", "6", ")", "N", "=", "128", "s_vals", "=", "np", ".", "linspace", "(", "0.0", ",", "1.0", ",", "N", "+", "1", ")", "# Add edges from surface.", "add_edges", "(", "ax", ",", "surface", ",", "s_vals", ",", "colors", "[", "4", "]", ")", "# Now do the same for surface B.", "add_edges", "(", "ax", ",", "sub_surface_b", ",", "s_vals", ",", "colors", "[", "0", "]", ")", "# Add the control points polygon for the original surface.", "nodes", "=", "surface", ".", "_nodes", "[", ":", ",", "(", "0", ",", "2", ",", "4", ",", "5", ",", "0", ")", "]", "add_patch", "(", "ax", ",", "nodes", ",", "colors", "[", "2", "]", ",", "with_nodes", "=", "False", ")", "# Add the control points polygon for the sub-surface.", "nodes", "=", "sub_surface_b", ".", "_nodes", "[", ":", ",", "(", "0", ",", "1", ",", "2", ",", "5", ",", "3", ",", "0", ")", "]", "add_patch", "(", "ax", ",", "nodes", ",", "colors", "[", "1", "]", ",", "with_nodes", "=", "False", ")", "# Plot **all** the nodes.", "sub_nodes", "=", "sub_surface_b", ".", "_nodes", "ax", ".", "plot", "(", "sub_nodes", "[", "0", ",", ":", "]", ",", "sub_nodes", "[", "1", ",", ":", "]", ",", "color", "=", "\"black\"", ",", "linestyle", "=", "\"None\"", ",", "marker", "=", "\"o\"", ",", ")", "# Take those same points and add the boundary.", "ax", ".", "plot", "(", "nodes", "[", "0", ",", ":", "]", ",", "nodes", "[", "1", ",", ":", "]", ",", "color", "=", "\"black\"", ",", "linestyle", "=", "\"dashed\"", ")", "ax", ".", "axis", "(", "\"scaled\"", ")", "ax", ".", "set_xlim", "(", "-", "1.125", ",", "2.125", ")", "ax", ".", "set_ylim", "(", "-", "0.125", ",", "4.125", ")", "save_image", "(", "ax", ".", "figure", ",", "\"surface_subdivide2\"", ")" ]
Image for :meth`.Surface.subdivide` docstring.
[ "Image", "for", ":", "meth", ".", "Surface", ".", "subdivide", "docstring", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/docs/make_images.py#L600-L635
dhermes/bezier
docs/make_images.py
curved_polygon_constructor1
def curved_polygon_constructor1(curved_poly): """Image for :class`.CurvedPolygon` docstring.""" if NO_IMAGES: return ax = curved_poly.plot(256) ax.axis("scaled") ax.set_xlim(-0.125, 2.125) ax.set_ylim(-0.625, 1.625) save_image(ax.figure, "curved_polygon_constructor1.png")
python
def curved_polygon_constructor1(curved_poly): """Image for :class`.CurvedPolygon` docstring.""" if NO_IMAGES: return ax = curved_poly.plot(256) ax.axis("scaled") ax.set_xlim(-0.125, 2.125) ax.set_ylim(-0.625, 1.625) save_image(ax.figure, "curved_polygon_constructor1.png")
[ "def", "curved_polygon_constructor1", "(", "curved_poly", ")", ":", "if", "NO_IMAGES", ":", "return", "ax", "=", "curved_poly", ".", "plot", "(", "256", ")", "ax", ".", "axis", "(", "\"scaled\"", ")", "ax", ".", "set_xlim", "(", "-", "0.125", ",", "2.125", ")", "ax", ".", "set_ylim", "(", "-", "0.625", ",", "1.625", ")", "save_image", "(", "ax", ".", "figure", ",", "\"curved_polygon_constructor1.png\"", ")" ]
Image for :class`.CurvedPolygon` docstring.
[ "Image", "for", ":", "class", ".", "CurvedPolygon", "docstring", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/docs/make_images.py#L638-L647
dhermes/bezier
docs/make_images.py
curve_specialize
def curve_specialize(curve, new_curve): """Image for :meth`.Curve.specialize` docstring.""" if NO_IMAGES: return ax = curve.plot(256) interval = r"$\left[0, 1\right]$" line = ax.lines[-1] line.set_label(interval) color1 = line.get_color() new_curve.plot(256, ax=ax) interval = r"$\left[-\frac{1}{4}, \frac{3}{4}\right]$" line = ax.lines[-1] line.set_label(interval) ax.plot( curve._nodes[0, (0, -1)], curve._nodes[1, (0, -1)], color=color1, linestyle="None", marker="o", ) ax.plot( new_curve._nodes[0, (0, -1)], new_curve._nodes[1, (0, -1)], color=line.get_color(), linestyle="None", marker="o", ) ax.legend(loc="lower right", fontsize=12) ax.axis("scaled") ax.set_xlim(-0.375, 1.125) ax.set_ylim(-0.75, 0.625) save_image(ax.figure, "curve_specialize.png")
python
def curve_specialize(curve, new_curve): """Image for :meth`.Curve.specialize` docstring.""" if NO_IMAGES: return ax = curve.plot(256) interval = r"$\left[0, 1\right]$" line = ax.lines[-1] line.set_label(interval) color1 = line.get_color() new_curve.plot(256, ax=ax) interval = r"$\left[-\frac{1}{4}, \frac{3}{4}\right]$" line = ax.lines[-1] line.set_label(interval) ax.plot( curve._nodes[0, (0, -1)], curve._nodes[1, (0, -1)], color=color1, linestyle="None", marker="o", ) ax.plot( new_curve._nodes[0, (0, -1)], new_curve._nodes[1, (0, -1)], color=line.get_color(), linestyle="None", marker="o", ) ax.legend(loc="lower right", fontsize=12) ax.axis("scaled") ax.set_xlim(-0.375, 1.125) ax.set_ylim(-0.75, 0.625) save_image(ax.figure, "curve_specialize.png")
[ "def", "curve_specialize", "(", "curve", ",", "new_curve", ")", ":", "if", "NO_IMAGES", ":", "return", "ax", "=", "curve", ".", "plot", "(", "256", ")", "interval", "=", "r\"$\\left[0, 1\\right]$\"", "line", "=", "ax", ".", "lines", "[", "-", "1", "]", "line", ".", "set_label", "(", "interval", ")", "color1", "=", "line", ".", "get_color", "(", ")", "new_curve", ".", "plot", "(", "256", ",", "ax", "=", "ax", ")", "interval", "=", "r\"$\\left[-\\frac{1}{4}, \\frac{3}{4}\\right]$\"", "line", "=", "ax", ".", "lines", "[", "-", "1", "]", "line", ".", "set_label", "(", "interval", ")", "ax", ".", "plot", "(", "curve", ".", "_nodes", "[", "0", ",", "(", "0", ",", "-", "1", ")", "]", ",", "curve", ".", "_nodes", "[", "1", ",", "(", "0", ",", "-", "1", ")", "]", ",", "color", "=", "color1", ",", "linestyle", "=", "\"None\"", ",", "marker", "=", "\"o\"", ",", ")", "ax", ".", "plot", "(", "new_curve", ".", "_nodes", "[", "0", ",", "(", "0", ",", "-", "1", ")", "]", ",", "new_curve", ".", "_nodes", "[", "1", ",", "(", "0", ",", "-", "1", ")", "]", ",", "color", "=", "line", ".", "get_color", "(", ")", ",", "linestyle", "=", "\"None\"", ",", "marker", "=", "\"o\"", ",", ")", "ax", ".", "legend", "(", "loc", "=", "\"lower right\"", ",", "fontsize", "=", "12", ")", "ax", ".", "axis", "(", "\"scaled\"", ")", "ax", ".", "set_xlim", "(", "-", "0.375", ",", "1.125", ")", "ax", ".", "set_ylim", "(", "-", "0.75", ",", "0.625", ")", "save_image", "(", "ax", ".", "figure", ",", "\"curve_specialize.png\"", ")" ]
Image for :meth`.Curve.specialize` docstring.
[ "Image", "for", ":", "meth", ".", "Curve", ".", "specialize", "docstring", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/docs/make_images.py#L677-L709
dhermes/bezier
docs/make_images.py
newton_refine_surface
def newton_refine_surface(surface, x_val, y_val, s, t, new_s, new_t): """Image for :func:`._surface_helpers.newton_refine` docstring.""" if NO_IMAGES: return figure, (ax1, ax2) = plt.subplots(1, 2) # Plot features of the parameter space in ax1. tri_surf = bezier.Surface.from_nodes( np.asfortranarray([[0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]) ) tri_surf.plot(2, ax=ax1) ax1.plot([0.25], [0.5], marker="H") ax1.plot([s], [t], color="black", linestyle="None", marker="o") ax1.plot( [new_s], [new_t], color="black", linestyle="None", marker="o", markeredgewidth=1, markerfacecolor="None", ) # Plot the equivalent output in ax2. surface.plot(256, ax=ax2) points = surface.evaluate_cartesian_multi( np.asfortranarray([[s, t], [new_s, new_t]]) ) ax2.plot([x_val], [y_val], marker="H") ax2.plot( points[0, [0]], points[1, [0]], color="black", linestyle="None", marker="o", ) ax2.plot( points[0, [1]], points[1, [1]], color="black", linestyle="None", marker="o", markeredgewidth=1, markerfacecolor="None", ) # Set the axis bounds / scaling. ax1.axis("scaled") ax1.set_xlim(-0.0625, 1.0625) ax1.set_ylim(-0.0625, 1.0625) ax2.axis("scaled") ax2.set_xlim(-0.125, 2.125) ax2.set_ylim(-0.125, 2.125) save_image(figure, "newton_refine_surface.png")
python
def newton_refine_surface(surface, x_val, y_val, s, t, new_s, new_t): """Image for :func:`._surface_helpers.newton_refine` docstring.""" if NO_IMAGES: return figure, (ax1, ax2) = plt.subplots(1, 2) # Plot features of the parameter space in ax1. tri_surf = bezier.Surface.from_nodes( np.asfortranarray([[0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]) ) tri_surf.plot(2, ax=ax1) ax1.plot([0.25], [0.5], marker="H") ax1.plot([s], [t], color="black", linestyle="None", marker="o") ax1.plot( [new_s], [new_t], color="black", linestyle="None", marker="o", markeredgewidth=1, markerfacecolor="None", ) # Plot the equivalent output in ax2. surface.plot(256, ax=ax2) points = surface.evaluate_cartesian_multi( np.asfortranarray([[s, t], [new_s, new_t]]) ) ax2.plot([x_val], [y_val], marker="H") ax2.plot( points[0, [0]], points[1, [0]], color="black", linestyle="None", marker="o", ) ax2.plot( points[0, [1]], points[1, [1]], color="black", linestyle="None", marker="o", markeredgewidth=1, markerfacecolor="None", ) # Set the axis bounds / scaling. ax1.axis("scaled") ax1.set_xlim(-0.0625, 1.0625) ax1.set_ylim(-0.0625, 1.0625) ax2.axis("scaled") ax2.set_xlim(-0.125, 2.125) ax2.set_ylim(-0.125, 2.125) save_image(figure, "newton_refine_surface.png")
[ "def", "newton_refine_surface", "(", "surface", ",", "x_val", ",", "y_val", ",", "s", ",", "t", ",", "new_s", ",", "new_t", ")", ":", "if", "NO_IMAGES", ":", "return", "figure", ",", "(", "ax1", ",", "ax2", ")", "=", "plt", ".", "subplots", "(", "1", ",", "2", ")", "# Plot features of the parameter space in ax1.", "tri_surf", "=", "bezier", ".", "Surface", ".", "from_nodes", "(", "np", ".", "asfortranarray", "(", "[", "[", "0.0", ",", "1.0", ",", "0.0", "]", ",", "[", "0.0", ",", "0.0", ",", "1.0", "]", "]", ")", ")", "tri_surf", ".", "plot", "(", "2", ",", "ax", "=", "ax1", ")", "ax1", ".", "plot", "(", "[", "0.25", "]", ",", "[", "0.5", "]", ",", "marker", "=", "\"H\"", ")", "ax1", ".", "plot", "(", "[", "s", "]", ",", "[", "t", "]", ",", "color", "=", "\"black\"", ",", "linestyle", "=", "\"None\"", ",", "marker", "=", "\"o\"", ")", "ax1", ".", "plot", "(", "[", "new_s", "]", ",", "[", "new_t", "]", ",", "color", "=", "\"black\"", ",", "linestyle", "=", "\"None\"", ",", "marker", "=", "\"o\"", ",", "markeredgewidth", "=", "1", ",", "markerfacecolor", "=", "\"None\"", ",", ")", "# Plot the equivalent output in ax2.", "surface", ".", "plot", "(", "256", ",", "ax", "=", "ax2", ")", "points", "=", "surface", ".", "evaluate_cartesian_multi", "(", "np", ".", "asfortranarray", "(", "[", "[", "s", ",", "t", "]", ",", "[", "new_s", ",", "new_t", "]", "]", ")", ")", "ax2", ".", "plot", "(", "[", "x_val", "]", ",", "[", "y_val", "]", ",", "marker", "=", "\"H\"", ")", "ax2", ".", "plot", "(", "points", "[", "0", ",", "[", "0", "]", "]", ",", "points", "[", "1", ",", "[", "0", "]", "]", ",", "color", "=", "\"black\"", ",", "linestyle", "=", "\"None\"", ",", "marker", "=", "\"o\"", ",", ")", "ax2", ".", "plot", "(", "points", "[", "0", ",", "[", "1", "]", "]", ",", "points", "[", "1", ",", "[", "1", "]", "]", ",", "color", "=", "\"black\"", ",", "linestyle", "=", "\"None\"", ",", "marker", "=", "\"o\"", ",", "markeredgewidth", "=", "1", ",", "markerfacecolor", "=", "\"None\"", ",", ")", "# Set the axis bounds / scaling.", "ax1", ".", "axis", "(", "\"scaled\"", ")", "ax1", ".", "set_xlim", "(", "-", "0.0625", ",", "1.0625", ")", "ax1", ".", "set_ylim", "(", "-", "0.0625", ",", "1.0625", ")", "ax2", ".", "axis", "(", "\"scaled\"", ")", "ax2", ".", "set_xlim", "(", "-", "0.125", ",", "2.125", ")", "ax2", ".", "set_ylim", "(", "-", "0.125", ",", "2.125", ")", "save_image", "(", "figure", ",", "\"newton_refine_surface.png\"", ")" ]
Image for :func:`._surface_helpers.newton_refine` docstring.
[ "Image", "for", ":", "func", ":", ".", "_surface_helpers", ".", "newton_refine", "docstring", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/docs/make_images.py#L712-L763
dhermes/bezier
docs/make_images.py
classify_intersection1
def classify_intersection1(s, curve1, tangent1, curve2, tangent2): """Image for :func:`._surface_helpers.classify_intersection` docstring.""" if NO_IMAGES: return surface1 = bezier.Surface.from_nodes( np.asfortranarray( [[1.0, 1.75, 2.0, 1.0, 1.5, 1.0], [0.0, 0.25, 1.0, 1.0, 1.5, 2.0]] ) ) surface2 = bezier.Surface.from_nodes( np.asfortranarray( [ [0.0, 1.6875, 2.0, 0.25, 1.25, 0.5], [0.0, 0.0625, 0.5, 1.0, 1.25, 2.0], ] ) ) ax = classify_help(s, curve1, surface1, curve2, surface2, 0) (int_x,), (int_y,) = curve1.evaluate(s) # Remove the alpha from the color color1 = ax.patches[0].get_facecolor()[:3] color2 = ax.patches[1].get_facecolor()[:3] ax.plot( [int_x, int_x + tangent1[0, 0]], [int_y, int_y + tangent1[1, 0]], color=color1, linestyle="dashed", ) ax.plot( [int_x, int_x + tangent2[0, 0]], [int_y, int_y + tangent2[1, 0]], color=color2, linestyle="dashed", ) ax.plot([int_x], [int_y], color=color1, linestyle="None", marker="o") ax.axis("scaled") ax.set_xlim(-0.125, 2.125) ax.set_ylim(-0.125, 1.125) save_image(ax.figure, "classify_intersection1.png")
python
def classify_intersection1(s, curve1, tangent1, curve2, tangent2): """Image for :func:`._surface_helpers.classify_intersection` docstring.""" if NO_IMAGES: return surface1 = bezier.Surface.from_nodes( np.asfortranarray( [[1.0, 1.75, 2.0, 1.0, 1.5, 1.0], [0.0, 0.25, 1.0, 1.0, 1.5, 2.0]] ) ) surface2 = bezier.Surface.from_nodes( np.asfortranarray( [ [0.0, 1.6875, 2.0, 0.25, 1.25, 0.5], [0.0, 0.0625, 0.5, 1.0, 1.25, 2.0], ] ) ) ax = classify_help(s, curve1, surface1, curve2, surface2, 0) (int_x,), (int_y,) = curve1.evaluate(s) # Remove the alpha from the color color1 = ax.patches[0].get_facecolor()[:3] color2 = ax.patches[1].get_facecolor()[:3] ax.plot( [int_x, int_x + tangent1[0, 0]], [int_y, int_y + tangent1[1, 0]], color=color1, linestyle="dashed", ) ax.plot( [int_x, int_x + tangent2[0, 0]], [int_y, int_y + tangent2[1, 0]], color=color2, linestyle="dashed", ) ax.plot([int_x], [int_y], color=color1, linestyle="None", marker="o") ax.axis("scaled") ax.set_xlim(-0.125, 2.125) ax.set_ylim(-0.125, 1.125) save_image(ax.figure, "classify_intersection1.png")
[ "def", "classify_intersection1", "(", "s", ",", "curve1", ",", "tangent1", ",", "curve2", ",", "tangent2", ")", ":", "if", "NO_IMAGES", ":", "return", "surface1", "=", "bezier", ".", "Surface", ".", "from_nodes", "(", "np", ".", "asfortranarray", "(", "[", "[", "1.0", ",", "1.75", ",", "2.0", ",", "1.0", ",", "1.5", ",", "1.0", "]", ",", "[", "0.0", ",", "0.25", ",", "1.0", ",", "1.0", ",", "1.5", ",", "2.0", "]", "]", ")", ")", "surface2", "=", "bezier", ".", "Surface", ".", "from_nodes", "(", "np", ".", "asfortranarray", "(", "[", "[", "0.0", ",", "1.6875", ",", "2.0", ",", "0.25", ",", "1.25", ",", "0.5", "]", ",", "[", "0.0", ",", "0.0625", ",", "0.5", ",", "1.0", ",", "1.25", ",", "2.0", "]", ",", "]", ")", ")", "ax", "=", "classify_help", "(", "s", ",", "curve1", ",", "surface1", ",", "curve2", ",", "surface2", ",", "0", ")", "(", "int_x", ",", ")", ",", "(", "int_y", ",", ")", "=", "curve1", ".", "evaluate", "(", "s", ")", "# Remove the alpha from the color", "color1", "=", "ax", ".", "patches", "[", "0", "]", ".", "get_facecolor", "(", ")", "[", ":", "3", "]", "color2", "=", "ax", ".", "patches", "[", "1", "]", ".", "get_facecolor", "(", ")", "[", ":", "3", "]", "ax", ".", "plot", "(", "[", "int_x", ",", "int_x", "+", "tangent1", "[", "0", ",", "0", "]", "]", ",", "[", "int_y", ",", "int_y", "+", "tangent1", "[", "1", ",", "0", "]", "]", ",", "color", "=", "color1", ",", "linestyle", "=", "\"dashed\"", ",", ")", "ax", ".", "plot", "(", "[", "int_x", ",", "int_x", "+", "tangent2", "[", "0", ",", "0", "]", "]", ",", "[", "int_y", ",", "int_y", "+", "tangent2", "[", "1", ",", "0", "]", "]", ",", "color", "=", "color2", ",", "linestyle", "=", "\"dashed\"", ",", ")", "ax", ".", "plot", "(", "[", "int_x", "]", ",", "[", "int_y", "]", ",", "color", "=", "color1", ",", "linestyle", "=", "\"None\"", ",", "marker", "=", "\"o\"", ")", "ax", ".", "axis", "(", "\"scaled\"", ")", "ax", ".", "set_xlim", "(", "-", "0.125", ",", "2.125", ")", "ax", ".", "set_ylim", "(", "-", "0.125", ",", "1.125", ")", "save_image", "(", "ax", ".", "figure", ",", "\"classify_intersection1.png\"", ")" ]
Image for :func:`._surface_helpers.classify_intersection` docstring.
[ "Image", "for", ":", "func", ":", ".", "_surface_helpers", ".", "classify_intersection", "docstring", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/docs/make_images.py#L797-L836
dhermes/bezier
docs/make_images.py
classify_intersection2
def classify_intersection2(s, curve1, curve2): """Image for :func:`._surface_helpers.classify_intersection` docstring.""" if NO_IMAGES: return surface1 = bezier.Surface.from_nodes( np.asfortranarray( [[1.0, 1.5, 2.0, 1.25, 1.75, 1.5], [0.0, 1.0, 0.0, 1.0, 1.0, 2.0]] ) ) surface2 = bezier.Surface.from_nodes( np.asfortranarray( [[0.0, 1.5, 3.0, 0.75, 2.25, 1.5], [0.0, 1.0, 0.0, 2.0, 2.0, 4.0]] ) ) ax = classify_help(s, curve1, surface1, curve2, surface2, 1) ax.set_xlim(-0.0625, 3.0625) ax.set_ylim(-0.0625, 0.5625) save_image(ax.figure, "classify_intersection2.png")
python
def classify_intersection2(s, curve1, curve2): """Image for :func:`._surface_helpers.classify_intersection` docstring.""" if NO_IMAGES: return surface1 = bezier.Surface.from_nodes( np.asfortranarray( [[1.0, 1.5, 2.0, 1.25, 1.75, 1.5], [0.0, 1.0, 0.0, 1.0, 1.0, 2.0]] ) ) surface2 = bezier.Surface.from_nodes( np.asfortranarray( [[0.0, 1.5, 3.0, 0.75, 2.25, 1.5], [0.0, 1.0, 0.0, 2.0, 2.0, 4.0]] ) ) ax = classify_help(s, curve1, surface1, curve2, surface2, 1) ax.set_xlim(-0.0625, 3.0625) ax.set_ylim(-0.0625, 0.5625) save_image(ax.figure, "classify_intersection2.png")
[ "def", "classify_intersection2", "(", "s", ",", "curve1", ",", "curve2", ")", ":", "if", "NO_IMAGES", ":", "return", "surface1", "=", "bezier", ".", "Surface", ".", "from_nodes", "(", "np", ".", "asfortranarray", "(", "[", "[", "1.0", ",", "1.5", ",", "2.0", ",", "1.25", ",", "1.75", ",", "1.5", "]", ",", "[", "0.0", ",", "1.0", ",", "0.0", ",", "1.0", ",", "1.0", ",", "2.0", "]", "]", ")", ")", "surface2", "=", "bezier", ".", "Surface", ".", "from_nodes", "(", "np", ".", "asfortranarray", "(", "[", "[", "0.0", ",", "1.5", ",", "3.0", ",", "0.75", ",", "2.25", ",", "1.5", "]", ",", "[", "0.0", ",", "1.0", ",", "0.0", ",", "2.0", ",", "2.0", ",", "4.0", "]", "]", ")", ")", "ax", "=", "classify_help", "(", "s", ",", "curve1", ",", "surface1", ",", "curve2", ",", "surface2", ",", "1", ")", "ax", ".", "set_xlim", "(", "-", "0.0625", ",", "3.0625", ")", "ax", ".", "set_ylim", "(", "-", "0.0625", ",", "0.5625", ")", "save_image", "(", "ax", ".", "figure", ",", "\"classify_intersection2.png\"", ")" ]
Image for :func:`._surface_helpers.classify_intersection` docstring.
[ "Image", "for", ":", "func", ":", ".", "_surface_helpers", ".", "classify_intersection", "docstring", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/docs/make_images.py#L839-L857
dhermes/bezier
docs/make_images.py
classify_intersection5
def classify_intersection5(s, curve1, curve2): """Image for :func:`._surface_helpers.classify_intersection` docstring.""" if NO_IMAGES: return surface1 = bezier.Surface.from_nodes( np.asfortranarray( [ [1.0, 1.5, 2.0, 1.25, 1.75, 1.5], [0.0, 1.0, 0.0, 0.9375, 0.9375, 1.875], ] ) ) surface2 = bezier.Surface.from_nodes( np.asfortranarray( [ [3.0, 1.5, 0.0, 2.25, 0.75, 1.5], [0.0, 1.0, 0.0, -2.0, -2.0, -4.0], ] ) ) figure, (ax1, ax2) = plt.subplots(2, 1) classify_help(s, curve1, surface1, curve2, surface2, 0, ax=ax1) classify_help(s, curve1, surface1, curve2, surface2, 1, ax=ax2) # Remove the alpha from the color color1 = ax1.patches[0].get_facecolor()[:3] color2 = ax1.patches[1].get_facecolor()[:3] # Now add the "degenerate" intersection polygons. The first # comes from specializing to # left1(0.5, 1.0)-left2(0.0, 0.25)-right1(0.375, 0.5) surface3 = bezier.Surface.from_nodes( np.asfortranarray( [ [1.5, 1.75, 2.0, 1.6875, 1.9375, 1.875], [0.5, 0.5, 0.0, 0.5, 0.234375, 0.46875], ] ) ) # NOTE: We don't require the intersection polygon be valid. surface3.plot(256, ax=ax1) # The second comes from specializing to # left1(0.0, 0.5)-right1(0.5, 0.625)-left3(0.75, 1.0) surface4 = bezier.Surface.from_nodes( np.asfortranarray( [ [1.0, 1.25, 1.5, 1.0625, 1.3125, 1.125], [0.0, 0.5, 0.5, 0.234375, 0.5, 0.46875], ] ) ) # NOTE: We don't require the intersection polygon be valid. surface4.plot(256, ax=ax2) (int_x,), (int_y,) = curve1.evaluate(s) ax1.plot([int_x], [int_y], color=color1, linestyle="None", marker="o") ax2.plot([int_x], [int_y], color=color2, linestyle="None", marker="o") for ax in (ax1, ax2): ax.axis("scaled") ax.set_xlim(-0.0625, 3.0625) ax.set_ylim(-0.0625, 0.5625) plt.setp(ax1.get_xticklabels(), visible=False) figure.tight_layout(h_pad=-7.0) save_image(figure, "classify_intersection5.png")
python
def classify_intersection5(s, curve1, curve2): """Image for :func:`._surface_helpers.classify_intersection` docstring.""" if NO_IMAGES: return surface1 = bezier.Surface.from_nodes( np.asfortranarray( [ [1.0, 1.5, 2.0, 1.25, 1.75, 1.5], [0.0, 1.0, 0.0, 0.9375, 0.9375, 1.875], ] ) ) surface2 = bezier.Surface.from_nodes( np.asfortranarray( [ [3.0, 1.5, 0.0, 2.25, 0.75, 1.5], [0.0, 1.0, 0.0, -2.0, -2.0, -4.0], ] ) ) figure, (ax1, ax2) = plt.subplots(2, 1) classify_help(s, curve1, surface1, curve2, surface2, 0, ax=ax1) classify_help(s, curve1, surface1, curve2, surface2, 1, ax=ax2) # Remove the alpha from the color color1 = ax1.patches[0].get_facecolor()[:3] color2 = ax1.patches[1].get_facecolor()[:3] # Now add the "degenerate" intersection polygons. The first # comes from specializing to # left1(0.5, 1.0)-left2(0.0, 0.25)-right1(0.375, 0.5) surface3 = bezier.Surface.from_nodes( np.asfortranarray( [ [1.5, 1.75, 2.0, 1.6875, 1.9375, 1.875], [0.5, 0.5, 0.0, 0.5, 0.234375, 0.46875], ] ) ) # NOTE: We don't require the intersection polygon be valid. surface3.plot(256, ax=ax1) # The second comes from specializing to # left1(0.0, 0.5)-right1(0.5, 0.625)-left3(0.75, 1.0) surface4 = bezier.Surface.from_nodes( np.asfortranarray( [ [1.0, 1.25, 1.5, 1.0625, 1.3125, 1.125], [0.0, 0.5, 0.5, 0.234375, 0.5, 0.46875], ] ) ) # NOTE: We don't require the intersection polygon be valid. surface4.plot(256, ax=ax2) (int_x,), (int_y,) = curve1.evaluate(s) ax1.plot([int_x], [int_y], color=color1, linestyle="None", marker="o") ax2.plot([int_x], [int_y], color=color2, linestyle="None", marker="o") for ax in (ax1, ax2): ax.axis("scaled") ax.set_xlim(-0.0625, 3.0625) ax.set_ylim(-0.0625, 0.5625) plt.setp(ax1.get_xticklabels(), visible=False) figure.tight_layout(h_pad=-7.0) save_image(figure, "classify_intersection5.png")
[ "def", "classify_intersection5", "(", "s", ",", "curve1", ",", "curve2", ")", ":", "if", "NO_IMAGES", ":", "return", "surface1", "=", "bezier", ".", "Surface", ".", "from_nodes", "(", "np", ".", "asfortranarray", "(", "[", "[", "1.0", ",", "1.5", ",", "2.0", ",", "1.25", ",", "1.75", ",", "1.5", "]", ",", "[", "0.0", ",", "1.0", ",", "0.0", ",", "0.9375", ",", "0.9375", ",", "1.875", "]", ",", "]", ")", ")", "surface2", "=", "bezier", ".", "Surface", ".", "from_nodes", "(", "np", ".", "asfortranarray", "(", "[", "[", "3.0", ",", "1.5", ",", "0.0", ",", "2.25", ",", "0.75", ",", "1.5", "]", ",", "[", "0.0", ",", "1.0", ",", "0.0", ",", "-", "2.0", ",", "-", "2.0", ",", "-", "4.0", "]", ",", "]", ")", ")", "figure", ",", "(", "ax1", ",", "ax2", ")", "=", "plt", ".", "subplots", "(", "2", ",", "1", ")", "classify_help", "(", "s", ",", "curve1", ",", "surface1", ",", "curve2", ",", "surface2", ",", "0", ",", "ax", "=", "ax1", ")", "classify_help", "(", "s", ",", "curve1", ",", "surface1", ",", "curve2", ",", "surface2", ",", "1", ",", "ax", "=", "ax2", ")", "# Remove the alpha from the color", "color1", "=", "ax1", ".", "patches", "[", "0", "]", ".", "get_facecolor", "(", ")", "[", ":", "3", "]", "color2", "=", "ax1", ".", "patches", "[", "1", "]", ".", "get_facecolor", "(", ")", "[", ":", "3", "]", "# Now add the \"degenerate\" intersection polygons. The first", "# comes from specializing to", "# left1(0.5, 1.0)-left2(0.0, 0.25)-right1(0.375, 0.5)", "surface3", "=", "bezier", ".", "Surface", ".", "from_nodes", "(", "np", ".", "asfortranarray", "(", "[", "[", "1.5", ",", "1.75", ",", "2.0", ",", "1.6875", ",", "1.9375", ",", "1.875", "]", ",", "[", "0.5", ",", "0.5", ",", "0.0", ",", "0.5", ",", "0.234375", ",", "0.46875", "]", ",", "]", ")", ")", "# NOTE: We don't require the intersection polygon be valid.", "surface3", ".", "plot", "(", "256", ",", "ax", "=", "ax1", ")", "# The second comes from specializing to", "# left1(0.0, 0.5)-right1(0.5, 0.625)-left3(0.75, 1.0)", "surface4", "=", "bezier", ".", "Surface", ".", "from_nodes", "(", "np", ".", "asfortranarray", "(", "[", "[", "1.0", ",", "1.25", ",", "1.5", ",", "1.0625", ",", "1.3125", ",", "1.125", "]", ",", "[", "0.0", ",", "0.5", ",", "0.5", ",", "0.234375", ",", "0.5", ",", "0.46875", "]", ",", "]", ")", ")", "# NOTE: We don't require the intersection polygon be valid.", "surface4", ".", "plot", "(", "256", ",", "ax", "=", "ax2", ")", "(", "int_x", ",", ")", ",", "(", "int_y", ",", ")", "=", "curve1", ".", "evaluate", "(", "s", ")", "ax1", ".", "plot", "(", "[", "int_x", "]", ",", "[", "int_y", "]", ",", "color", "=", "color1", ",", "linestyle", "=", "\"None\"", ",", "marker", "=", "\"o\"", ")", "ax2", ".", "plot", "(", "[", "int_x", "]", ",", "[", "int_y", "]", ",", "color", "=", "color2", ",", "linestyle", "=", "\"None\"", ",", "marker", "=", "\"o\"", ")", "for", "ax", "in", "(", "ax1", ",", "ax2", ")", ":", "ax", ".", "axis", "(", "\"scaled\"", ")", "ax", ".", "set_xlim", "(", "-", "0.0625", ",", "3.0625", ")", "ax", ".", "set_ylim", "(", "-", "0.0625", ",", "0.5625", ")", "plt", ".", "setp", "(", "ax1", ".", "get_xticklabels", "(", ")", ",", "visible", "=", "False", ")", "figure", ".", "tight_layout", "(", "h_pad", "=", "-", "7.0", ")", "save_image", "(", "figure", ",", "\"classify_intersection5.png\"", ")" ]
Image for :func:`._surface_helpers.classify_intersection` docstring.
[ "Image", "for", ":", "func", ":", ".", "_surface_helpers", ".", "classify_intersection", "docstring", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/docs/make_images.py#L911-L972
dhermes/bezier
docs/make_images.py
classify_intersection7
def classify_intersection7(s, curve1a, curve1b, curve2): """Image for :func:`._surface_helpers.classify_intersection` docstring.""" if NO_IMAGES: return surface1 = bezier.Surface.from_nodes( np.asfortranarray( [ [0.0, 4.5, 9.0, 0.0, 4.5, 0.0], [0.0, 0.0, 2.25, 1.25, 2.375, 2.5], ] ) ) surface2 = bezier.Surface.from_nodes( np.asfortranarray( [ [11.25, 9.0, 2.75, 8.125, 3.875, 5.0], [0.0, 4.5, 1.0, -0.75, -0.25, -1.5], ] ) ) figure, (ax1, ax2) = plt.subplots(2, 1) classify_help(s, curve1a, surface1, curve2, surface2, None, ax=ax1) surface1._nodes = np.asfortranarray(surface1._nodes[:, (2, 4, 5, 1, 3, 0)]) surface1._edges = None classify_help(0.0, curve1b, surface1, curve2, surface2, 0, ax=ax2) for ax in (ax1, ax2): ax.set_xlim(-0.125, 11.5) ax.set_ylim(-0.125, 2.625) plt.setp(ax1.get_xticklabels(), visible=False) figure.tight_layout(h_pad=-5.0) save_image(figure, "classify_intersection7.png")
python
def classify_intersection7(s, curve1a, curve1b, curve2): """Image for :func:`._surface_helpers.classify_intersection` docstring.""" if NO_IMAGES: return surface1 = bezier.Surface.from_nodes( np.asfortranarray( [ [0.0, 4.5, 9.0, 0.0, 4.5, 0.0], [0.0, 0.0, 2.25, 1.25, 2.375, 2.5], ] ) ) surface2 = bezier.Surface.from_nodes( np.asfortranarray( [ [11.25, 9.0, 2.75, 8.125, 3.875, 5.0], [0.0, 4.5, 1.0, -0.75, -0.25, -1.5], ] ) ) figure, (ax1, ax2) = plt.subplots(2, 1) classify_help(s, curve1a, surface1, curve2, surface2, None, ax=ax1) surface1._nodes = np.asfortranarray(surface1._nodes[:, (2, 4, 5, 1, 3, 0)]) surface1._edges = None classify_help(0.0, curve1b, surface1, curve2, surface2, 0, ax=ax2) for ax in (ax1, ax2): ax.set_xlim(-0.125, 11.5) ax.set_ylim(-0.125, 2.625) plt.setp(ax1.get_xticklabels(), visible=False) figure.tight_layout(h_pad=-5.0) save_image(figure, "classify_intersection7.png")
[ "def", "classify_intersection7", "(", "s", ",", "curve1a", ",", "curve1b", ",", "curve2", ")", ":", "if", "NO_IMAGES", ":", "return", "surface1", "=", "bezier", ".", "Surface", ".", "from_nodes", "(", "np", ".", "asfortranarray", "(", "[", "[", "0.0", ",", "4.5", ",", "9.0", ",", "0.0", ",", "4.5", ",", "0.0", "]", ",", "[", "0.0", ",", "0.0", ",", "2.25", ",", "1.25", ",", "2.375", ",", "2.5", "]", ",", "]", ")", ")", "surface2", "=", "bezier", ".", "Surface", ".", "from_nodes", "(", "np", ".", "asfortranarray", "(", "[", "[", "11.25", ",", "9.0", ",", "2.75", ",", "8.125", ",", "3.875", ",", "5.0", "]", ",", "[", "0.0", ",", "4.5", ",", "1.0", ",", "-", "0.75", ",", "-", "0.25", ",", "-", "1.5", "]", ",", "]", ")", ")", "figure", ",", "(", "ax1", ",", "ax2", ")", "=", "plt", ".", "subplots", "(", "2", ",", "1", ")", "classify_help", "(", "s", ",", "curve1a", ",", "surface1", ",", "curve2", ",", "surface2", ",", "None", ",", "ax", "=", "ax1", ")", "surface1", ".", "_nodes", "=", "np", ".", "asfortranarray", "(", "surface1", ".", "_nodes", "[", ":", ",", "(", "2", ",", "4", ",", "5", ",", "1", ",", "3", ",", "0", ")", "]", ")", "surface1", ".", "_edges", "=", "None", "classify_help", "(", "0.0", ",", "curve1b", ",", "surface1", ",", "curve2", ",", "surface2", ",", "0", ",", "ax", "=", "ax2", ")", "for", "ax", "in", "(", "ax1", ",", "ax2", ")", ":", "ax", ".", "set_xlim", "(", "-", "0.125", ",", "11.5", ")", "ax", ".", "set_ylim", "(", "-", "0.125", ",", "2.625", ")", "plt", ".", "setp", "(", "ax1", ".", "get_xticklabels", "(", ")", ",", "visible", "=", "False", ")", "figure", ".", "tight_layout", "(", "h_pad", "=", "-", "5.0", ")", "save_image", "(", "figure", ",", "\"classify_intersection7.png\"", ")" ]
Image for :func:`._surface_helpers.classify_intersection` docstring.
[ "Image", "for", ":", "func", ":", ".", "_surface_helpers", ".", "classify_intersection", "docstring", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/docs/make_images.py#L1002-L1033
dhermes/bezier
docs/make_images.py
get_curvature
def get_curvature(nodes, s, tangent_vec, curvature): """Image for :func:`get_curvature` docstring.""" if NO_IMAGES: return curve = bezier.Curve.from_nodes(nodes) # Find the center of the circle along the direction # perpendicular to the tangent vector (90 degree left turn). radius_dir = np.asfortranarray([[-tangent_vec[1, 0]], [tangent_vec[0, 0]]]) radius_dir /= np.linalg.norm(radius_dir, ord=2) point = curve.evaluate(s) circle_center = point + radius_dir / curvature # Add the curve. ax = curve.plot(256) # Add the circle. circle_center = circle_center.ravel(order="F") circle = plt.Circle(circle_center, 1.0 / abs(curvature), alpha=0.25) ax.add_artist(circle) # Add the point. ax.plot( point[0, :], point[1, :], color="black", marker="o", linestyle="None" ) ax.axis("scaled") ax.set_xlim(-0.0625, 1.0625) ax.set_ylim(-0.0625, 0.625) save_image(ax.figure, "get_curvature.png")
python
def get_curvature(nodes, s, tangent_vec, curvature): """Image for :func:`get_curvature` docstring.""" if NO_IMAGES: return curve = bezier.Curve.from_nodes(nodes) # Find the center of the circle along the direction # perpendicular to the tangent vector (90 degree left turn). radius_dir = np.asfortranarray([[-tangent_vec[1, 0]], [tangent_vec[0, 0]]]) radius_dir /= np.linalg.norm(radius_dir, ord=2) point = curve.evaluate(s) circle_center = point + radius_dir / curvature # Add the curve. ax = curve.plot(256) # Add the circle. circle_center = circle_center.ravel(order="F") circle = plt.Circle(circle_center, 1.0 / abs(curvature), alpha=0.25) ax.add_artist(circle) # Add the point. ax.plot( point[0, :], point[1, :], color="black", marker="o", linestyle="None" ) ax.axis("scaled") ax.set_xlim(-0.0625, 1.0625) ax.set_ylim(-0.0625, 0.625) save_image(ax.figure, "get_curvature.png")
[ "def", "get_curvature", "(", "nodes", ",", "s", ",", "tangent_vec", ",", "curvature", ")", ":", "if", "NO_IMAGES", ":", "return", "curve", "=", "bezier", ".", "Curve", ".", "from_nodes", "(", "nodes", ")", "# Find the center of the circle along the direction", "# perpendicular to the tangent vector (90 degree left turn).", "radius_dir", "=", "np", ".", "asfortranarray", "(", "[", "[", "-", "tangent_vec", "[", "1", ",", "0", "]", "]", ",", "[", "tangent_vec", "[", "0", ",", "0", "]", "]", "]", ")", "radius_dir", "/=", "np", ".", "linalg", ".", "norm", "(", "radius_dir", ",", "ord", "=", "2", ")", "point", "=", "curve", ".", "evaluate", "(", "s", ")", "circle_center", "=", "point", "+", "radius_dir", "/", "curvature", "# Add the curve.", "ax", "=", "curve", ".", "plot", "(", "256", ")", "# Add the circle.", "circle_center", "=", "circle_center", ".", "ravel", "(", "order", "=", "\"F\"", ")", "circle", "=", "plt", ".", "Circle", "(", "circle_center", ",", "1.0", "/", "abs", "(", "curvature", ")", ",", "alpha", "=", "0.25", ")", "ax", ".", "add_artist", "(", "circle", ")", "# Add the point.", "ax", ".", "plot", "(", "point", "[", "0", ",", ":", "]", ",", "point", "[", "1", ",", ":", "]", ",", "color", "=", "\"black\"", ",", "marker", "=", "\"o\"", ",", "linestyle", "=", "\"None\"", ")", "ax", ".", "axis", "(", "\"scaled\"", ")", "ax", ".", "set_xlim", "(", "-", "0.0625", ",", "1.0625", ")", "ax", ".", "set_ylim", "(", "-", "0.0625", ",", "0.625", ")", "save_image", "(", "ax", ".", "figure", ",", "\"get_curvature.png\"", ")" ]
Image for :func:`get_curvature` docstring.
[ "Image", "for", ":", "func", ":", "get_curvature", "docstring", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/docs/make_images.py#L1036-L1061
dhermes/bezier
docs/make_images.py
curve_locate
def curve_locate(curve, point1, point2, point3): """Image for :meth`.Curve.locate` docstring.""" if NO_IMAGES: return ax = curve.plot(256) points = np.hstack([point1, point2, point3]) ax.plot( points[0, :], points[1, :], color="black", linestyle="None", marker="o" ) ax.axis("scaled") ax.set_xlim(-0.8125, 0.0625) ax.set_ylim(0.75, 2.0625) save_image(ax.figure, "curve_locate.png")
python
def curve_locate(curve, point1, point2, point3): """Image for :meth`.Curve.locate` docstring.""" if NO_IMAGES: return ax = curve.plot(256) points = np.hstack([point1, point2, point3]) ax.plot( points[0, :], points[1, :], color="black", linestyle="None", marker="o" ) ax.axis("scaled") ax.set_xlim(-0.8125, 0.0625) ax.set_ylim(0.75, 2.0625) save_image(ax.figure, "curve_locate.png")
[ "def", "curve_locate", "(", "curve", ",", "point1", ",", "point2", ",", "point3", ")", ":", "if", "NO_IMAGES", ":", "return", "ax", "=", "curve", ".", "plot", "(", "256", ")", "points", "=", "np", ".", "hstack", "(", "[", "point1", ",", "point2", ",", "point3", "]", ")", "ax", ".", "plot", "(", "points", "[", "0", ",", ":", "]", ",", "points", "[", "1", ",", ":", "]", ",", "color", "=", "\"black\"", ",", "linestyle", "=", "\"None\"", ",", "marker", "=", "\"o\"", ")", "ax", ".", "axis", "(", "\"scaled\"", ")", "ax", ".", "set_xlim", "(", "-", "0.8125", ",", "0.0625", ")", "ax", ".", "set_ylim", "(", "0.75", ",", "2.0625", ")", "save_image", "(", "ax", ".", "figure", ",", "\"curve_locate.png\"", ")" ]
Image for :meth`.Curve.locate` docstring.
[ "Image", "for", ":", "meth", ".", "Curve", ".", "locate", "docstring", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/docs/make_images.py#L1064-L1077
dhermes/bezier
docs/make_images.py
newton_refine_curve
def newton_refine_curve(curve, point, s, new_s): """Image for :func:`._curve_helpers.newton_refine` docstring.""" if NO_IMAGES: return ax = curve.plot(256) ax.plot(point[0, :], point[1, :], marker="H") wrong_points = curve.evaluate_multi(np.asfortranarray([s, new_s])) ax.plot( wrong_points[0, [0]], wrong_points[1, [0]], color="black", linestyle="None", marker="o", ) ax.plot( wrong_points[0, [1]], wrong_points[1, [1]], color="black", linestyle="None", marker="o", markeredgewidth=1, markerfacecolor="None", ) # Set the axis bounds / scaling. ax.axis("scaled") ax.set_xlim(-0.125, 3.125) ax.set_ylim(-0.125, 1.375) save_image(ax.figure, "newton_refine_curve.png")
python
def newton_refine_curve(curve, point, s, new_s): """Image for :func:`._curve_helpers.newton_refine` docstring.""" if NO_IMAGES: return ax = curve.plot(256) ax.plot(point[0, :], point[1, :], marker="H") wrong_points = curve.evaluate_multi(np.asfortranarray([s, new_s])) ax.plot( wrong_points[0, [0]], wrong_points[1, [0]], color="black", linestyle="None", marker="o", ) ax.plot( wrong_points[0, [1]], wrong_points[1, [1]], color="black", linestyle="None", marker="o", markeredgewidth=1, markerfacecolor="None", ) # Set the axis bounds / scaling. ax.axis("scaled") ax.set_xlim(-0.125, 3.125) ax.set_ylim(-0.125, 1.375) save_image(ax.figure, "newton_refine_curve.png")
[ "def", "newton_refine_curve", "(", "curve", ",", "point", ",", "s", ",", "new_s", ")", ":", "if", "NO_IMAGES", ":", "return", "ax", "=", "curve", ".", "plot", "(", "256", ")", "ax", ".", "plot", "(", "point", "[", "0", ",", ":", "]", ",", "point", "[", "1", ",", ":", "]", ",", "marker", "=", "\"H\"", ")", "wrong_points", "=", "curve", ".", "evaluate_multi", "(", "np", ".", "asfortranarray", "(", "[", "s", ",", "new_s", "]", ")", ")", "ax", ".", "plot", "(", "wrong_points", "[", "0", ",", "[", "0", "]", "]", ",", "wrong_points", "[", "1", ",", "[", "0", "]", "]", ",", "color", "=", "\"black\"", ",", "linestyle", "=", "\"None\"", ",", "marker", "=", "\"o\"", ",", ")", "ax", ".", "plot", "(", "wrong_points", "[", "0", ",", "[", "1", "]", "]", ",", "wrong_points", "[", "1", ",", "[", "1", "]", "]", ",", "color", "=", "\"black\"", ",", "linestyle", "=", "\"None\"", ",", "marker", "=", "\"o\"", ",", "markeredgewidth", "=", "1", ",", "markerfacecolor", "=", "\"None\"", ",", ")", "# Set the axis bounds / scaling.", "ax", ".", "axis", "(", "\"scaled\"", ")", "ax", ".", "set_xlim", "(", "-", "0.125", ",", "3.125", ")", "ax", ".", "set_ylim", "(", "-", "0.125", ",", "1.375", ")", "save_image", "(", "ax", ".", "figure", ",", "\"newton_refine_curve.png\"", ")" ]
Image for :func:`._curve_helpers.newton_refine` docstring.
[ "Image", "for", ":", "func", ":", ".", "_curve_helpers", ".", "newton_refine", "docstring", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/docs/make_images.py#L1080-L1108
dhermes/bezier
docs/make_images.py
newton_refine_curve_cusp
def newton_refine_curve_cusp(curve, s_vals): """Image for :func:`._curve_helpers.newton_refine` docstring.""" if NO_IMAGES: return ax = curve.plot(256) ax.lines[-1].zorder = 1 points = curve.evaluate_multi(np.asfortranarray(s_vals)) colors = seaborn.dark_palette("blue", 6) ax.scatter( points[0, :], points[1, :], c=colors, s=20, alpha=0.75, zorder=2 ) # Set the axis bounds / scaling. ax.axis("scaled") ax.set_xlim(-0.125, 6.125) ax.set_ylim(-3.125, 3.125) save_image(ax.figure, "newton_refine_curve_cusp.png")
python
def newton_refine_curve_cusp(curve, s_vals): """Image for :func:`._curve_helpers.newton_refine` docstring.""" if NO_IMAGES: return ax = curve.plot(256) ax.lines[-1].zorder = 1 points = curve.evaluate_multi(np.asfortranarray(s_vals)) colors = seaborn.dark_palette("blue", 6) ax.scatter( points[0, :], points[1, :], c=colors, s=20, alpha=0.75, zorder=2 ) # Set the axis bounds / scaling. ax.axis("scaled") ax.set_xlim(-0.125, 6.125) ax.set_ylim(-3.125, 3.125) save_image(ax.figure, "newton_refine_curve_cusp.png")
[ "def", "newton_refine_curve_cusp", "(", "curve", ",", "s_vals", ")", ":", "if", "NO_IMAGES", ":", "return", "ax", "=", "curve", ".", "plot", "(", "256", ")", "ax", ".", "lines", "[", "-", "1", "]", ".", "zorder", "=", "1", "points", "=", "curve", ".", "evaluate_multi", "(", "np", ".", "asfortranarray", "(", "s_vals", ")", ")", "colors", "=", "seaborn", ".", "dark_palette", "(", "\"blue\"", ",", "6", ")", "ax", ".", "scatter", "(", "points", "[", "0", ",", ":", "]", ",", "points", "[", "1", ",", ":", "]", ",", "c", "=", "colors", ",", "s", "=", "20", ",", "alpha", "=", "0.75", ",", "zorder", "=", "2", ")", "# Set the axis bounds / scaling.", "ax", ".", "axis", "(", "\"scaled\"", ")", "ax", ".", "set_xlim", "(", "-", "0.125", ",", "6.125", ")", "ax", ".", "set_ylim", "(", "-", "3.125", ",", "3.125", ")", "save_image", "(", "ax", ".", "figure", ",", "\"newton_refine_curve_cusp.png\"", ")" ]
Image for :func:`._curve_helpers.newton_refine` docstring.
[ "Image", "for", ":", "func", ":", ".", "_curve_helpers", ".", "newton_refine", "docstring", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/docs/make_images.py#L1111-L1127
dhermes/bezier
docs/make_images.py
classify_intersection8
def classify_intersection8(s, curve1, surface1, curve2, surface2): """Image for :func:`._surface_helpers.classify_intersection` docstring.""" if NO_IMAGES: return ax = classify_help(s, curve1, surface1, curve2, surface2, None) ax.set_xlim(-1.125, 1.125) ax.set_ylim(-0.125, 1.125) save_image(ax.figure, "classify_intersection8.png")
python
def classify_intersection8(s, curve1, surface1, curve2, surface2): """Image for :func:`._surface_helpers.classify_intersection` docstring.""" if NO_IMAGES: return ax = classify_help(s, curve1, surface1, curve2, surface2, None) ax.set_xlim(-1.125, 1.125) ax.set_ylim(-0.125, 1.125) save_image(ax.figure, "classify_intersection8.png")
[ "def", "classify_intersection8", "(", "s", ",", "curve1", ",", "surface1", ",", "curve2", ",", "surface2", ")", ":", "if", "NO_IMAGES", ":", "return", "ax", "=", "classify_help", "(", "s", ",", "curve1", ",", "surface1", ",", "curve2", ",", "surface2", ",", "None", ")", "ax", ".", "set_xlim", "(", "-", "1.125", ",", "1.125", ")", "ax", ".", "set_ylim", "(", "-", "0.125", ",", "1.125", ")", "save_image", "(", "ax", ".", "figure", ",", "\"classify_intersection8.png\"", ")" ]
Image for :func:`._surface_helpers.classify_intersection` docstring.
[ "Image", "for", ":", "func", ":", ".", "_surface_helpers", ".", "classify_intersection", "docstring", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/docs/make_images.py#L1130-L1138
dhermes/bezier
docs/make_images.py
_edges_classify_intersection9
def _edges_classify_intersection9(): """The edges for the curved polygon intersection used below. Helper for :func:`classify_intersection9`. """ edges1 = ( bezier.Curve.from_nodes( np.asfortranarray([[32.0, 30.0], [20.0, 25.0]]) ), bezier.Curve.from_nodes( np.asfortranarray([[30.0, 25.0, 20.0], [25.0, 20.0, 20.0]]) ), bezier.Curve.from_nodes( np.asfortranarray([[20.0, 25.0, 30.0], [20.0, 20.0, 15.0]]) ), bezier.Curve.from_nodes( np.asfortranarray([[30.0, 32.0], [15.0, 20.0]]) ), ) edges2 = ( bezier.Curve.from_nodes( np.asfortranarray([[8.0, 10.0], [20.0, 15.0]]) ), bezier.Curve.from_nodes( np.asfortranarray([[10.0, 15.0, 20.0], [15.0, 20.0, 20.0]]) ), bezier.Curve.from_nodes( np.asfortranarray([[20.0, 15.0, 10.0], [20.0, 20.0, 25.0]]) ), bezier.Curve.from_nodes( np.asfortranarray([[10.0, 8.0], [25.0, 20.0]]) ), ) return edges1, edges2
python
def _edges_classify_intersection9(): """The edges for the curved polygon intersection used below. Helper for :func:`classify_intersection9`. """ edges1 = ( bezier.Curve.from_nodes( np.asfortranarray([[32.0, 30.0], [20.0, 25.0]]) ), bezier.Curve.from_nodes( np.asfortranarray([[30.0, 25.0, 20.0], [25.0, 20.0, 20.0]]) ), bezier.Curve.from_nodes( np.asfortranarray([[20.0, 25.0, 30.0], [20.0, 20.0, 15.0]]) ), bezier.Curve.from_nodes( np.asfortranarray([[30.0, 32.0], [15.0, 20.0]]) ), ) edges2 = ( bezier.Curve.from_nodes( np.asfortranarray([[8.0, 10.0], [20.0, 15.0]]) ), bezier.Curve.from_nodes( np.asfortranarray([[10.0, 15.0, 20.0], [15.0, 20.0, 20.0]]) ), bezier.Curve.from_nodes( np.asfortranarray([[20.0, 15.0, 10.0], [20.0, 20.0, 25.0]]) ), bezier.Curve.from_nodes( np.asfortranarray([[10.0, 8.0], [25.0, 20.0]]) ), ) return edges1, edges2
[ "def", "_edges_classify_intersection9", "(", ")", ":", "edges1", "=", "(", "bezier", ".", "Curve", ".", "from_nodes", "(", "np", ".", "asfortranarray", "(", "[", "[", "32.0", ",", "30.0", "]", ",", "[", "20.0", ",", "25.0", "]", "]", ")", ")", ",", "bezier", ".", "Curve", ".", "from_nodes", "(", "np", ".", "asfortranarray", "(", "[", "[", "30.0", ",", "25.0", ",", "20.0", "]", ",", "[", "25.0", ",", "20.0", ",", "20.0", "]", "]", ")", ")", ",", "bezier", ".", "Curve", ".", "from_nodes", "(", "np", ".", "asfortranarray", "(", "[", "[", "20.0", ",", "25.0", ",", "30.0", "]", ",", "[", "20.0", ",", "20.0", ",", "15.0", "]", "]", ")", ")", ",", "bezier", ".", "Curve", ".", "from_nodes", "(", "np", ".", "asfortranarray", "(", "[", "[", "30.0", ",", "32.0", "]", ",", "[", "15.0", ",", "20.0", "]", "]", ")", ")", ",", ")", "edges2", "=", "(", "bezier", ".", "Curve", ".", "from_nodes", "(", "np", ".", "asfortranarray", "(", "[", "[", "8.0", ",", "10.0", "]", ",", "[", "20.0", ",", "15.0", "]", "]", ")", ")", ",", "bezier", ".", "Curve", ".", "from_nodes", "(", "np", ".", "asfortranarray", "(", "[", "[", "10.0", ",", "15.0", ",", "20.0", "]", ",", "[", "15.0", ",", "20.0", ",", "20.0", "]", "]", ")", ")", ",", "bezier", ".", "Curve", ".", "from_nodes", "(", "np", ".", "asfortranarray", "(", "[", "[", "20.0", ",", "15.0", ",", "10.0", "]", ",", "[", "20.0", ",", "20.0", ",", "25.0", "]", "]", ")", ")", ",", "bezier", ".", "Curve", ".", "from_nodes", "(", "np", ".", "asfortranarray", "(", "[", "[", "10.0", ",", "8.0", "]", ",", "[", "25.0", ",", "20.0", "]", "]", ")", ")", ",", ")", "return", "edges1", ",", "edges2" ]
The edges for the curved polygon intersection used below. Helper for :func:`classify_intersection9`.
[ "The", "edges", "for", "the", "curved", "polygon", "intersection", "used", "below", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/docs/make_images.py#L1141-L1174
dhermes/bezier
docs/make_images.py
classify_intersection9
def classify_intersection9(s, curve1, curve2): """Image for :func:`._surface_helpers.classify_intersection` docstring.""" if NO_IMAGES: return surface1 = bezier.Surface.from_nodes( np.asfortranarray( [ [0.0, 20.0, 40.0, 10.0, 30.0, 20.0], [0.0, 40.0, 0.0, 25.0, 25.0, 50.0], ] ) ) surface2 = bezier.Surface.from_nodes( np.asfortranarray( [ [40.0, 20.0, 0.0, 30.0, 10.0, 20.0], [40.0, 0.0, 40.0, 15.0, 15.0, -10.0], ] ) ) figure, (ax1, ax2) = plt.subplots(1, 2) classify_help(s, curve1, surface1, curve2, surface2, 0, ax=ax1) classify_help(s, curve1, surface1, curve2, surface2, 1, ax=ax2) # Remove the alpha from the color color1 = ax1.patches[0].get_facecolor()[:3] color2 = ax1.patches[1].get_facecolor()[:3] # Now add the "degenerate" intersection polygons. cp_edges1, cp_edges2 = _edges_classify_intersection9() curved_polygon1 = bezier.CurvedPolygon(*cp_edges1) curved_polygon1.plot(256, ax=ax1) curved_polygon2 = bezier.CurvedPolygon(*cp_edges2) curved_polygon2.plot(256, ax=ax2) (int_x,), (int_y,) = curve1.evaluate(s) ax1.plot([int_x], [int_y], color=color1, linestyle="None", marker="o") ax2.plot([int_x], [int_y], color=color2, linestyle="None", marker="o") for ax in (ax1, ax2): ax.axis("scaled") ax.set_xlim(-2.0, 42.0) ax.set_ylim(-12.0, 52.0) plt.setp(ax2.get_yticklabels(), visible=False) figure.tight_layout(w_pad=1.0) save_image(figure, "classify_intersection9.png")
python
def classify_intersection9(s, curve1, curve2): """Image for :func:`._surface_helpers.classify_intersection` docstring.""" if NO_IMAGES: return surface1 = bezier.Surface.from_nodes( np.asfortranarray( [ [0.0, 20.0, 40.0, 10.0, 30.0, 20.0], [0.0, 40.0, 0.0, 25.0, 25.0, 50.0], ] ) ) surface2 = bezier.Surface.from_nodes( np.asfortranarray( [ [40.0, 20.0, 0.0, 30.0, 10.0, 20.0], [40.0, 0.0, 40.0, 15.0, 15.0, -10.0], ] ) ) figure, (ax1, ax2) = plt.subplots(1, 2) classify_help(s, curve1, surface1, curve2, surface2, 0, ax=ax1) classify_help(s, curve1, surface1, curve2, surface2, 1, ax=ax2) # Remove the alpha from the color color1 = ax1.patches[0].get_facecolor()[:3] color2 = ax1.patches[1].get_facecolor()[:3] # Now add the "degenerate" intersection polygons. cp_edges1, cp_edges2 = _edges_classify_intersection9() curved_polygon1 = bezier.CurvedPolygon(*cp_edges1) curved_polygon1.plot(256, ax=ax1) curved_polygon2 = bezier.CurvedPolygon(*cp_edges2) curved_polygon2.plot(256, ax=ax2) (int_x,), (int_y,) = curve1.evaluate(s) ax1.plot([int_x], [int_y], color=color1, linestyle="None", marker="o") ax2.plot([int_x], [int_y], color=color2, linestyle="None", marker="o") for ax in (ax1, ax2): ax.axis("scaled") ax.set_xlim(-2.0, 42.0) ax.set_ylim(-12.0, 52.0) plt.setp(ax2.get_yticklabels(), visible=False) figure.tight_layout(w_pad=1.0) save_image(figure, "classify_intersection9.png")
[ "def", "classify_intersection9", "(", "s", ",", "curve1", ",", "curve2", ")", ":", "if", "NO_IMAGES", ":", "return", "surface1", "=", "bezier", ".", "Surface", ".", "from_nodes", "(", "np", ".", "asfortranarray", "(", "[", "[", "0.0", ",", "20.0", ",", "40.0", ",", "10.0", ",", "30.0", ",", "20.0", "]", ",", "[", "0.0", ",", "40.0", ",", "0.0", ",", "25.0", ",", "25.0", ",", "50.0", "]", ",", "]", ")", ")", "surface2", "=", "bezier", ".", "Surface", ".", "from_nodes", "(", "np", ".", "asfortranarray", "(", "[", "[", "40.0", ",", "20.0", ",", "0.0", ",", "30.0", ",", "10.0", ",", "20.0", "]", ",", "[", "40.0", ",", "0.0", ",", "40.0", ",", "15.0", ",", "15.0", ",", "-", "10.0", "]", ",", "]", ")", ")", "figure", ",", "(", "ax1", ",", "ax2", ")", "=", "plt", ".", "subplots", "(", "1", ",", "2", ")", "classify_help", "(", "s", ",", "curve1", ",", "surface1", ",", "curve2", ",", "surface2", ",", "0", ",", "ax", "=", "ax1", ")", "classify_help", "(", "s", ",", "curve1", ",", "surface1", ",", "curve2", ",", "surface2", ",", "1", ",", "ax", "=", "ax2", ")", "# Remove the alpha from the color", "color1", "=", "ax1", ".", "patches", "[", "0", "]", ".", "get_facecolor", "(", ")", "[", ":", "3", "]", "color2", "=", "ax1", ".", "patches", "[", "1", "]", ".", "get_facecolor", "(", ")", "[", ":", "3", "]", "# Now add the \"degenerate\" intersection polygons.", "cp_edges1", ",", "cp_edges2", "=", "_edges_classify_intersection9", "(", ")", "curved_polygon1", "=", "bezier", ".", "CurvedPolygon", "(", "*", "cp_edges1", ")", "curved_polygon1", ".", "plot", "(", "256", ",", "ax", "=", "ax1", ")", "curved_polygon2", "=", "bezier", ".", "CurvedPolygon", "(", "*", "cp_edges2", ")", "curved_polygon2", ".", "plot", "(", "256", ",", "ax", "=", "ax2", ")", "(", "int_x", ",", ")", ",", "(", "int_y", ",", ")", "=", "curve1", ".", "evaluate", "(", "s", ")", "ax1", ".", "plot", "(", "[", "int_x", "]", ",", "[", "int_y", "]", ",", "color", "=", "color1", ",", "linestyle", "=", "\"None\"", ",", "marker", "=", "\"o\"", ")", "ax2", ".", "plot", "(", "[", "int_x", "]", ",", "[", "int_y", "]", ",", "color", "=", "color2", ",", "linestyle", "=", "\"None\"", ",", "marker", "=", "\"o\"", ")", "for", "ax", "in", "(", "ax1", ",", "ax2", ")", ":", "ax", ".", "axis", "(", "\"scaled\"", ")", "ax", ".", "set_xlim", "(", "-", "2.0", ",", "42.0", ")", "ax", ".", "set_ylim", "(", "-", "12.0", ",", "52.0", ")", "plt", ".", "setp", "(", "ax2", ".", "get_yticklabels", "(", ")", ",", "visible", "=", "False", ")", "figure", ".", "tight_layout", "(", "w_pad", "=", "1.0", ")", "save_image", "(", "figure", ",", "\"classify_intersection9.png\"", ")" ]
Image for :func:`._surface_helpers.classify_intersection` docstring.
[ "Image", "for", ":", "func", ":", ".", "_surface_helpers", ".", "classify_intersection", "docstring", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/docs/make_images.py#L1177-L1219
dhermes/bezier
docs/make_images.py
curve_elevate
def curve_elevate(curve, elevated): """Image for :meth:`.curve.Curve.elevate` docstring.""" if NO_IMAGES: return figure, (ax1, ax2) = plt.subplots(1, 2) curve.plot(256, ax=ax1) color = ax1.lines[-1].get_color() add_patch(ax1, curve._nodes, color) elevated.plot(256, ax=ax2) color = ax2.lines[-1].get_color() add_patch(ax2, elevated._nodes, color) ax1.axis("scaled") ax2.axis("scaled") _plot_helpers.add_plot_boundary(ax1) ax2.set_xlim(*ax1.get_xlim()) ax2.set_ylim(*ax1.get_ylim()) save_image(figure, "curve_elevate.png")
python
def curve_elevate(curve, elevated): """Image for :meth:`.curve.Curve.elevate` docstring.""" if NO_IMAGES: return figure, (ax1, ax2) = plt.subplots(1, 2) curve.plot(256, ax=ax1) color = ax1.lines[-1].get_color() add_patch(ax1, curve._nodes, color) elevated.plot(256, ax=ax2) color = ax2.lines[-1].get_color() add_patch(ax2, elevated._nodes, color) ax1.axis("scaled") ax2.axis("scaled") _plot_helpers.add_plot_boundary(ax1) ax2.set_xlim(*ax1.get_xlim()) ax2.set_ylim(*ax1.get_ylim()) save_image(figure, "curve_elevate.png")
[ "def", "curve_elevate", "(", "curve", ",", "elevated", ")", ":", "if", "NO_IMAGES", ":", "return", "figure", ",", "(", "ax1", ",", "ax2", ")", "=", "plt", ".", "subplots", "(", "1", ",", "2", ")", "curve", ".", "plot", "(", "256", ",", "ax", "=", "ax1", ")", "color", "=", "ax1", ".", "lines", "[", "-", "1", "]", ".", "get_color", "(", ")", "add_patch", "(", "ax1", ",", "curve", ".", "_nodes", ",", "color", ")", "elevated", ".", "plot", "(", "256", ",", "ax", "=", "ax2", ")", "color", "=", "ax2", ".", "lines", "[", "-", "1", "]", ".", "get_color", "(", ")", "add_patch", "(", "ax2", ",", "elevated", ".", "_nodes", ",", "color", ")", "ax1", ".", "axis", "(", "\"scaled\"", ")", "ax2", ".", "axis", "(", "\"scaled\"", ")", "_plot_helpers", ".", "add_plot_boundary", "(", "ax1", ")", "ax2", ".", "set_xlim", "(", "*", "ax1", ".", "get_xlim", "(", ")", ")", "ax2", ".", "set_ylim", "(", "*", "ax1", ".", "get_ylim", "(", ")", ")", "save_image", "(", "figure", ",", "\"curve_elevate.png\"", ")" ]
Image for :meth:`.curve.Curve.elevate` docstring.
[ "Image", "for", ":", "meth", ":", ".", "curve", ".", "Curve", ".", "elevate", "docstring", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/docs/make_images.py#L1222-L1239
dhermes/bezier
docs/make_images.py
unit_triangle
def unit_triangle(): """Image for :class:`.surface.Surface` docstring.""" if NO_IMAGES: return nodes = np.asfortranarray([[0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]) surface = bezier.Surface(nodes, degree=1) ax = surface.plot(256) ax.axis("scaled") _plot_helpers.add_plot_boundary(ax) save_image(ax.figure, "unit_triangle.png")
python
def unit_triangle(): """Image for :class:`.surface.Surface` docstring.""" if NO_IMAGES: return nodes = np.asfortranarray([[0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]) surface = bezier.Surface(nodes, degree=1) ax = surface.plot(256) ax.axis("scaled") _plot_helpers.add_plot_boundary(ax) save_image(ax.figure, "unit_triangle.png")
[ "def", "unit_triangle", "(", ")", ":", "if", "NO_IMAGES", ":", "return", "nodes", "=", "np", ".", "asfortranarray", "(", "[", "[", "0.0", ",", "1.0", ",", "0.0", "]", ",", "[", "0.0", ",", "0.0", ",", "1.0", "]", "]", ")", "surface", "=", "bezier", ".", "Surface", "(", "nodes", ",", "degree", "=", "1", ")", "ax", "=", "surface", ".", "plot", "(", "256", ")", "ax", ".", "axis", "(", "\"scaled\"", ")", "_plot_helpers", ".", "add_plot_boundary", "(", "ax", ")", "save_image", "(", "ax", ".", "figure", ",", "\"unit_triangle.png\"", ")" ]
Image for :class:`.surface.Surface` docstring.
[ "Image", "for", ":", "class", ":", ".", "surface", ".", "Surface", "docstring", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/docs/make_images.py#L1264-L1274
dhermes/bezier
docs/make_images.py
curve_reduce
def curve_reduce(curve, reduced): """Image for :meth:`.curve.Curve.reduce` docstring.""" if NO_IMAGES: return figure, (ax1, ax2) = plt.subplots(1, 2, sharex=True, sharey=True) curve.plot(256, ax=ax1) color = ax1.lines[-1].get_color() add_patch(ax1, curve._nodes, color) reduced.plot(256, ax=ax2) color = ax2.lines[-1].get_color() add_patch(ax2, reduced._nodes, color) ax1.axis("scaled") ax2.axis("scaled") _plot_helpers.add_plot_boundary(ax2) save_image(figure, "curve_reduce.png")
python
def curve_reduce(curve, reduced): """Image for :meth:`.curve.Curve.reduce` docstring.""" if NO_IMAGES: return figure, (ax1, ax2) = plt.subplots(1, 2, sharex=True, sharey=True) curve.plot(256, ax=ax1) color = ax1.lines[-1].get_color() add_patch(ax1, curve._nodes, color) reduced.plot(256, ax=ax2) color = ax2.lines[-1].get_color() add_patch(ax2, reduced._nodes, color) ax1.axis("scaled") ax2.axis("scaled") _plot_helpers.add_plot_boundary(ax2) save_image(figure, "curve_reduce.png")
[ "def", "curve_reduce", "(", "curve", ",", "reduced", ")", ":", "if", "NO_IMAGES", ":", "return", "figure", ",", "(", "ax1", ",", "ax2", ")", "=", "plt", ".", "subplots", "(", "1", ",", "2", ",", "sharex", "=", "True", ",", "sharey", "=", "True", ")", "curve", ".", "plot", "(", "256", ",", "ax", "=", "ax1", ")", "color", "=", "ax1", ".", "lines", "[", "-", "1", "]", ".", "get_color", "(", ")", "add_patch", "(", "ax1", ",", "curve", ".", "_nodes", ",", "color", ")", "reduced", ".", "plot", "(", "256", ",", "ax", "=", "ax2", ")", "color", "=", "ax2", ".", "lines", "[", "-", "1", "]", ".", "get_color", "(", ")", "add_patch", "(", "ax2", ",", "reduced", ".", "_nodes", ",", "color", ")", "ax1", ".", "axis", "(", "\"scaled\"", ")", "ax2", ".", "axis", "(", "\"scaled\"", ")", "_plot_helpers", ".", "add_plot_boundary", "(", "ax2", ")", "save_image", "(", "figure", ",", "\"curve_reduce.png\"", ")" ]
Image for :meth:`.curve.Curve.reduce` docstring.
[ "Image", "for", ":", "meth", ":", ".", "curve", ".", "Curve", ".", "reduce", "docstring", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/docs/make_images.py#L1277-L1292
dhermes/bezier
docs/make_images.py
curve_reduce_approx
def curve_reduce_approx(curve, reduced): """Image for :meth:`.curve.Curve.reduce` docstring.""" if NO_IMAGES: return ax = curve.plot(256) color = ax.lines[-1].get_color() add_patch(ax, curve._nodes, color, alpha=0.25, node_color=color) reduced.plot(256, ax=ax) color = ax.lines[-1].get_color() add_patch(ax, reduced._nodes, color, alpha=0.25, node_color=color) ax.axis("scaled") _plot_helpers.add_plot_boundary(ax) save_image(ax.figure, "curve_reduce_approx.png")
python
def curve_reduce_approx(curve, reduced): """Image for :meth:`.curve.Curve.reduce` docstring.""" if NO_IMAGES: return ax = curve.plot(256) color = ax.lines[-1].get_color() add_patch(ax, curve._nodes, color, alpha=0.25, node_color=color) reduced.plot(256, ax=ax) color = ax.lines[-1].get_color() add_patch(ax, reduced._nodes, color, alpha=0.25, node_color=color) ax.axis("scaled") _plot_helpers.add_plot_boundary(ax) save_image(ax.figure, "curve_reduce_approx.png")
[ "def", "curve_reduce_approx", "(", "curve", ",", "reduced", ")", ":", "if", "NO_IMAGES", ":", "return", "ax", "=", "curve", ".", "plot", "(", "256", ")", "color", "=", "ax", ".", "lines", "[", "-", "1", "]", ".", "get_color", "(", ")", "add_patch", "(", "ax", ",", "curve", ".", "_nodes", ",", "color", ",", "alpha", "=", "0.25", ",", "node_color", "=", "color", ")", "reduced", ".", "plot", "(", "256", ",", "ax", "=", "ax", ")", "color", "=", "ax", ".", "lines", "[", "-", "1", "]", ".", "get_color", "(", ")", "add_patch", "(", "ax", ",", "reduced", ".", "_nodes", ",", "color", ",", "alpha", "=", "0.25", ",", "node_color", "=", "color", ")", "ax", ".", "axis", "(", "\"scaled\"", ")", "_plot_helpers", ".", "add_plot_boundary", "(", "ax", ")", "save_image", "(", "ax", ".", "figure", ",", "\"curve_reduce_approx.png\"", ")" ]
Image for :meth:`.curve.Curve.reduce` docstring.
[ "Image", "for", ":", "meth", ":", ".", "curve", ".", "Curve", ".", "reduce", "docstring", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/docs/make_images.py#L1295-L1308
dhermes/bezier
src/bezier/_surface_intersection.py
newton_refine_solve
def newton_refine_solve(jac_both, x_val, surf_x, y_val, surf_y): r"""Helper for :func:`newton_refine`. We have a system: .. code-block:: rest [A C][ds] = [E] [B D][dt] [F] This is not a typo, ``A->B->C->D`` matches the data in ``jac_both``. We solve directly rather than using a linear algebra utility: .. code-block:: rest ds = (D E - C F) / (A D - B C) dt = (A F - B E) / (A D - B C) Args: jac_both (numpy.ndarray): A ``4 x 1`` matrix of entries in a Jacobian. x_val (float): An ``x``-value we are trying to reach. surf_x (float): The actual ``x``-value we are currently at. y_val (float): An ``y``-value we are trying to reach. surf_y (float): The actual ``x``-value we are currently at. Returns: Tuple[float, float]: The pair of values the solve the linear system. """ a_val, b_val, c_val, d_val = jac_both[:, 0] # and e_val = x_val - surf_x f_val = y_val - surf_y # Now solve: denom = a_val * d_val - b_val * c_val delta_s = (d_val * e_val - c_val * f_val) / denom delta_t = (a_val * f_val - b_val * e_val) / denom return delta_s, delta_t
python
def newton_refine_solve(jac_both, x_val, surf_x, y_val, surf_y): r"""Helper for :func:`newton_refine`. We have a system: .. code-block:: rest [A C][ds] = [E] [B D][dt] [F] This is not a typo, ``A->B->C->D`` matches the data in ``jac_both``. We solve directly rather than using a linear algebra utility: .. code-block:: rest ds = (D E - C F) / (A D - B C) dt = (A F - B E) / (A D - B C) Args: jac_both (numpy.ndarray): A ``4 x 1`` matrix of entries in a Jacobian. x_val (float): An ``x``-value we are trying to reach. surf_x (float): The actual ``x``-value we are currently at. y_val (float): An ``y``-value we are trying to reach. surf_y (float): The actual ``x``-value we are currently at. Returns: Tuple[float, float]: The pair of values the solve the linear system. """ a_val, b_val, c_val, d_val = jac_both[:, 0] # and e_val = x_val - surf_x f_val = y_val - surf_y # Now solve: denom = a_val * d_val - b_val * c_val delta_s = (d_val * e_val - c_val * f_val) / denom delta_t = (a_val * f_val - b_val * e_val) / denom return delta_s, delta_t
[ "def", "newton_refine_solve", "(", "jac_both", ",", "x_val", ",", "surf_x", ",", "y_val", ",", "surf_y", ")", ":", "a_val", ",", "b_val", ",", "c_val", ",", "d_val", "=", "jac_both", "[", ":", ",", "0", "]", "# and", "e_val", "=", "x_val", "-", "surf_x", "f_val", "=", "y_val", "-", "surf_y", "# Now solve:", "denom", "=", "a_val", "*", "d_val", "-", "b_val", "*", "c_val", "delta_s", "=", "(", "d_val", "*", "e_val", "-", "c_val", "*", "f_val", ")", "/", "denom", "delta_t", "=", "(", "a_val", "*", "f_val", "-", "b_val", "*", "e_val", ")", "/", "denom", "return", "delta_s", ",", "delta_t" ]
r"""Helper for :func:`newton_refine`. We have a system: .. code-block:: rest [A C][ds] = [E] [B D][dt] [F] This is not a typo, ``A->B->C->D`` matches the data in ``jac_both``. We solve directly rather than using a linear algebra utility: .. code-block:: rest ds = (D E - C F) / (A D - B C) dt = (A F - B E) / (A D - B C) Args: jac_both (numpy.ndarray): A ``4 x 1`` matrix of entries in a Jacobian. x_val (float): An ``x``-value we are trying to reach. surf_x (float): The actual ``x``-value we are currently at. y_val (float): An ``y``-value we are trying to reach. surf_y (float): The actual ``x``-value we are currently at. Returns: Tuple[float, float]: The pair of values the solve the linear system.
[ "r", "Helper", "for", ":", "func", ":", "newton_refine", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_surface_intersection.py#L63-L100
dhermes/bezier
src/bezier/_surface_intersection.py
_newton_refine
def _newton_refine(nodes, degree, x_val, y_val, s, t): r"""Refine a solution to :math:`B(s, t) = p` using Newton's method. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Computes updates via .. math:: \left[\begin{array}{c} 0 \\ 0 \end{array}\right] \approx \left(B\left(s_{\ast}, t_{\ast}\right) - \left[\begin{array}{c} x \\ y \end{array}\right]\right) + \left[\begin{array}{c c} B_s\left(s_{\ast}, t_{\ast}\right) & B_t\left(s_{\ast}, t_{\ast}\right) \end{array}\right] \left[\begin{array}{c} \Delta s \\ \Delta t \end{array}\right] For example, (with weights :math:`\lambda_1 = 1 - s - t, \lambda_2 = s, \lambda_3 = t`) consider the surface .. math:: B(s, t) = \left[\begin{array}{c} 0 \\ 0 \end{array}\right] \lambda_1^2 + \left[\begin{array}{c} 1 \\ 0 \end{array}\right] 2 \lambda_1 \lambda_2 + \left[\begin{array}{c} 2 \\ 0 \end{array}\right] \lambda_2^2 + \left[\begin{array}{c} 2 \\ 1 \end{array}\right] 2 \lambda_1 \lambda_3 + \left[\begin{array}{c} 2 \\ 2 \end{array}\right] 2 \lambda_2 \lambda_1 + \left[\begin{array}{c} 0 \\ 2 \end{array}\right] \lambda_3^2 and the point :math:`B\left(\frac{1}{4}, \frac{1}{2}\right) = \frac{1}{4} \left[\begin{array}{c} 5 \\ 5 \end{array}\right]`. Starting from the **wrong** point :math:`s = \frac{1}{2}, t = \frac{1}{4}`, we have .. math:: \begin{align*} \left[\begin{array}{c} x \\ y \end{array}\right] - B\left(\frac{1}{2}, \frac{1}{4}\right) &= \frac{1}{4} \left[\begin{array}{c} -1 \\ 2 \end{array}\right] \\ DB\left(\frac{1}{2}, \frac{1}{4}\right) &= \frac{1}{2} \left[\begin{array}{c c} 3 & 2 \\ 1 & 6 \end{array}\right] \\ \Longrightarrow \left[\begin{array}{c} \Delta s \\ \Delta t \end{array}\right] &= \frac{1}{32} \left[\begin{array}{c} -10 \\ 7 \end{array}\right] \end{align*} .. image:: ../images/newton_refine_surface.png :align: center .. testsetup:: newton-refine-surface import numpy as np import bezier from bezier._surface_intersection import newton_refine .. doctest:: newton-refine-surface >>> nodes = np.asfortranarray([ ... [0.0, 1.0, 2.0, 2.0, 2.0, 0.0], ... [0.0, 0.0, 0.0, 1.0, 2.0, 2.0], ... ]) >>> surface = bezier.Surface(nodes, degree=2) >>> surface.is_valid True >>> (x_val,), (y_val,) = surface.evaluate_cartesian(0.25, 0.5) >>> x_val, y_val (1.25, 1.25) >>> s, t = 0.5, 0.25 >>> new_s, new_t = newton_refine(nodes, 2, x_val, y_val, s, t) >>> 32 * (new_s - s) -10.0 >>> 32 * (new_t - t) 7.0 .. testcleanup:: newton-refine-surface import make_images make_images.newton_refine_surface( surface, x_val, y_val, s, t, new_s, new_t) Args: nodes (numpy.ndarray): Array of nodes in a surface. degree (int): The degree of the surface. x_val (float): The :math:`x`-coordinate of a point on the surface. y_val (float): The :math:`y`-coordinate of a point on the surface. s (float): Approximate :math:`s`-value to be refined. t (float): Approximate :math:`t`-value to be refined. Returns: Tuple[float, float]: The refined :math:`s` and :math:`t` values. """ lambda1 = 1.0 - s - t (surf_x,), (surf_y,) = _surface_helpers.evaluate_barycentric( nodes, degree, lambda1, s, t ) if surf_x == x_val and surf_y == y_val: # No refinement is needed. return s, t # NOTE: This function assumes ``dimension==2`` (i.e. since ``x, y``). jac_nodes = _surface_helpers.jacobian_both(nodes, degree, 2) # The degree of the jacobian is one less. jac_both = _surface_helpers.evaluate_barycentric( jac_nodes, degree - 1, lambda1, s, t ) # The first row of the jacobian matrix is B_s (i.e. the # top-most values in ``jac_both``). delta_s, delta_t = newton_refine_solve( jac_both, x_val, surf_x, y_val, surf_y ) return s + delta_s, t + delta_t
python
def _newton_refine(nodes, degree, x_val, y_val, s, t): r"""Refine a solution to :math:`B(s, t) = p` using Newton's method. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Computes updates via .. math:: \left[\begin{array}{c} 0 \\ 0 \end{array}\right] \approx \left(B\left(s_{\ast}, t_{\ast}\right) - \left[\begin{array}{c} x \\ y \end{array}\right]\right) + \left[\begin{array}{c c} B_s\left(s_{\ast}, t_{\ast}\right) & B_t\left(s_{\ast}, t_{\ast}\right) \end{array}\right] \left[\begin{array}{c} \Delta s \\ \Delta t \end{array}\right] For example, (with weights :math:`\lambda_1 = 1 - s - t, \lambda_2 = s, \lambda_3 = t`) consider the surface .. math:: B(s, t) = \left[\begin{array}{c} 0 \\ 0 \end{array}\right] \lambda_1^2 + \left[\begin{array}{c} 1 \\ 0 \end{array}\right] 2 \lambda_1 \lambda_2 + \left[\begin{array}{c} 2 \\ 0 \end{array}\right] \lambda_2^2 + \left[\begin{array}{c} 2 \\ 1 \end{array}\right] 2 \lambda_1 \lambda_3 + \left[\begin{array}{c} 2 \\ 2 \end{array}\right] 2 \lambda_2 \lambda_1 + \left[\begin{array}{c} 0 \\ 2 \end{array}\right] \lambda_3^2 and the point :math:`B\left(\frac{1}{4}, \frac{1}{2}\right) = \frac{1}{4} \left[\begin{array}{c} 5 \\ 5 \end{array}\right]`. Starting from the **wrong** point :math:`s = \frac{1}{2}, t = \frac{1}{4}`, we have .. math:: \begin{align*} \left[\begin{array}{c} x \\ y \end{array}\right] - B\left(\frac{1}{2}, \frac{1}{4}\right) &= \frac{1}{4} \left[\begin{array}{c} -1 \\ 2 \end{array}\right] \\ DB\left(\frac{1}{2}, \frac{1}{4}\right) &= \frac{1}{2} \left[\begin{array}{c c} 3 & 2 \\ 1 & 6 \end{array}\right] \\ \Longrightarrow \left[\begin{array}{c} \Delta s \\ \Delta t \end{array}\right] &= \frac{1}{32} \left[\begin{array}{c} -10 \\ 7 \end{array}\right] \end{align*} .. image:: ../images/newton_refine_surface.png :align: center .. testsetup:: newton-refine-surface import numpy as np import bezier from bezier._surface_intersection import newton_refine .. doctest:: newton-refine-surface >>> nodes = np.asfortranarray([ ... [0.0, 1.0, 2.0, 2.0, 2.0, 0.0], ... [0.0, 0.0, 0.0, 1.0, 2.0, 2.0], ... ]) >>> surface = bezier.Surface(nodes, degree=2) >>> surface.is_valid True >>> (x_val,), (y_val,) = surface.evaluate_cartesian(0.25, 0.5) >>> x_val, y_val (1.25, 1.25) >>> s, t = 0.5, 0.25 >>> new_s, new_t = newton_refine(nodes, 2, x_val, y_val, s, t) >>> 32 * (new_s - s) -10.0 >>> 32 * (new_t - t) 7.0 .. testcleanup:: newton-refine-surface import make_images make_images.newton_refine_surface( surface, x_val, y_val, s, t, new_s, new_t) Args: nodes (numpy.ndarray): Array of nodes in a surface. degree (int): The degree of the surface. x_val (float): The :math:`x`-coordinate of a point on the surface. y_val (float): The :math:`y`-coordinate of a point on the surface. s (float): Approximate :math:`s`-value to be refined. t (float): Approximate :math:`t`-value to be refined. Returns: Tuple[float, float]: The refined :math:`s` and :math:`t` values. """ lambda1 = 1.0 - s - t (surf_x,), (surf_y,) = _surface_helpers.evaluate_barycentric( nodes, degree, lambda1, s, t ) if surf_x == x_val and surf_y == y_val: # No refinement is needed. return s, t # NOTE: This function assumes ``dimension==2`` (i.e. since ``x, y``). jac_nodes = _surface_helpers.jacobian_both(nodes, degree, 2) # The degree of the jacobian is one less. jac_both = _surface_helpers.evaluate_barycentric( jac_nodes, degree - 1, lambda1, s, t ) # The first row of the jacobian matrix is B_s (i.e. the # top-most values in ``jac_both``). delta_s, delta_t = newton_refine_solve( jac_both, x_val, surf_x, y_val, surf_y ) return s + delta_s, t + delta_t
[ "def", "_newton_refine", "(", "nodes", ",", "degree", ",", "x_val", ",", "y_val", ",", "s", ",", "t", ")", ":", "lambda1", "=", "1.0", "-", "s", "-", "t", "(", "surf_x", ",", ")", ",", "(", "surf_y", ",", ")", "=", "_surface_helpers", ".", "evaluate_barycentric", "(", "nodes", ",", "degree", ",", "lambda1", ",", "s", ",", "t", ")", "if", "surf_x", "==", "x_val", "and", "surf_y", "==", "y_val", ":", "# No refinement is needed.", "return", "s", ",", "t", "# NOTE: This function assumes ``dimension==2`` (i.e. since ``x, y``).", "jac_nodes", "=", "_surface_helpers", ".", "jacobian_both", "(", "nodes", ",", "degree", ",", "2", ")", "# The degree of the jacobian is one less.", "jac_both", "=", "_surface_helpers", ".", "evaluate_barycentric", "(", "jac_nodes", ",", "degree", "-", "1", ",", "lambda1", ",", "s", ",", "t", ")", "# The first row of the jacobian matrix is B_s (i.e. the", "# top-most values in ``jac_both``).", "delta_s", ",", "delta_t", "=", "newton_refine_solve", "(", "jac_both", ",", "x_val", ",", "surf_x", ",", "y_val", ",", "surf_y", ")", "return", "s", "+", "delta_s", ",", "t", "+", "delta_t" ]
r"""Refine a solution to :math:`B(s, t) = p` using Newton's method. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Computes updates via .. math:: \left[\begin{array}{c} 0 \\ 0 \end{array}\right] \approx \left(B\left(s_{\ast}, t_{\ast}\right) - \left[\begin{array}{c} x \\ y \end{array}\right]\right) + \left[\begin{array}{c c} B_s\left(s_{\ast}, t_{\ast}\right) & B_t\left(s_{\ast}, t_{\ast}\right) \end{array}\right] \left[\begin{array}{c} \Delta s \\ \Delta t \end{array}\right] For example, (with weights :math:`\lambda_1 = 1 - s - t, \lambda_2 = s, \lambda_3 = t`) consider the surface .. math:: B(s, t) = \left[\begin{array}{c} 0 \\ 0 \end{array}\right] \lambda_1^2 + \left[\begin{array}{c} 1 \\ 0 \end{array}\right] 2 \lambda_1 \lambda_2 + \left[\begin{array}{c} 2 \\ 0 \end{array}\right] \lambda_2^2 + \left[\begin{array}{c} 2 \\ 1 \end{array}\right] 2 \lambda_1 \lambda_3 + \left[\begin{array}{c} 2 \\ 2 \end{array}\right] 2 \lambda_2 \lambda_1 + \left[\begin{array}{c} 0 \\ 2 \end{array}\right] \lambda_3^2 and the point :math:`B\left(\frac{1}{4}, \frac{1}{2}\right) = \frac{1}{4} \left[\begin{array}{c} 5 \\ 5 \end{array}\right]`. Starting from the **wrong** point :math:`s = \frac{1}{2}, t = \frac{1}{4}`, we have .. math:: \begin{align*} \left[\begin{array}{c} x \\ y \end{array}\right] - B\left(\frac{1}{2}, \frac{1}{4}\right) &= \frac{1}{4} \left[\begin{array}{c} -1 \\ 2 \end{array}\right] \\ DB\left(\frac{1}{2}, \frac{1}{4}\right) &= \frac{1}{2} \left[\begin{array}{c c} 3 & 2 \\ 1 & 6 \end{array}\right] \\ \Longrightarrow \left[\begin{array}{c} \Delta s \\ \Delta t \end{array}\right] &= \frac{1}{32} \left[\begin{array}{c} -10 \\ 7 \end{array}\right] \end{align*} .. image:: ../images/newton_refine_surface.png :align: center .. testsetup:: newton-refine-surface import numpy as np import bezier from bezier._surface_intersection import newton_refine .. doctest:: newton-refine-surface >>> nodes = np.asfortranarray([ ... [0.0, 1.0, 2.0, 2.0, 2.0, 0.0], ... [0.0, 0.0, 0.0, 1.0, 2.0, 2.0], ... ]) >>> surface = bezier.Surface(nodes, degree=2) >>> surface.is_valid True >>> (x_val,), (y_val,) = surface.evaluate_cartesian(0.25, 0.5) >>> x_val, y_val (1.25, 1.25) >>> s, t = 0.5, 0.25 >>> new_s, new_t = newton_refine(nodes, 2, x_val, y_val, s, t) >>> 32 * (new_s - s) -10.0 >>> 32 * (new_t - t) 7.0 .. testcleanup:: newton-refine-surface import make_images make_images.newton_refine_surface( surface, x_val, y_val, s, t, new_s, new_t) Args: nodes (numpy.ndarray): Array of nodes in a surface. degree (int): The degree of the surface. x_val (float): The :math:`x`-coordinate of a point on the surface. y_val (float): The :math:`y`-coordinate of a point on the surface. s (float): Approximate :math:`s`-value to be refined. t (float): Approximate :math:`t`-value to be refined. Returns: Tuple[float, float]: The refined :math:`s` and :math:`t` values.
[ "r", "Refine", "a", "solution", "to", ":", "math", ":", "B", "(", "s", "t", ")", "=", "p", "using", "Newton", "s", "method", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_surface_intersection.py#L103-L228
dhermes/bezier
src/bezier/_surface_intersection.py
update_locate_candidates
def update_locate_candidates(candidate, next_candidates, x_val, y_val, degree): """Update list of candidate surfaces during geometric search for a point. .. note:: This is used **only** as a helper for :func:`locate_point`. Checks if the point ``(x_val, y_val)`` is contained in the ``candidate`` surface. If not, this function does nothing. If the point is contaned, the four subdivided surfaces from ``candidate`` are added to ``next_candidates``. Args: candidate (Tuple[float, float, float, numpy.ndarray]): A 4-tuple describing a surface and its centroid / width. Contains * Three times centroid ``x``-value * Three times centroid ``y``-value * "Width" of parameter space for the surface * Control points for the surface next_candidates (list): List of "candidate" sub-surfaces that may contain the point being located. x_val (float): The ``x``-coordinate being located. y_val (float): The ``y``-coordinate being located. degree (int): The degree of the surface. """ centroid_x, centroid_y, width, candidate_nodes = candidate point = np.asfortranarray([x_val, y_val]) if not _helpers.contains_nd(candidate_nodes, point): return nodes_a, nodes_b, nodes_c, nodes_d = _surface_helpers.subdivide_nodes( candidate_nodes, degree ) half_width = 0.5 * width next_candidates.extend( ( ( centroid_x - half_width, centroid_y - half_width, half_width, nodes_a, ), (centroid_x, centroid_y, -half_width, nodes_b), (centroid_x + width, centroid_y - half_width, half_width, nodes_c), (centroid_x - half_width, centroid_y + width, half_width, nodes_d), ) )
python
def update_locate_candidates(candidate, next_candidates, x_val, y_val, degree): """Update list of candidate surfaces during geometric search for a point. .. note:: This is used **only** as a helper for :func:`locate_point`. Checks if the point ``(x_val, y_val)`` is contained in the ``candidate`` surface. If not, this function does nothing. If the point is contaned, the four subdivided surfaces from ``candidate`` are added to ``next_candidates``. Args: candidate (Tuple[float, float, float, numpy.ndarray]): A 4-tuple describing a surface and its centroid / width. Contains * Three times centroid ``x``-value * Three times centroid ``y``-value * "Width" of parameter space for the surface * Control points for the surface next_candidates (list): List of "candidate" sub-surfaces that may contain the point being located. x_val (float): The ``x``-coordinate being located. y_val (float): The ``y``-coordinate being located. degree (int): The degree of the surface. """ centroid_x, centroid_y, width, candidate_nodes = candidate point = np.asfortranarray([x_val, y_val]) if not _helpers.contains_nd(candidate_nodes, point): return nodes_a, nodes_b, nodes_c, nodes_d = _surface_helpers.subdivide_nodes( candidate_nodes, degree ) half_width = 0.5 * width next_candidates.extend( ( ( centroid_x - half_width, centroid_y - half_width, half_width, nodes_a, ), (centroid_x, centroid_y, -half_width, nodes_b), (centroid_x + width, centroid_y - half_width, half_width, nodes_c), (centroid_x - half_width, centroid_y + width, half_width, nodes_d), ) )
[ "def", "update_locate_candidates", "(", "candidate", ",", "next_candidates", ",", "x_val", ",", "y_val", ",", "degree", ")", ":", "centroid_x", ",", "centroid_y", ",", "width", ",", "candidate_nodes", "=", "candidate", "point", "=", "np", ".", "asfortranarray", "(", "[", "x_val", ",", "y_val", "]", ")", "if", "not", "_helpers", ".", "contains_nd", "(", "candidate_nodes", ",", "point", ")", ":", "return", "nodes_a", ",", "nodes_b", ",", "nodes_c", ",", "nodes_d", "=", "_surface_helpers", ".", "subdivide_nodes", "(", "candidate_nodes", ",", "degree", ")", "half_width", "=", "0.5", "*", "width", "next_candidates", ".", "extend", "(", "(", "(", "centroid_x", "-", "half_width", ",", "centroid_y", "-", "half_width", ",", "half_width", ",", "nodes_a", ",", ")", ",", "(", "centroid_x", ",", "centroid_y", ",", "-", "half_width", ",", "nodes_b", ")", ",", "(", "centroid_x", "+", "width", ",", "centroid_y", "-", "half_width", ",", "half_width", ",", "nodes_c", ")", ",", "(", "centroid_x", "-", "half_width", ",", "centroid_y", "+", "width", ",", "half_width", ",", "nodes_d", ")", ",", ")", ")" ]
Update list of candidate surfaces during geometric search for a point. .. note:: This is used **only** as a helper for :func:`locate_point`. Checks if the point ``(x_val, y_val)`` is contained in the ``candidate`` surface. If not, this function does nothing. If the point is contaned, the four subdivided surfaces from ``candidate`` are added to ``next_candidates``. Args: candidate (Tuple[float, float, float, numpy.ndarray]): A 4-tuple describing a surface and its centroid / width. Contains * Three times centroid ``x``-value * Three times centroid ``y``-value * "Width" of parameter space for the surface * Control points for the surface next_candidates (list): List of "candidate" sub-surfaces that may contain the point being located. x_val (float): The ``x``-coordinate being located. y_val (float): The ``y``-coordinate being located. degree (int): The degree of the surface.
[ "Update", "list", "of", "candidate", "surfaces", "during", "geometric", "search", "for", "a", "point", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_surface_intersection.py#L231-L278
dhermes/bezier
src/bezier/_surface_intersection.py
mean_centroid
def mean_centroid(candidates): """Take the mean of all centroids in set of reference triangles. .. note:: This is used **only** as a helper for :func:`locate_point`. Args: candidates (List[Tuple[float, float, float, numpy.ndarray]): List of 4-tuples, each of which has been produced by :func:`locate_point`. Each 4-tuple contains * Three times centroid ``x``-value * Three times centroid ``y``-value * "Width" of a parameter space for a surface * Control points for a surface We only use the first two values, which are triple the desired value so that we can put off division by three until summing in our average. We don't use the other two values, they are just an artifact of the way ``candidates`` is constructed by the caller. Returns: Tuple[float, float]: The mean of all centroids. """ sum_x = 0.0 sum_y = 0.0 for centroid_x, centroid_y, _, _ in candidates: sum_x += centroid_x sum_y += centroid_y denom = 3.0 * len(candidates) return sum_x / denom, sum_y / denom
python
def mean_centroid(candidates): """Take the mean of all centroids in set of reference triangles. .. note:: This is used **only** as a helper for :func:`locate_point`. Args: candidates (List[Tuple[float, float, float, numpy.ndarray]): List of 4-tuples, each of which has been produced by :func:`locate_point`. Each 4-tuple contains * Three times centroid ``x``-value * Three times centroid ``y``-value * "Width" of a parameter space for a surface * Control points for a surface We only use the first two values, which are triple the desired value so that we can put off division by three until summing in our average. We don't use the other two values, they are just an artifact of the way ``candidates`` is constructed by the caller. Returns: Tuple[float, float]: The mean of all centroids. """ sum_x = 0.0 sum_y = 0.0 for centroid_x, centroid_y, _, _ in candidates: sum_x += centroid_x sum_y += centroid_y denom = 3.0 * len(candidates) return sum_x / denom, sum_y / denom
[ "def", "mean_centroid", "(", "candidates", ")", ":", "sum_x", "=", "0.0", "sum_y", "=", "0.0", "for", "centroid_x", ",", "centroid_y", ",", "_", ",", "_", "in", "candidates", ":", "sum_x", "+=", "centroid_x", "sum_y", "+=", "centroid_y", "denom", "=", "3.0", "*", "len", "(", "candidates", ")", "return", "sum_x", "/", "denom", ",", "sum_y", "/", "denom" ]
Take the mean of all centroids in set of reference triangles. .. note:: This is used **only** as a helper for :func:`locate_point`. Args: candidates (List[Tuple[float, float, float, numpy.ndarray]): List of 4-tuples, each of which has been produced by :func:`locate_point`. Each 4-tuple contains * Three times centroid ``x``-value * Three times centroid ``y``-value * "Width" of a parameter space for a surface * Control points for a surface We only use the first two values, which are triple the desired value so that we can put off division by three until summing in our average. We don't use the other two values, they are just an artifact of the way ``candidates`` is constructed by the caller. Returns: Tuple[float, float]: The mean of all centroids.
[ "Take", "the", "mean", "of", "all", "centroids", "in", "set", "of", "reference", "triangles", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_surface_intersection.py#L281-L312
dhermes/bezier
src/bezier/_surface_intersection.py
_locate_point
def _locate_point(nodes, degree, x_val, y_val): r"""Locate a point on a surface. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Does so by recursively subdividing the surface and rejecting sub-surfaces with bounding boxes that don't contain the point. After the sub-surfaces are sufficiently small, uses Newton's method to narrow in on the pre-image of the point. Args: nodes (numpy.ndarray): Control points for B |eacute| zier surface (assumed to be two-dimensional). degree (int): The degree of the surface. x_val (float): The :math:`x`-coordinate of a point on the surface. y_val (float): The :math:`y`-coordinate of a point on the surface. Returns: Optional[Tuple[float, float]]: The :math:`s` and :math:`t` values corresponding to ``x_val`` and ``y_val`` or :data:`None` if the point is not on the ``surface``. """ # We track the centroid rather than base_x/base_y/width (by storing triple # the centroid -- to avoid division by three until needed). We also need # to track the width (or rather, just the sign of the width). candidates = [(1.0, 1.0, 1.0, nodes)] for _ in six.moves.xrange(MAX_LOCATE_SUBDIVISIONS + 1): next_candidates = [] for candidate in candidates: update_locate_candidates( candidate, next_candidates, x_val, y_val, degree ) candidates = next_candidates if not candidates: return None # We take the average of all centroids from the candidates # that may contain the point. s_approx, t_approx = mean_centroid(candidates) s, t = newton_refine(nodes, degree, x_val, y_val, s_approx, t_approx) actual = _surface_helpers.evaluate_barycentric( nodes, degree, 1.0 - s - t, s, t ) expected = np.asfortranarray([x_val, y_val]) if not _helpers.vector_close( actual.ravel(order="F"), expected, eps=LOCATE_EPS ): s, t = newton_refine(nodes, degree, x_val, y_val, s, t) return s, t
python
def _locate_point(nodes, degree, x_val, y_val): r"""Locate a point on a surface. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Does so by recursively subdividing the surface and rejecting sub-surfaces with bounding boxes that don't contain the point. After the sub-surfaces are sufficiently small, uses Newton's method to narrow in on the pre-image of the point. Args: nodes (numpy.ndarray): Control points for B |eacute| zier surface (assumed to be two-dimensional). degree (int): The degree of the surface. x_val (float): The :math:`x`-coordinate of a point on the surface. y_val (float): The :math:`y`-coordinate of a point on the surface. Returns: Optional[Tuple[float, float]]: The :math:`s` and :math:`t` values corresponding to ``x_val`` and ``y_val`` or :data:`None` if the point is not on the ``surface``. """ # We track the centroid rather than base_x/base_y/width (by storing triple # the centroid -- to avoid division by three until needed). We also need # to track the width (or rather, just the sign of the width). candidates = [(1.0, 1.0, 1.0, nodes)] for _ in six.moves.xrange(MAX_LOCATE_SUBDIVISIONS + 1): next_candidates = [] for candidate in candidates: update_locate_candidates( candidate, next_candidates, x_val, y_val, degree ) candidates = next_candidates if not candidates: return None # We take the average of all centroids from the candidates # that may contain the point. s_approx, t_approx = mean_centroid(candidates) s, t = newton_refine(nodes, degree, x_val, y_val, s_approx, t_approx) actual = _surface_helpers.evaluate_barycentric( nodes, degree, 1.0 - s - t, s, t ) expected = np.asfortranarray([x_val, y_val]) if not _helpers.vector_close( actual.ravel(order="F"), expected, eps=LOCATE_EPS ): s, t = newton_refine(nodes, degree, x_val, y_val, s, t) return s, t
[ "def", "_locate_point", "(", "nodes", ",", "degree", ",", "x_val", ",", "y_val", ")", ":", "# We track the centroid rather than base_x/base_y/width (by storing triple", "# the centroid -- to avoid division by three until needed). We also need", "# to track the width (or rather, just the sign of the width).", "candidates", "=", "[", "(", "1.0", ",", "1.0", ",", "1.0", ",", "nodes", ")", "]", "for", "_", "in", "six", ".", "moves", ".", "xrange", "(", "MAX_LOCATE_SUBDIVISIONS", "+", "1", ")", ":", "next_candidates", "=", "[", "]", "for", "candidate", "in", "candidates", ":", "update_locate_candidates", "(", "candidate", ",", "next_candidates", ",", "x_val", ",", "y_val", ",", "degree", ")", "candidates", "=", "next_candidates", "if", "not", "candidates", ":", "return", "None", "# We take the average of all centroids from the candidates", "# that may contain the point.", "s_approx", ",", "t_approx", "=", "mean_centroid", "(", "candidates", ")", "s", ",", "t", "=", "newton_refine", "(", "nodes", ",", "degree", ",", "x_val", ",", "y_val", ",", "s_approx", ",", "t_approx", ")", "actual", "=", "_surface_helpers", ".", "evaluate_barycentric", "(", "nodes", ",", "degree", ",", "1.0", "-", "s", "-", "t", ",", "s", ",", "t", ")", "expected", "=", "np", ".", "asfortranarray", "(", "[", "x_val", ",", "y_val", "]", ")", "if", "not", "_helpers", ".", "vector_close", "(", "actual", ".", "ravel", "(", "order", "=", "\"F\"", ")", ",", "expected", ",", "eps", "=", "LOCATE_EPS", ")", ":", "s", ",", "t", "=", "newton_refine", "(", "nodes", ",", "degree", ",", "x_val", ",", "y_val", ",", "s", ",", "t", ")", "return", "s", ",", "t" ]
r"""Locate a point on a surface. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Does so by recursively subdividing the surface and rejecting sub-surfaces with bounding boxes that don't contain the point. After the sub-surfaces are sufficiently small, uses Newton's method to narrow in on the pre-image of the point. Args: nodes (numpy.ndarray): Control points for B |eacute| zier surface (assumed to be two-dimensional). degree (int): The degree of the surface. x_val (float): The :math:`x`-coordinate of a point on the surface. y_val (float): The :math:`y`-coordinate of a point on the surface. Returns: Optional[Tuple[float, float]]: The :math:`s` and :math:`t` values corresponding to ``x_val`` and ``y_val`` or :data:`None` if the point is not on the ``surface``.
[ "r", "Locate", "a", "point", "on", "a", "surface", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_surface_intersection.py#L315-L368
dhermes/bezier
src/bezier/_surface_intersection.py
same_intersection
def same_intersection(intersection1, intersection2, wiggle=0.5 ** 40): """Check if two intersections are close to machine precision. .. note:: This is a helper used only by :func:`verify_duplicates`, which in turn is only used by :func:`generic_intersect`. Args: intersection1 (.Intersection): The first intersection. intersection2 (.Intersection): The second intersection. wiggle (Optional[float]): The amount of relative error allowed in parameter values. Returns: bool: Indicates if the two intersections are the same to machine precision. """ if intersection1.index_first != intersection2.index_first: return False if intersection1.index_second != intersection2.index_second: return False return np.allclose( [intersection1.s, intersection1.t], [intersection2.s, intersection2.t], atol=0.0, rtol=wiggle, )
python
def same_intersection(intersection1, intersection2, wiggle=0.5 ** 40): """Check if two intersections are close to machine precision. .. note:: This is a helper used only by :func:`verify_duplicates`, which in turn is only used by :func:`generic_intersect`. Args: intersection1 (.Intersection): The first intersection. intersection2 (.Intersection): The second intersection. wiggle (Optional[float]): The amount of relative error allowed in parameter values. Returns: bool: Indicates if the two intersections are the same to machine precision. """ if intersection1.index_first != intersection2.index_first: return False if intersection1.index_second != intersection2.index_second: return False return np.allclose( [intersection1.s, intersection1.t], [intersection2.s, intersection2.t], atol=0.0, rtol=wiggle, )
[ "def", "same_intersection", "(", "intersection1", ",", "intersection2", ",", "wiggle", "=", "0.5", "**", "40", ")", ":", "if", "intersection1", ".", "index_first", "!=", "intersection2", ".", "index_first", ":", "return", "False", "if", "intersection1", ".", "index_second", "!=", "intersection2", ".", "index_second", ":", "return", "False", "return", "np", ".", "allclose", "(", "[", "intersection1", ".", "s", ",", "intersection1", ".", "t", "]", ",", "[", "intersection2", ".", "s", ",", "intersection2", ".", "t", "]", ",", "atol", "=", "0.0", ",", "rtol", "=", "wiggle", ",", ")" ]
Check if two intersections are close to machine precision. .. note:: This is a helper used only by :func:`verify_duplicates`, which in turn is only used by :func:`generic_intersect`. Args: intersection1 (.Intersection): The first intersection. intersection2 (.Intersection): The second intersection. wiggle (Optional[float]): The amount of relative error allowed in parameter values. Returns: bool: Indicates if the two intersections are the same to machine precision.
[ "Check", "if", "two", "intersections", "are", "close", "to", "machine", "precision", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_surface_intersection.py#L371-L400
dhermes/bezier
src/bezier/_surface_intersection.py
verify_duplicates
def verify_duplicates(duplicates, uniques): """Verify that a set of intersections had expected duplicates. .. note:: This is a helper used only by :func:`generic_intersect`. Args: duplicates (List[.Intersection]): List of intersections corresponding to duplicates that were filtered out. uniques (List[.Intersection]): List of "final" intersections with duplicates filtered out. Raises: ValueError: If the ``uniques`` are not actually all unique. ValueError: If one of the ``duplicates`` does not correspond to an intersection in ``uniques``. ValueError: If a duplicate occurs only once but does not have exactly one of ``s`` and ``t`` equal to ``0.0``. ValueError: If a duplicate occurs three times but does not have exactly both ``s == t == 0.0``. ValueError: If a duplicate occurs a number other than one or three times. """ for uniq1, uniq2 in itertools.combinations(uniques, 2): if same_intersection(uniq1, uniq2): raise ValueError("Non-unique intersection") counter = collections.Counter() for dupe in duplicates: matches = [] for index, uniq in enumerate(uniques): if same_intersection(dupe, uniq): matches.append(index) if len(matches) != 1: raise ValueError("Duplicate not among uniques", dupe) matched = matches[0] counter[matched] += 1 for index, count in six.iteritems(counter): uniq = uniques[index] if count == 1: if (uniq.s, uniq.t).count(0.0) != 1: raise ValueError("Count == 1 should be a single corner", uniq) elif count == 3: if (uniq.s, uniq.t) != (0.0, 0.0): raise ValueError("Count == 3 should be a double corner", uniq) else: raise ValueError("Unexpected duplicate count", count)
python
def verify_duplicates(duplicates, uniques): """Verify that a set of intersections had expected duplicates. .. note:: This is a helper used only by :func:`generic_intersect`. Args: duplicates (List[.Intersection]): List of intersections corresponding to duplicates that were filtered out. uniques (List[.Intersection]): List of "final" intersections with duplicates filtered out. Raises: ValueError: If the ``uniques`` are not actually all unique. ValueError: If one of the ``duplicates`` does not correspond to an intersection in ``uniques``. ValueError: If a duplicate occurs only once but does not have exactly one of ``s`` and ``t`` equal to ``0.0``. ValueError: If a duplicate occurs three times but does not have exactly both ``s == t == 0.0``. ValueError: If a duplicate occurs a number other than one or three times. """ for uniq1, uniq2 in itertools.combinations(uniques, 2): if same_intersection(uniq1, uniq2): raise ValueError("Non-unique intersection") counter = collections.Counter() for dupe in duplicates: matches = [] for index, uniq in enumerate(uniques): if same_intersection(dupe, uniq): matches.append(index) if len(matches) != 1: raise ValueError("Duplicate not among uniques", dupe) matched = matches[0] counter[matched] += 1 for index, count in six.iteritems(counter): uniq = uniques[index] if count == 1: if (uniq.s, uniq.t).count(0.0) != 1: raise ValueError("Count == 1 should be a single corner", uniq) elif count == 3: if (uniq.s, uniq.t) != (0.0, 0.0): raise ValueError("Count == 3 should be a double corner", uniq) else: raise ValueError("Unexpected duplicate count", count)
[ "def", "verify_duplicates", "(", "duplicates", ",", "uniques", ")", ":", "for", "uniq1", ",", "uniq2", "in", "itertools", ".", "combinations", "(", "uniques", ",", "2", ")", ":", "if", "same_intersection", "(", "uniq1", ",", "uniq2", ")", ":", "raise", "ValueError", "(", "\"Non-unique intersection\"", ")", "counter", "=", "collections", ".", "Counter", "(", ")", "for", "dupe", "in", "duplicates", ":", "matches", "=", "[", "]", "for", "index", ",", "uniq", "in", "enumerate", "(", "uniques", ")", ":", "if", "same_intersection", "(", "dupe", ",", "uniq", ")", ":", "matches", ".", "append", "(", "index", ")", "if", "len", "(", "matches", ")", "!=", "1", ":", "raise", "ValueError", "(", "\"Duplicate not among uniques\"", ",", "dupe", ")", "matched", "=", "matches", "[", "0", "]", "counter", "[", "matched", "]", "+=", "1", "for", "index", ",", "count", "in", "six", ".", "iteritems", "(", "counter", ")", ":", "uniq", "=", "uniques", "[", "index", "]", "if", "count", "==", "1", ":", "if", "(", "uniq", ".", "s", ",", "uniq", ".", "t", ")", ".", "count", "(", "0.0", ")", "!=", "1", ":", "raise", "ValueError", "(", "\"Count == 1 should be a single corner\"", ",", "uniq", ")", "elif", "count", "==", "3", ":", "if", "(", "uniq", ".", "s", ",", "uniq", ".", "t", ")", "!=", "(", "0.0", ",", "0.0", ")", ":", "raise", "ValueError", "(", "\"Count == 3 should be a double corner\"", ",", "uniq", ")", "else", ":", "raise", "ValueError", "(", "\"Unexpected duplicate count\"", ",", "count", ")" ]
Verify that a set of intersections had expected duplicates. .. note:: This is a helper used only by :func:`generic_intersect`. Args: duplicates (List[.Intersection]): List of intersections corresponding to duplicates that were filtered out. uniques (List[.Intersection]): List of "final" intersections with duplicates filtered out. Raises: ValueError: If the ``uniques`` are not actually all unique. ValueError: If one of the ``duplicates`` does not correspond to an intersection in ``uniques``. ValueError: If a duplicate occurs only once but does not have exactly one of ``s`` and ``t`` equal to ``0.0``. ValueError: If a duplicate occurs three times but does not have exactly both ``s == t == 0.0``. ValueError: If a duplicate occurs a number other than one or three times.
[ "Verify", "that", "a", "set", "of", "intersections", "had", "expected", "duplicates", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_surface_intersection.py#L403-L453
dhermes/bezier
src/bezier/_surface_intersection.py
verify_edge_segments
def verify_edge_segments(edge_infos): """Verify that the edge segments in an intersection are valid. .. note:: This is a helper used only by :func:`generic_intersect`. Args: edge_infos (Optional[list]): List of "edge info" lists. Each list represents a curved polygon and contains 3-tuples of edge index, start and end (see the output of :func:`ends_to_curve`). Raises: ValueError: If two consecutive edge segments lie on the same edge index. ValueError: If the start and end parameter are "invalid" (they should be between 0 and 1 and start should be strictly less than end). """ if edge_infos is None: return for edge_info in edge_infos: num_segments = len(edge_info) for index in six.moves.xrange(-1, num_segments - 1): index1, start1, end1 = edge_info[index] # First, verify the start and end parameters for the current # segment. if not 0.0 <= start1 < end1 <= 1.0: raise ValueError(BAD_SEGMENT_PARAMS, edge_info[index]) # Then, verify that the indices are not the same. index2, _, _ = edge_info[index + 1] if index1 == index2: raise ValueError( SEGMENTS_SAME_EDGE, edge_info[index], edge_info[index + 1] )
python
def verify_edge_segments(edge_infos): """Verify that the edge segments in an intersection are valid. .. note:: This is a helper used only by :func:`generic_intersect`. Args: edge_infos (Optional[list]): List of "edge info" lists. Each list represents a curved polygon and contains 3-tuples of edge index, start and end (see the output of :func:`ends_to_curve`). Raises: ValueError: If two consecutive edge segments lie on the same edge index. ValueError: If the start and end parameter are "invalid" (they should be between 0 and 1 and start should be strictly less than end). """ if edge_infos is None: return for edge_info in edge_infos: num_segments = len(edge_info) for index in six.moves.xrange(-1, num_segments - 1): index1, start1, end1 = edge_info[index] # First, verify the start and end parameters for the current # segment. if not 0.0 <= start1 < end1 <= 1.0: raise ValueError(BAD_SEGMENT_PARAMS, edge_info[index]) # Then, verify that the indices are not the same. index2, _, _ = edge_info[index + 1] if index1 == index2: raise ValueError( SEGMENTS_SAME_EDGE, edge_info[index], edge_info[index + 1] )
[ "def", "verify_edge_segments", "(", "edge_infos", ")", ":", "if", "edge_infos", "is", "None", ":", "return", "for", "edge_info", "in", "edge_infos", ":", "num_segments", "=", "len", "(", "edge_info", ")", "for", "index", "in", "six", ".", "moves", ".", "xrange", "(", "-", "1", ",", "num_segments", "-", "1", ")", ":", "index1", ",", "start1", ",", "end1", "=", "edge_info", "[", "index", "]", "# First, verify the start and end parameters for the current", "# segment.", "if", "not", "0.0", "<=", "start1", "<", "end1", "<=", "1.0", ":", "raise", "ValueError", "(", "BAD_SEGMENT_PARAMS", ",", "edge_info", "[", "index", "]", ")", "# Then, verify that the indices are not the same.", "index2", ",", "_", ",", "_", "=", "edge_info", "[", "index", "+", "1", "]", "if", "index1", "==", "index2", ":", "raise", "ValueError", "(", "SEGMENTS_SAME_EDGE", ",", "edge_info", "[", "index", "]", ",", "edge_info", "[", "index", "+", "1", "]", ")" ]
Verify that the edge segments in an intersection are valid. .. note:: This is a helper used only by :func:`generic_intersect`. Args: edge_infos (Optional[list]): List of "edge info" lists. Each list represents a curved polygon and contains 3-tuples of edge index, start and end (see the output of :func:`ends_to_curve`). Raises: ValueError: If two consecutive edge segments lie on the same edge index. ValueError: If the start and end parameter are "invalid" (they should be between 0 and 1 and start should be strictly less than end).
[ "Verify", "that", "the", "edge", "segments", "in", "an", "intersection", "are", "valid", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_surface_intersection.py#L456-L491
dhermes/bezier
src/bezier/_surface_intersection.py
add_edge_end_unused
def add_edge_end_unused(intersection, duplicates, intersections): """Add intersection that is ``COINCIDENT_UNUSED`` but on an edge end. This is a helper for :func:`~._surface_intersection.add_intersection`. It assumes that * ``intersection`` will have at least one of ``s == 0.0`` or ``t == 0.0`` * A "misclassified" intersection in ``intersections`` that matches ``intersection`` will be the "same" if it matches both ``index_first`` and ``index_second`` and if it matches the start index exactly Args: intersection (.Intersection): An intersection to be added. duplicates (List[.Intersection]): List of duplicate intersections. intersections (List[.Intersection]): List of "accepted" (i.e. non-duplicate) intersections. """ found = None for other in intersections: if ( intersection.index_first == other.index_first and intersection.index_second == other.index_second ): if intersection.s == 0.0 and other.s == 0.0: found = other break if intersection.t == 0.0 and other.t == 0.0: found = other break if found is not None: intersections.remove(found) duplicates.append(found) intersections.append(intersection)
python
def add_edge_end_unused(intersection, duplicates, intersections): """Add intersection that is ``COINCIDENT_UNUSED`` but on an edge end. This is a helper for :func:`~._surface_intersection.add_intersection`. It assumes that * ``intersection`` will have at least one of ``s == 0.0`` or ``t == 0.0`` * A "misclassified" intersection in ``intersections`` that matches ``intersection`` will be the "same" if it matches both ``index_first`` and ``index_second`` and if it matches the start index exactly Args: intersection (.Intersection): An intersection to be added. duplicates (List[.Intersection]): List of duplicate intersections. intersections (List[.Intersection]): List of "accepted" (i.e. non-duplicate) intersections. """ found = None for other in intersections: if ( intersection.index_first == other.index_first and intersection.index_second == other.index_second ): if intersection.s == 0.0 and other.s == 0.0: found = other break if intersection.t == 0.0 and other.t == 0.0: found = other break if found is not None: intersections.remove(found) duplicates.append(found) intersections.append(intersection)
[ "def", "add_edge_end_unused", "(", "intersection", ",", "duplicates", ",", "intersections", ")", ":", "found", "=", "None", "for", "other", "in", "intersections", ":", "if", "(", "intersection", ".", "index_first", "==", "other", ".", "index_first", "and", "intersection", ".", "index_second", "==", "other", ".", "index_second", ")", ":", "if", "intersection", ".", "s", "==", "0.0", "and", "other", ".", "s", "==", "0.0", ":", "found", "=", "other", "break", "if", "intersection", ".", "t", "==", "0.0", "and", "other", ".", "t", "==", "0.0", ":", "found", "=", "other", "break", "if", "found", "is", "not", "None", ":", "intersections", ".", "remove", "(", "found", ")", "duplicates", ".", "append", "(", "found", ")", "intersections", ".", "append", "(", "intersection", ")" ]
Add intersection that is ``COINCIDENT_UNUSED`` but on an edge end. This is a helper for :func:`~._surface_intersection.add_intersection`. It assumes that * ``intersection`` will have at least one of ``s == 0.0`` or ``t == 0.0`` * A "misclassified" intersection in ``intersections`` that matches ``intersection`` will be the "same" if it matches both ``index_first`` and ``index_second`` and if it matches the start index exactly Args: intersection (.Intersection): An intersection to be added. duplicates (List[.Intersection]): List of duplicate intersections. intersections (List[.Intersection]): List of "accepted" (i.e. non-duplicate) intersections.
[ "Add", "intersection", "that", "is", "COINCIDENT_UNUSED", "but", "on", "an", "edge", "end", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_surface_intersection.py#L494-L528
dhermes/bezier
src/bezier/_surface_intersection.py
check_unused
def check_unused(intersection, duplicates, intersections): """Check if a "valid" ``intersection`` is already in ``intersections``. This assumes that * ``intersection`` will have at least one of ``s == 0.0`` or ``t == 0.0`` * At least one of the intersections in ``intersections`` is classified as ``COINCIDENT_UNUSED``. Args: intersection (.Intersection): An intersection to be added. duplicates (List[.Intersection]): List of duplicate intersections. intersections (List[.Intersection]): List of "accepted" (i.e. non-duplicate) intersections. Returns: bool: Indicates if the ``intersection`` is a duplicate. """ for other in intersections: if ( other.interior_curve == UNUSED_T and intersection.index_first == other.index_first and intersection.index_second == other.index_second ): if intersection.s == 0.0 and other.s == 0.0: duplicates.append(intersection) return True if intersection.t == 0.0 and other.t == 0.0: duplicates.append(intersection) return True return False
python
def check_unused(intersection, duplicates, intersections): """Check if a "valid" ``intersection`` is already in ``intersections``. This assumes that * ``intersection`` will have at least one of ``s == 0.0`` or ``t == 0.0`` * At least one of the intersections in ``intersections`` is classified as ``COINCIDENT_UNUSED``. Args: intersection (.Intersection): An intersection to be added. duplicates (List[.Intersection]): List of duplicate intersections. intersections (List[.Intersection]): List of "accepted" (i.e. non-duplicate) intersections. Returns: bool: Indicates if the ``intersection`` is a duplicate. """ for other in intersections: if ( other.interior_curve == UNUSED_T and intersection.index_first == other.index_first and intersection.index_second == other.index_second ): if intersection.s == 0.0 and other.s == 0.0: duplicates.append(intersection) return True if intersection.t == 0.0 and other.t == 0.0: duplicates.append(intersection) return True return False
[ "def", "check_unused", "(", "intersection", ",", "duplicates", ",", "intersections", ")", ":", "for", "other", "in", "intersections", ":", "if", "(", "other", ".", "interior_curve", "==", "UNUSED_T", "and", "intersection", ".", "index_first", "==", "other", ".", "index_first", "and", "intersection", ".", "index_second", "==", "other", ".", "index_second", ")", ":", "if", "intersection", ".", "s", "==", "0.0", "and", "other", ".", "s", "==", "0.0", ":", "duplicates", ".", "append", "(", "intersection", ")", "return", "True", "if", "intersection", ".", "t", "==", "0.0", "and", "other", ".", "t", "==", "0.0", ":", "duplicates", ".", "append", "(", "intersection", ")", "return", "True", "return", "False" ]
Check if a "valid" ``intersection`` is already in ``intersections``. This assumes that * ``intersection`` will have at least one of ``s == 0.0`` or ``t == 0.0`` * At least one of the intersections in ``intersections`` is classified as ``COINCIDENT_UNUSED``. Args: intersection (.Intersection): An intersection to be added. duplicates (List[.Intersection]): List of duplicate intersections. intersections (List[.Intersection]): List of "accepted" (i.e. non-duplicate) intersections. Returns: bool: Indicates if the ``intersection`` is a duplicate.
[ "Check", "if", "a", "valid", "intersection", "is", "already", "in", "intersections", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_surface_intersection.py#L531-L563
dhermes/bezier
src/bezier/_surface_intersection.py
add_intersection
def add_intersection( # pylint: disable=too-many-arguments index1, s, index2, t, interior_curve, edge_nodes1, edge_nodes2, duplicates, intersections, ): """Create an :class:`Intersection` and append. The intersection will be classified as either a duplicate or a valid intersection and appended to one of ``duplicates`` or ``intersections`` depending on that classification. Args: index1 (int): The index (among 0, 1, 2) of the first edge in the intersection. s (float): The parameter along the first curve of the intersection. index2 (int): The index (among 0, 1, 2) of the second edge in the intersection. t (float): The parameter along the second curve of the intersection. interior_curve (Optional[.IntersectionClassification]): The classification of the intersection, if known. If :data:`None`, the classification will be computed below. edge_nodes1 (Tuple[numpy.ndarray, numpy.ndarray, numpy.ndarray]): The nodes of the three edges of the first surface being intersected. edge_nodes2 (Tuple[numpy.ndarray, numpy.ndarray, numpy.ndarray]): The nodes of the three edges of the second surface being intersected. duplicates (List[.Intersection]): List of duplicate intersections. intersections (List[.Intersection]): List of "accepted" (i.e. non-duplicate) intersections. """ # NOTE: There is no corresponding "enable", but the disable only applies # in this lexical scope. # pylint: disable=too-many-locals edge_end, is_corner, intersection_args = _surface_helpers.handle_ends( index1, s, index2, t ) if edge_end: intersection = _intersection_helpers.Intersection(*intersection_args) intersection.interior_curve = interior_curve if interior_curve == UNUSED_T: add_edge_end_unused(intersection, duplicates, intersections) else: duplicates.append(intersection) else: intersection = _intersection_helpers.Intersection(index1, s, index2, t) if is_corner: is_duplicate = check_unused( intersection, duplicates, intersections ) if is_duplicate: return # Classify the intersection. if interior_curve is None: interior_curve = _surface_helpers.classify_intersection( intersection, edge_nodes1, edge_nodes2 ) intersection.interior_curve = interior_curve intersections.append(intersection)
python
def add_intersection( # pylint: disable=too-many-arguments index1, s, index2, t, interior_curve, edge_nodes1, edge_nodes2, duplicates, intersections, ): """Create an :class:`Intersection` and append. The intersection will be classified as either a duplicate or a valid intersection and appended to one of ``duplicates`` or ``intersections`` depending on that classification. Args: index1 (int): The index (among 0, 1, 2) of the first edge in the intersection. s (float): The parameter along the first curve of the intersection. index2 (int): The index (among 0, 1, 2) of the second edge in the intersection. t (float): The parameter along the second curve of the intersection. interior_curve (Optional[.IntersectionClassification]): The classification of the intersection, if known. If :data:`None`, the classification will be computed below. edge_nodes1 (Tuple[numpy.ndarray, numpy.ndarray, numpy.ndarray]): The nodes of the three edges of the first surface being intersected. edge_nodes2 (Tuple[numpy.ndarray, numpy.ndarray, numpy.ndarray]): The nodes of the three edges of the second surface being intersected. duplicates (List[.Intersection]): List of duplicate intersections. intersections (List[.Intersection]): List of "accepted" (i.e. non-duplicate) intersections. """ # NOTE: There is no corresponding "enable", but the disable only applies # in this lexical scope. # pylint: disable=too-many-locals edge_end, is_corner, intersection_args = _surface_helpers.handle_ends( index1, s, index2, t ) if edge_end: intersection = _intersection_helpers.Intersection(*intersection_args) intersection.interior_curve = interior_curve if interior_curve == UNUSED_T: add_edge_end_unused(intersection, duplicates, intersections) else: duplicates.append(intersection) else: intersection = _intersection_helpers.Intersection(index1, s, index2, t) if is_corner: is_duplicate = check_unused( intersection, duplicates, intersections ) if is_duplicate: return # Classify the intersection. if interior_curve is None: interior_curve = _surface_helpers.classify_intersection( intersection, edge_nodes1, edge_nodes2 ) intersection.interior_curve = interior_curve intersections.append(intersection)
[ "def", "add_intersection", "(", "# pylint: disable=too-many-arguments", "index1", ",", "s", ",", "index2", ",", "t", ",", "interior_curve", ",", "edge_nodes1", ",", "edge_nodes2", ",", "duplicates", ",", "intersections", ",", ")", ":", "# NOTE: There is no corresponding \"enable\", but the disable only applies", "# in this lexical scope.", "# pylint: disable=too-many-locals", "edge_end", ",", "is_corner", ",", "intersection_args", "=", "_surface_helpers", ".", "handle_ends", "(", "index1", ",", "s", ",", "index2", ",", "t", ")", "if", "edge_end", ":", "intersection", "=", "_intersection_helpers", ".", "Intersection", "(", "*", "intersection_args", ")", "intersection", ".", "interior_curve", "=", "interior_curve", "if", "interior_curve", "==", "UNUSED_T", ":", "add_edge_end_unused", "(", "intersection", ",", "duplicates", ",", "intersections", ")", "else", ":", "duplicates", ".", "append", "(", "intersection", ")", "else", ":", "intersection", "=", "_intersection_helpers", ".", "Intersection", "(", "index1", ",", "s", ",", "index2", ",", "t", ")", "if", "is_corner", ":", "is_duplicate", "=", "check_unused", "(", "intersection", ",", "duplicates", ",", "intersections", ")", "if", "is_duplicate", ":", "return", "# Classify the intersection.", "if", "interior_curve", "is", "None", ":", "interior_curve", "=", "_surface_helpers", ".", "classify_intersection", "(", "intersection", ",", "edge_nodes1", ",", "edge_nodes2", ")", "intersection", ".", "interior_curve", "=", "interior_curve", "intersections", ".", "append", "(", "intersection", ")" ]
Create an :class:`Intersection` and append. The intersection will be classified as either a duplicate or a valid intersection and appended to one of ``duplicates`` or ``intersections`` depending on that classification. Args: index1 (int): The index (among 0, 1, 2) of the first edge in the intersection. s (float): The parameter along the first curve of the intersection. index2 (int): The index (among 0, 1, 2) of the second edge in the intersection. t (float): The parameter along the second curve of the intersection. interior_curve (Optional[.IntersectionClassification]): The classification of the intersection, if known. If :data:`None`, the classification will be computed below. edge_nodes1 (Tuple[numpy.ndarray, numpy.ndarray, numpy.ndarray]): The nodes of the three edges of the first surface being intersected. edge_nodes2 (Tuple[numpy.ndarray, numpy.ndarray, numpy.ndarray]): The nodes of the three edges of the second surface being intersected. duplicates (List[.Intersection]): List of duplicate intersections. intersections (List[.Intersection]): List of "accepted" (i.e. non-duplicate) intersections.
[ "Create", "an", ":", "class", ":", "Intersection", "and", "append", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_surface_intersection.py#L566-L629
dhermes/bezier
src/bezier/_surface_intersection.py
classify_coincident
def classify_coincident(st_vals, coincident): r"""Determine if coincident parameters are "unused". .. note:: This is a helper for :func:`surface_intersections`. In the case that ``coincident`` is :data:`True`, then we'll have two sets of parameters :math:`(s_1, t_1)` and :math:`(s_2, t_2)`. If one of :math:`s1 < s2` or :math:`t1 < t2` is not satisfied, the coincident segments will be moving in opposite directions, hence don't define an interior of an intersection. .. warning:: In the "coincident" case, this assumes, but doesn't check, that ``st_vals`` is ``2 x 2``. Args: st_vals (numpy.ndarray): ``2 X N`` array of intersection parameters. coincident (bool): Flag indicating if the intersections are the endpoints of coincident segments of two curves. Returns: Optional[.IntersectionClassification]: The classification of the intersections. """ if not coincident: return None if st_vals[0, 0] >= st_vals[0, 1] or st_vals[1, 0] >= st_vals[1, 1]: return UNUSED_T else: return CLASSIFICATION_T.COINCIDENT
python
def classify_coincident(st_vals, coincident): r"""Determine if coincident parameters are "unused". .. note:: This is a helper for :func:`surface_intersections`. In the case that ``coincident`` is :data:`True`, then we'll have two sets of parameters :math:`(s_1, t_1)` and :math:`(s_2, t_2)`. If one of :math:`s1 < s2` or :math:`t1 < t2` is not satisfied, the coincident segments will be moving in opposite directions, hence don't define an interior of an intersection. .. warning:: In the "coincident" case, this assumes, but doesn't check, that ``st_vals`` is ``2 x 2``. Args: st_vals (numpy.ndarray): ``2 X N`` array of intersection parameters. coincident (bool): Flag indicating if the intersections are the endpoints of coincident segments of two curves. Returns: Optional[.IntersectionClassification]: The classification of the intersections. """ if not coincident: return None if st_vals[0, 0] >= st_vals[0, 1] or st_vals[1, 0] >= st_vals[1, 1]: return UNUSED_T else: return CLASSIFICATION_T.COINCIDENT
[ "def", "classify_coincident", "(", "st_vals", ",", "coincident", ")", ":", "if", "not", "coincident", ":", "return", "None", "if", "st_vals", "[", "0", ",", "0", "]", ">=", "st_vals", "[", "0", ",", "1", "]", "or", "st_vals", "[", "1", ",", "0", "]", ">=", "st_vals", "[", "1", ",", "1", "]", ":", "return", "UNUSED_T", "else", ":", "return", "CLASSIFICATION_T", ".", "COINCIDENT" ]
r"""Determine if coincident parameters are "unused". .. note:: This is a helper for :func:`surface_intersections`. In the case that ``coincident`` is :data:`True`, then we'll have two sets of parameters :math:`(s_1, t_1)` and :math:`(s_2, t_2)`. If one of :math:`s1 < s2` or :math:`t1 < t2` is not satisfied, the coincident segments will be moving in opposite directions, hence don't define an interior of an intersection. .. warning:: In the "coincident" case, this assumes, but doesn't check, that ``st_vals`` is ``2 x 2``. Args: st_vals (numpy.ndarray): ``2 X N`` array of intersection parameters. coincident (bool): Flag indicating if the intersections are the endpoints of coincident segments of two curves. Returns: Optional[.IntersectionClassification]: The classification of the intersections.
[ "r", "Determine", "if", "coincident", "parameters", "are", "unused", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_surface_intersection.py#L632-L667
dhermes/bezier
src/bezier/_surface_intersection.py
should_use
def should_use(intersection): """Check if an intersection can be used as part of a curved polygon. Will return :data:`True` if the intersection is classified as :attr:`~.IntersectionClassification.FIRST`, :attr:`~.IntersectionClassification.SECOND` or :attr:`~.IntersectionClassification.COINCIDENT` or if the intersection is classified is a corner / edge end which is classified as :attr:`~.IntersectionClassification.TANGENT_FIRST` or :attr:`~.IntersectionClassification.TANGENT_SECOND`. Args: intersection (.Intersection): An intersection to be added. Returns: bool: Indicating if the intersection will be used. """ if intersection.interior_curve in ACCEPTABLE_CLASSIFICATIONS: return True if intersection.interior_curve in TANGENT_CLASSIFICATIONS: return intersection.s == 0.0 or intersection.t == 0.0 return False
python
def should_use(intersection): """Check if an intersection can be used as part of a curved polygon. Will return :data:`True` if the intersection is classified as :attr:`~.IntersectionClassification.FIRST`, :attr:`~.IntersectionClassification.SECOND` or :attr:`~.IntersectionClassification.COINCIDENT` or if the intersection is classified is a corner / edge end which is classified as :attr:`~.IntersectionClassification.TANGENT_FIRST` or :attr:`~.IntersectionClassification.TANGENT_SECOND`. Args: intersection (.Intersection): An intersection to be added. Returns: bool: Indicating if the intersection will be used. """ if intersection.interior_curve in ACCEPTABLE_CLASSIFICATIONS: return True if intersection.interior_curve in TANGENT_CLASSIFICATIONS: return intersection.s == 0.0 or intersection.t == 0.0 return False
[ "def", "should_use", "(", "intersection", ")", ":", "if", "intersection", ".", "interior_curve", "in", "ACCEPTABLE_CLASSIFICATIONS", ":", "return", "True", "if", "intersection", ".", "interior_curve", "in", "TANGENT_CLASSIFICATIONS", ":", "return", "intersection", ".", "s", "==", "0.0", "or", "intersection", ".", "t", "==", "0.0", "return", "False" ]
Check if an intersection can be used as part of a curved polygon. Will return :data:`True` if the intersection is classified as :attr:`~.IntersectionClassification.FIRST`, :attr:`~.IntersectionClassification.SECOND` or :attr:`~.IntersectionClassification.COINCIDENT` or if the intersection is classified is a corner / edge end which is classified as :attr:`~.IntersectionClassification.TANGENT_FIRST` or :attr:`~.IntersectionClassification.TANGENT_SECOND`. Args: intersection (.Intersection): An intersection to be added. Returns: bool: Indicating if the intersection will be used.
[ "Check", "if", "an", "intersection", "can", "be", "used", "as", "part", "of", "a", "curved", "polygon", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_surface_intersection.py#L670-L693
dhermes/bezier
src/bezier/_surface_intersection.py
surface_intersections
def surface_intersections(edge_nodes1, edge_nodes2, all_intersections): """Find all intersections among edges of two surfaces. This treats intersections which have ``s == 1.0`` or ``t == 1.0`` as duplicates. The duplicates may be checked by the caller, e.g. by :func:`verify_duplicates`. Args: edge_nodes1 (Tuple[numpy.ndarray, numpy.ndarray, numpy.ndarray]): The nodes of the three edges of the first surface being intersected. edge_nodes2 (Tuple[numpy.ndarray, numpy.ndarray, numpy.ndarray]): The nodes of the three edges of the second surface being intersected. all_intersections (Callable): A helper that intersects B |eacute| zier curves. Takes the nodes of each curve as input and returns an array (``2 x N``) of intersections. Returns: Tuple[list, list, list, set]: 4-tuple of * The actual "unique" :class:`Intersection`-s * Duplicate :class:`Intersection`-s encountered (these will be corner intersections) * Intersections that won't be used, such as a tangent intersection along an edge * All the intersection classifications encountered """ # NOTE: There is no corresponding "enable", but the disable only applies # in this lexical scope. # pylint: disable=too-many-locals intersections = [] duplicates = [] for index1, nodes1 in enumerate(edge_nodes1): for index2, nodes2 in enumerate(edge_nodes2): st_vals, coincident = all_intersections(nodes1, nodes2) interior_curve = classify_coincident(st_vals, coincident) for s, t in st_vals.T: add_intersection( index1, s, index2, t, interior_curve, edge_nodes1, edge_nodes2, duplicates, intersections, ) all_types = set() to_keep = [] unused = [] for intersection in intersections: all_types.add(intersection.interior_curve) # Only keep the intersections which are "acceptable". if should_use(intersection): to_keep.append(intersection) else: unused.append(intersection) return to_keep, duplicates, unused, all_types
python
def surface_intersections(edge_nodes1, edge_nodes2, all_intersections): """Find all intersections among edges of two surfaces. This treats intersections which have ``s == 1.0`` or ``t == 1.0`` as duplicates. The duplicates may be checked by the caller, e.g. by :func:`verify_duplicates`. Args: edge_nodes1 (Tuple[numpy.ndarray, numpy.ndarray, numpy.ndarray]): The nodes of the three edges of the first surface being intersected. edge_nodes2 (Tuple[numpy.ndarray, numpy.ndarray, numpy.ndarray]): The nodes of the three edges of the second surface being intersected. all_intersections (Callable): A helper that intersects B |eacute| zier curves. Takes the nodes of each curve as input and returns an array (``2 x N``) of intersections. Returns: Tuple[list, list, list, set]: 4-tuple of * The actual "unique" :class:`Intersection`-s * Duplicate :class:`Intersection`-s encountered (these will be corner intersections) * Intersections that won't be used, such as a tangent intersection along an edge * All the intersection classifications encountered """ # NOTE: There is no corresponding "enable", but the disable only applies # in this lexical scope. # pylint: disable=too-many-locals intersections = [] duplicates = [] for index1, nodes1 in enumerate(edge_nodes1): for index2, nodes2 in enumerate(edge_nodes2): st_vals, coincident = all_intersections(nodes1, nodes2) interior_curve = classify_coincident(st_vals, coincident) for s, t in st_vals.T: add_intersection( index1, s, index2, t, interior_curve, edge_nodes1, edge_nodes2, duplicates, intersections, ) all_types = set() to_keep = [] unused = [] for intersection in intersections: all_types.add(intersection.interior_curve) # Only keep the intersections which are "acceptable". if should_use(intersection): to_keep.append(intersection) else: unused.append(intersection) return to_keep, duplicates, unused, all_types
[ "def", "surface_intersections", "(", "edge_nodes1", ",", "edge_nodes2", ",", "all_intersections", ")", ":", "# NOTE: There is no corresponding \"enable\", but the disable only applies", "# in this lexical scope.", "# pylint: disable=too-many-locals", "intersections", "=", "[", "]", "duplicates", "=", "[", "]", "for", "index1", ",", "nodes1", "in", "enumerate", "(", "edge_nodes1", ")", ":", "for", "index2", ",", "nodes2", "in", "enumerate", "(", "edge_nodes2", ")", ":", "st_vals", ",", "coincident", "=", "all_intersections", "(", "nodes1", ",", "nodes2", ")", "interior_curve", "=", "classify_coincident", "(", "st_vals", ",", "coincident", ")", "for", "s", ",", "t", "in", "st_vals", ".", "T", ":", "add_intersection", "(", "index1", ",", "s", ",", "index2", ",", "t", ",", "interior_curve", ",", "edge_nodes1", ",", "edge_nodes2", ",", "duplicates", ",", "intersections", ",", ")", "all_types", "=", "set", "(", ")", "to_keep", "=", "[", "]", "unused", "=", "[", "]", "for", "intersection", "in", "intersections", ":", "all_types", ".", "add", "(", "intersection", ".", "interior_curve", ")", "# Only keep the intersections which are \"acceptable\".", "if", "should_use", "(", "intersection", ")", ":", "to_keep", ".", "append", "(", "intersection", ")", "else", ":", "unused", ".", "append", "(", "intersection", ")", "return", "to_keep", ",", "duplicates", ",", "unused", ",", "all_types" ]
Find all intersections among edges of two surfaces. This treats intersections which have ``s == 1.0`` or ``t == 1.0`` as duplicates. The duplicates may be checked by the caller, e.g. by :func:`verify_duplicates`. Args: edge_nodes1 (Tuple[numpy.ndarray, numpy.ndarray, numpy.ndarray]): The nodes of the three edges of the first surface being intersected. edge_nodes2 (Tuple[numpy.ndarray, numpy.ndarray, numpy.ndarray]): The nodes of the three edges of the second surface being intersected. all_intersections (Callable): A helper that intersects B |eacute| zier curves. Takes the nodes of each curve as input and returns an array (``2 x N``) of intersections. Returns: Tuple[list, list, list, set]: 4-tuple of * The actual "unique" :class:`Intersection`-s * Duplicate :class:`Intersection`-s encountered (these will be corner intersections) * Intersections that won't be used, such as a tangent intersection along an edge * All the intersection classifications encountered
[ "Find", "all", "intersections", "among", "edges", "of", "two", "surfaces", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_surface_intersection.py#L696-L753
dhermes/bezier
src/bezier/_surface_intersection.py
generic_intersect
def generic_intersect( nodes1, degree1, nodes2, degree2, verify, all_intersections ): r"""Find all intersections among edges of two surfaces. This treats intersections which have ``s == 1.0`` or ``t == 1.0`` as duplicates. The duplicates will be checked by :func:`verify_duplicates` if ``verify`` is :data:`True`. Args: nodes1 (numpy.ndarray): The nodes defining the first surface in the intersection (assumed in :math:\mathbf{R}^2`). degree1 (int): The degree of the surface given by ``nodes1``. nodes2 (numpy.ndarray): The nodes defining the second surface in the intersection (assumed in :math:\mathbf{R}^2`). degree2 (int): The degree of the surface given by ``nodes2``. verify (Optional[bool]): Indicates if duplicate intersections should be checked. all_intersections (Callable): A helper that intersects B |eacute| zier curves. Takes the nodes of each curve as input and returns an array (``2 x N``) of intersections. Returns: Tuple[Optional[list], Optional[bool], tuple]: 3-tuple of * List of "edge info" lists. Each list represents a curved polygon and contains 3-tuples of edge index, start and end (see the output of :func:`ends_to_curve`). * "Contained" boolean. If not :data:`None`, indicates that one of the surfaces is contained in the other. * The nodes of three edges of the first surface being intersected followed by the nodes of the three edges of the second. """ bbox_int = _geometric_intersection.bbox_intersect(nodes1, nodes2) if bbox_int != INTERSECTION_T: return [], None, () # We need **all** edges (as nodes). edge_nodes1 = _surface_helpers.compute_edge_nodes(nodes1, degree1) edge_nodes2 = _surface_helpers.compute_edge_nodes(nodes2, degree2) # Run through **all** pairs of edges. intersections, duplicates, unused, all_types = surface_intersections( edge_nodes1, edge_nodes2, all_intersections ) edge_infos, contained = _surface_helpers.combine_intersections( intersections, nodes1, degree1, nodes2, degree2, all_types ) # Verify the duplicates and intersection if need be. if verify: verify_duplicates(duplicates, intersections + unused) verify_edge_segments(edge_infos) if edge_infos is None or edge_infos == []: return edge_infos, contained, () return edge_infos, contained, edge_nodes1 + edge_nodes2
python
def generic_intersect( nodes1, degree1, nodes2, degree2, verify, all_intersections ): r"""Find all intersections among edges of two surfaces. This treats intersections which have ``s == 1.0`` or ``t == 1.0`` as duplicates. The duplicates will be checked by :func:`verify_duplicates` if ``verify`` is :data:`True`. Args: nodes1 (numpy.ndarray): The nodes defining the first surface in the intersection (assumed in :math:\mathbf{R}^2`). degree1 (int): The degree of the surface given by ``nodes1``. nodes2 (numpy.ndarray): The nodes defining the second surface in the intersection (assumed in :math:\mathbf{R}^2`). degree2 (int): The degree of the surface given by ``nodes2``. verify (Optional[bool]): Indicates if duplicate intersections should be checked. all_intersections (Callable): A helper that intersects B |eacute| zier curves. Takes the nodes of each curve as input and returns an array (``2 x N``) of intersections. Returns: Tuple[Optional[list], Optional[bool], tuple]: 3-tuple of * List of "edge info" lists. Each list represents a curved polygon and contains 3-tuples of edge index, start and end (see the output of :func:`ends_to_curve`). * "Contained" boolean. If not :data:`None`, indicates that one of the surfaces is contained in the other. * The nodes of three edges of the first surface being intersected followed by the nodes of the three edges of the second. """ bbox_int = _geometric_intersection.bbox_intersect(nodes1, nodes2) if bbox_int != INTERSECTION_T: return [], None, () # We need **all** edges (as nodes). edge_nodes1 = _surface_helpers.compute_edge_nodes(nodes1, degree1) edge_nodes2 = _surface_helpers.compute_edge_nodes(nodes2, degree2) # Run through **all** pairs of edges. intersections, duplicates, unused, all_types = surface_intersections( edge_nodes1, edge_nodes2, all_intersections ) edge_infos, contained = _surface_helpers.combine_intersections( intersections, nodes1, degree1, nodes2, degree2, all_types ) # Verify the duplicates and intersection if need be. if verify: verify_duplicates(duplicates, intersections + unused) verify_edge_segments(edge_infos) if edge_infos is None or edge_infos == []: return edge_infos, contained, () return edge_infos, contained, edge_nodes1 + edge_nodes2
[ "def", "generic_intersect", "(", "nodes1", ",", "degree1", ",", "nodes2", ",", "degree2", ",", "verify", ",", "all_intersections", ")", ":", "bbox_int", "=", "_geometric_intersection", ".", "bbox_intersect", "(", "nodes1", ",", "nodes2", ")", "if", "bbox_int", "!=", "INTERSECTION_T", ":", "return", "[", "]", ",", "None", ",", "(", ")", "# We need **all** edges (as nodes).", "edge_nodes1", "=", "_surface_helpers", ".", "compute_edge_nodes", "(", "nodes1", ",", "degree1", ")", "edge_nodes2", "=", "_surface_helpers", ".", "compute_edge_nodes", "(", "nodes2", ",", "degree2", ")", "# Run through **all** pairs of edges.", "intersections", ",", "duplicates", ",", "unused", ",", "all_types", "=", "surface_intersections", "(", "edge_nodes1", ",", "edge_nodes2", ",", "all_intersections", ")", "edge_infos", ",", "contained", "=", "_surface_helpers", ".", "combine_intersections", "(", "intersections", ",", "nodes1", ",", "degree1", ",", "nodes2", ",", "degree2", ",", "all_types", ")", "# Verify the duplicates and intersection if need be.", "if", "verify", ":", "verify_duplicates", "(", "duplicates", ",", "intersections", "+", "unused", ")", "verify_edge_segments", "(", "edge_infos", ")", "if", "edge_infos", "is", "None", "or", "edge_infos", "==", "[", "]", ":", "return", "edge_infos", ",", "contained", ",", "(", ")", "return", "edge_infos", ",", "contained", ",", "edge_nodes1", "+", "edge_nodes2" ]
r"""Find all intersections among edges of two surfaces. This treats intersections which have ``s == 1.0`` or ``t == 1.0`` as duplicates. The duplicates will be checked by :func:`verify_duplicates` if ``verify`` is :data:`True`. Args: nodes1 (numpy.ndarray): The nodes defining the first surface in the intersection (assumed in :math:\mathbf{R}^2`). degree1 (int): The degree of the surface given by ``nodes1``. nodes2 (numpy.ndarray): The nodes defining the second surface in the intersection (assumed in :math:\mathbf{R}^2`). degree2 (int): The degree of the surface given by ``nodes2``. verify (Optional[bool]): Indicates if duplicate intersections should be checked. all_intersections (Callable): A helper that intersects B |eacute| zier curves. Takes the nodes of each curve as input and returns an array (``2 x N``) of intersections. Returns: Tuple[Optional[list], Optional[bool], tuple]: 3-tuple of * List of "edge info" lists. Each list represents a curved polygon and contains 3-tuples of edge index, start and end (see the output of :func:`ends_to_curve`). * "Contained" boolean. If not :data:`None`, indicates that one of the surfaces is contained in the other. * The nodes of three edges of the first surface being intersected followed by the nodes of the three edges of the second.
[ "r", "Find", "all", "intersections", "among", "edges", "of", "two", "surfaces", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_surface_intersection.py#L756-L810
dhermes/bezier
src/bezier/_surface_intersection.py
_geometric_intersect
def _geometric_intersect(nodes1, degree1, nodes2, degree2, verify): r"""Find all intersections among edges of two surfaces. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Uses :func:`generic_intersect` with the :attr:`~.IntersectionStrategy.GEOMETRIC` intersection strategy. Args: nodes1 (numpy.ndarray): The nodes defining the first surface in the intersection (assumed in :math:\mathbf{R}^2`). degree1 (int): The degree of the surface given by ``nodes1``. nodes2 (numpy.ndarray): The nodes defining the second surface in the intersection (assumed in :math:\mathbf{R}^2`). degree2 (int): The degree of the surface given by ``nodes2``. verify (Optional[bool]): Indicates if duplicate intersections should be checked. Returns: Tuple[Optional[list], Optional[bool], tuple]: 3-tuple of * List of "edge info" lists. Each list represents a curved polygon and contains 3-tuples of edge index, start and end (see the output of :func:`ends_to_curve`). * "Contained" boolean. If not :data:`None`, indicates that one of the surfaces is contained in the other. * The nodes of three edges of the first surface being intersected followed by the nodes of the three edges of the second. """ all_intersections = _geometric_intersection.all_intersections return generic_intersect( nodes1, degree1, nodes2, degree2, verify, all_intersections )
python
def _geometric_intersect(nodes1, degree1, nodes2, degree2, verify): r"""Find all intersections among edges of two surfaces. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Uses :func:`generic_intersect` with the :attr:`~.IntersectionStrategy.GEOMETRIC` intersection strategy. Args: nodes1 (numpy.ndarray): The nodes defining the first surface in the intersection (assumed in :math:\mathbf{R}^2`). degree1 (int): The degree of the surface given by ``nodes1``. nodes2 (numpy.ndarray): The nodes defining the second surface in the intersection (assumed in :math:\mathbf{R}^2`). degree2 (int): The degree of the surface given by ``nodes2``. verify (Optional[bool]): Indicates if duplicate intersections should be checked. Returns: Tuple[Optional[list], Optional[bool], tuple]: 3-tuple of * List of "edge info" lists. Each list represents a curved polygon and contains 3-tuples of edge index, start and end (see the output of :func:`ends_to_curve`). * "Contained" boolean. If not :data:`None`, indicates that one of the surfaces is contained in the other. * The nodes of three edges of the first surface being intersected followed by the nodes of the three edges of the second. """ all_intersections = _geometric_intersection.all_intersections return generic_intersect( nodes1, degree1, nodes2, degree2, verify, all_intersections )
[ "def", "_geometric_intersect", "(", "nodes1", ",", "degree1", ",", "nodes2", ",", "degree2", ",", "verify", ")", ":", "all_intersections", "=", "_geometric_intersection", ".", "all_intersections", "return", "generic_intersect", "(", "nodes1", ",", "degree1", ",", "nodes2", ",", "degree2", ",", "verify", ",", "all_intersections", ")" ]
r"""Find all intersections among edges of two surfaces. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Uses :func:`generic_intersect` with the :attr:`~.IntersectionStrategy.GEOMETRIC` intersection strategy. Args: nodes1 (numpy.ndarray): The nodes defining the first surface in the intersection (assumed in :math:\mathbf{R}^2`). degree1 (int): The degree of the surface given by ``nodes1``. nodes2 (numpy.ndarray): The nodes defining the second surface in the intersection (assumed in :math:\mathbf{R}^2`). degree2 (int): The degree of the surface given by ``nodes2``. verify (Optional[bool]): Indicates if duplicate intersections should be checked. Returns: Tuple[Optional[list], Optional[bool], tuple]: 3-tuple of * List of "edge info" lists. Each list represents a curved polygon and contains 3-tuples of edge index, start and end (see the output of :func:`ends_to_curve`). * "Contained" boolean. If not :data:`None`, indicates that one of the surfaces is contained in the other. * The nodes of three edges of the first surface being intersected followed by the nodes of the three edges of the second.
[ "r", "Find", "all", "intersections", "among", "edges", "of", "two", "surfaces", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_surface_intersection.py#L813-L848
dhermes/bezier
src/bezier/_surface_intersection.py
algebraic_intersect
def algebraic_intersect(nodes1, degree1, nodes2, degree2, verify): r"""Find all intersections among edges of two surfaces. Uses :func:`generic_intersect` with the :attr:`~.IntersectionStrategy.ALGEBRAIC` intersection strategy. Args: nodes1 (numpy.ndarray): The nodes defining the first surface in the intersection (assumed in :math:\mathbf{R}^2`). degree1 (int): The degree of the surface given by ``nodes1``. nodes2 (numpy.ndarray): The nodes defining the second surface in the intersection (assumed in :math:\mathbf{R}^2`). degree2 (int): The degree of the surface given by ``nodes2``. verify (Optional[bool]): Indicates if duplicate intersections should be checked. Returns: Tuple[Optional[list], Optional[bool], tuple]: 3-tuple of * List of "edge info" lists. Each list represents a curved polygon and contains 3-tuples of edge index, start and end (see the output of :func:`ends_to_curve`). * "Contained" boolean. If not :data:`None`, indicates that one of the surfaces is contained in the other. * The nodes of three edges of the first surface being intersected followed by the nodes of the three edges of the second. """ all_intersections = _algebraic_intersection.all_intersections return generic_intersect( nodes1, degree1, nodes2, degree2, verify, all_intersections )
python
def algebraic_intersect(nodes1, degree1, nodes2, degree2, verify): r"""Find all intersections among edges of two surfaces. Uses :func:`generic_intersect` with the :attr:`~.IntersectionStrategy.ALGEBRAIC` intersection strategy. Args: nodes1 (numpy.ndarray): The nodes defining the first surface in the intersection (assumed in :math:\mathbf{R}^2`). degree1 (int): The degree of the surface given by ``nodes1``. nodes2 (numpy.ndarray): The nodes defining the second surface in the intersection (assumed in :math:\mathbf{R}^2`). degree2 (int): The degree of the surface given by ``nodes2``. verify (Optional[bool]): Indicates if duplicate intersections should be checked. Returns: Tuple[Optional[list], Optional[bool], tuple]: 3-tuple of * List of "edge info" lists. Each list represents a curved polygon and contains 3-tuples of edge index, start and end (see the output of :func:`ends_to_curve`). * "Contained" boolean. If not :data:`None`, indicates that one of the surfaces is contained in the other. * The nodes of three edges of the first surface being intersected followed by the nodes of the three edges of the second. """ all_intersections = _algebraic_intersection.all_intersections return generic_intersect( nodes1, degree1, nodes2, degree2, verify, all_intersections )
[ "def", "algebraic_intersect", "(", "nodes1", ",", "degree1", ",", "nodes2", ",", "degree2", ",", "verify", ")", ":", "all_intersections", "=", "_algebraic_intersection", ".", "all_intersections", "return", "generic_intersect", "(", "nodes1", ",", "degree1", ",", "nodes2", ",", "degree2", ",", "verify", ",", "all_intersections", ")" ]
r"""Find all intersections among edges of two surfaces. Uses :func:`generic_intersect` with the :attr:`~.IntersectionStrategy.ALGEBRAIC` intersection strategy. Args: nodes1 (numpy.ndarray): The nodes defining the first surface in the intersection (assumed in :math:\mathbf{R}^2`). degree1 (int): The degree of the surface given by ``nodes1``. nodes2 (numpy.ndarray): The nodes defining the second surface in the intersection (assumed in :math:\mathbf{R}^2`). degree2 (int): The degree of the surface given by ``nodes2``. verify (Optional[bool]): Indicates if duplicate intersections should be checked. Returns: Tuple[Optional[list], Optional[bool], tuple]: 3-tuple of * List of "edge info" lists. Each list represents a curved polygon and contains 3-tuples of edge index, start and end (see the output of :func:`ends_to_curve`). * "Contained" boolean. If not :data:`None`, indicates that one of the surfaces is contained in the other. * The nodes of three edges of the first surface being intersected followed by the nodes of the three edges of the second.
[ "r", "Find", "all", "intersections", "among", "edges", "of", "two", "surfaces", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_surface_intersection.py#L851-L881
dhermes/bezier
src/bezier/__config__.py
modify_path
def modify_path(): """Modify the module search path.""" # Only modify path on Windows. if os.name != "nt": return path = os.environ.get("PATH") if path is None: return try: extra_dll_dir = pkg_resources.resource_filename("bezier", "extra-dll") if os.path.isdir(extra_dll_dir): os.environ["PATH"] = path + os.pathsep + extra_dll_dir except ImportError: pass
python
def modify_path(): """Modify the module search path.""" # Only modify path on Windows. if os.name != "nt": return path = os.environ.get("PATH") if path is None: return try: extra_dll_dir = pkg_resources.resource_filename("bezier", "extra-dll") if os.path.isdir(extra_dll_dir): os.environ["PATH"] = path + os.pathsep + extra_dll_dir except ImportError: pass
[ "def", "modify_path", "(", ")", ":", "# Only modify path on Windows.", "if", "os", ".", "name", "!=", "\"nt\"", ":", "return", "path", "=", "os", ".", "environ", ".", "get", "(", "\"PATH\"", ")", "if", "path", "is", "None", ":", "return", "try", ":", "extra_dll_dir", "=", "pkg_resources", ".", "resource_filename", "(", "\"bezier\"", ",", "\"extra-dll\"", ")", "if", "os", ".", "path", ".", "isdir", "(", "extra_dll_dir", ")", ":", "os", ".", "environ", "[", "\"PATH\"", "]", "=", "path", "+", "os", ".", "pathsep", "+", "extra_dll_dir", "except", "ImportError", ":", "pass" ]
Modify the module search path.
[ "Modify", "the", "module", "search", "path", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/__config__.py#L30-L45
dhermes/bezier
src/bezier/__config__.py
handle_import_error
def handle_import_error(caught_exc, name): """Allow or re-raise an import error. This is to distinguish between expected and unexpected import errors. If the module is not found, it simply means the Cython / Fortran speedups were not built with the package. If the error message is different, e.g. ``... undefined symbol: __curve_intersection_MOD_all_intersections``, then the import error **should** be raised. Args: caught_exc (ImportError): An exception caught when trying to import a Cython module. name (str): The name of the module. For example, for the module ``bezier._curve_speedup``, the name is ``"_curve_speedup"``. Raises: ImportError: If the error message is different than the basic "missing module" error message. """ for template in TEMPLATES: expected_msg = template.format(name) if caught_exc.args == (expected_msg,): return raise caught_exc
python
def handle_import_error(caught_exc, name): """Allow or re-raise an import error. This is to distinguish between expected and unexpected import errors. If the module is not found, it simply means the Cython / Fortran speedups were not built with the package. If the error message is different, e.g. ``... undefined symbol: __curve_intersection_MOD_all_intersections``, then the import error **should** be raised. Args: caught_exc (ImportError): An exception caught when trying to import a Cython module. name (str): The name of the module. For example, for the module ``bezier._curve_speedup``, the name is ``"_curve_speedup"``. Raises: ImportError: If the error message is different than the basic "missing module" error message. """ for template in TEMPLATES: expected_msg = template.format(name) if caught_exc.args == (expected_msg,): return raise caught_exc
[ "def", "handle_import_error", "(", "caught_exc", ",", "name", ")", ":", "for", "template", "in", "TEMPLATES", ":", "expected_msg", "=", "template", ".", "format", "(", "name", ")", "if", "caught_exc", ".", "args", "==", "(", "expected_msg", ",", ")", ":", "return", "raise", "caught_exc" ]
Allow or re-raise an import error. This is to distinguish between expected and unexpected import errors. If the module is not found, it simply means the Cython / Fortran speedups were not built with the package. If the error message is different, e.g. ``... undefined symbol: __curve_intersection_MOD_all_intersections``, then the import error **should** be raised. Args: caught_exc (ImportError): An exception caught when trying to import a Cython module. name (str): The name of the module. For example, for the module ``bezier._curve_speedup``, the name is ``"_curve_speedup"``. Raises: ImportError: If the error message is different than the basic "missing module" error message.
[ "Allow", "or", "re", "-", "raise", "an", "import", "error", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/__config__.py#L48-L72
dhermes/bezier
setup_helpers_macos.py
is_macos_gfortran
def is_macos_gfortran(f90_compiler): """Checks if the current build is ``gfortran`` on macOS. Args: f90_compiler (numpy.distutils.fcompiler.FCompiler): A Fortran compiler instance. Returns: bool: Only :data:`True` if * Current OS is macOS (checked via ``sys.platform``). * ``f90_compiler`` corresponds to ``gfortran``. """ # NOTE: NumPy may not be installed, but we don't want **this** module to # cause an import failure. from numpy.distutils.fcompiler import gnu # Only macOS. if sys.platform != MAC_OS: return False # Only ``gfortran``. if not isinstance(f90_compiler, gnu.Gnu95FCompiler): return False return True
python
def is_macos_gfortran(f90_compiler): """Checks if the current build is ``gfortran`` on macOS. Args: f90_compiler (numpy.distutils.fcompiler.FCompiler): A Fortran compiler instance. Returns: bool: Only :data:`True` if * Current OS is macOS (checked via ``sys.platform``). * ``f90_compiler`` corresponds to ``gfortran``. """ # NOTE: NumPy may not be installed, but we don't want **this** module to # cause an import failure. from numpy.distutils.fcompiler import gnu # Only macOS. if sys.platform != MAC_OS: return False # Only ``gfortran``. if not isinstance(f90_compiler, gnu.Gnu95FCompiler): return False return True
[ "def", "is_macos_gfortran", "(", "f90_compiler", ")", ":", "# NOTE: NumPy may not be installed, but we don't want **this** module to", "# cause an import failure.", "from", "numpy", ".", "distutils", ".", "fcompiler", "import", "gnu", "# Only macOS.", "if", "sys", ".", "platform", "!=", "MAC_OS", ":", "return", "False", "# Only ``gfortran``.", "if", "not", "isinstance", "(", "f90_compiler", ",", "gnu", ".", "Gnu95FCompiler", ")", ":", "return", "False", "return", "True" ]
Checks if the current build is ``gfortran`` on macOS. Args: f90_compiler (numpy.distutils.fcompiler.FCompiler): A Fortran compiler instance. Returns: bool: Only :data:`True` if * Current OS is macOS (checked via ``sys.platform``). * ``f90_compiler`` corresponds to ``gfortran``.
[ "Checks", "if", "the", "current", "build", "is", "gfortran", "on", "macOS", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/setup_helpers_macos.py#L23-L48
dhermes/bezier
setup_helpers_macos.py
patch_f90_compiler
def patch_f90_compiler(f90_compiler): """Patch up ``f90_compiler.library_dirs``. On macOS, a Homebrew installed ``gfortran`` needs some help. The ``numpy.distutils`` "default" constructor for ``Gnu95FCompiler`` only has a single library search path, but there are many library paths included in the full ``gcc`` install. Args: f90_compiler (numpy.distutils.fcompiler.FCompiler): A Fortran compiler instance. """ if not is_macos_gfortran(f90_compiler): return library_dirs = f90_compiler.library_dirs # ``library_dirs`` is a list (i.e. mutable), so we can update in place. library_dirs[:] = setup_helpers.gfortran_search_path(library_dirs)
python
def patch_f90_compiler(f90_compiler): """Patch up ``f90_compiler.library_dirs``. On macOS, a Homebrew installed ``gfortran`` needs some help. The ``numpy.distutils`` "default" constructor for ``Gnu95FCompiler`` only has a single library search path, but there are many library paths included in the full ``gcc`` install. Args: f90_compiler (numpy.distutils.fcompiler.FCompiler): A Fortran compiler instance. """ if not is_macos_gfortran(f90_compiler): return library_dirs = f90_compiler.library_dirs # ``library_dirs`` is a list (i.e. mutable), so we can update in place. library_dirs[:] = setup_helpers.gfortran_search_path(library_dirs)
[ "def", "patch_f90_compiler", "(", "f90_compiler", ")", ":", "if", "not", "is_macos_gfortran", "(", "f90_compiler", ")", ":", "return", "library_dirs", "=", "f90_compiler", ".", "library_dirs", "# ``library_dirs`` is a list (i.e. mutable), so we can update in place.", "library_dirs", "[", ":", "]", "=", "setup_helpers", ".", "gfortran_search_path", "(", "library_dirs", ")" ]
Patch up ``f90_compiler.library_dirs``. On macOS, a Homebrew installed ``gfortran`` needs some help. The ``numpy.distutils`` "default" constructor for ``Gnu95FCompiler`` only has a single library search path, but there are many library paths included in the full ``gcc`` install. Args: f90_compiler (numpy.distutils.fcompiler.FCompiler): A Fortran compiler instance.
[ "Patch", "up", "f90_compiler", ".", "library_dirs", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/setup_helpers_macos.py#L51-L68
dhermes/bezier
src/bezier/surface.py
_make_intersection
def _make_intersection(edge_info, all_edge_nodes): """Convert a description of edges into a curved polygon. .. note:: This is a helper used only by :meth:`.Surface.intersect`. Args: edge_info (Tuple[Tuple[int, float, float], ...]): Information describing each edge in the curved polygon by indicating which surface / edge on the surface and then start and end parameters along that edge. (See :func:`.ends_to_curve`.) all_edge_nodes (Tuple[numpy.ndarray, ...]): The nodes of three edges of the first surface being intersected followed by the nodes of the three edges of the second. Returns: .CurvedPolygon: The intersection corresponding to ``edge_info``. """ edges = [] for index, start, end in edge_info: nodes = all_edge_nodes[index] new_nodes = _curve_helpers.specialize_curve(nodes, start, end) degree = new_nodes.shape[1] - 1 edge = _curve_mod.Curve(new_nodes, degree, _copy=False) edges.append(edge) return curved_polygon.CurvedPolygon( *edges, metadata=edge_info, _verify=False )
python
def _make_intersection(edge_info, all_edge_nodes): """Convert a description of edges into a curved polygon. .. note:: This is a helper used only by :meth:`.Surface.intersect`. Args: edge_info (Tuple[Tuple[int, float, float], ...]): Information describing each edge in the curved polygon by indicating which surface / edge on the surface and then start and end parameters along that edge. (See :func:`.ends_to_curve`.) all_edge_nodes (Tuple[numpy.ndarray, ...]): The nodes of three edges of the first surface being intersected followed by the nodes of the three edges of the second. Returns: .CurvedPolygon: The intersection corresponding to ``edge_info``. """ edges = [] for index, start, end in edge_info: nodes = all_edge_nodes[index] new_nodes = _curve_helpers.specialize_curve(nodes, start, end) degree = new_nodes.shape[1] - 1 edge = _curve_mod.Curve(new_nodes, degree, _copy=False) edges.append(edge) return curved_polygon.CurvedPolygon( *edges, metadata=edge_info, _verify=False )
[ "def", "_make_intersection", "(", "edge_info", ",", "all_edge_nodes", ")", ":", "edges", "=", "[", "]", "for", "index", ",", "start", ",", "end", "in", "edge_info", ":", "nodes", "=", "all_edge_nodes", "[", "index", "]", "new_nodes", "=", "_curve_helpers", ".", "specialize_curve", "(", "nodes", ",", "start", ",", "end", ")", "degree", "=", "new_nodes", ".", "shape", "[", "1", "]", "-", "1", "edge", "=", "_curve_mod", ".", "Curve", "(", "new_nodes", ",", "degree", ",", "_copy", "=", "False", ")", "edges", ".", "append", "(", "edge", ")", "return", "curved_polygon", ".", "CurvedPolygon", "(", "*", "edges", ",", "metadata", "=", "edge_info", ",", "_verify", "=", "False", ")" ]
Convert a description of edges into a curved polygon. .. note:: This is a helper used only by :meth:`.Surface.intersect`. Args: edge_info (Tuple[Tuple[int, float, float], ...]): Information describing each edge in the curved polygon by indicating which surface / edge on the surface and then start and end parameters along that edge. (See :func:`.ends_to_curve`.) all_edge_nodes (Tuple[numpy.ndarray, ...]): The nodes of three edges of the first surface being intersected followed by the nodes of the three edges of the second. Returns: .CurvedPolygon: The intersection corresponding to ``edge_info``.
[ "Convert", "a", "description", "of", "edges", "into", "a", "curved", "polygon", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/surface.py#L1100-L1128
dhermes/bezier
src/bezier/surface.py
Surface.from_nodes
def from_nodes(cls, nodes, _copy=True): """Create a :class:`.Surface` from nodes. Computes the ``degree`` based on the shape of ``nodes``. Args: nodes (numpy.ndarray): The nodes in the surface. The columns represent each node while the rows are the dimension of the ambient space. _copy (bool): Flag indicating if the nodes should be copied before being stored. Defaults to :data:`True` since callers may freely mutate ``nodes`` after passing in. Returns: Surface: The constructed surface. """ _, num_nodes = nodes.shape degree = cls._get_degree(num_nodes) return cls(nodes, degree, _copy=_copy)
python
def from_nodes(cls, nodes, _copy=True): """Create a :class:`.Surface` from nodes. Computes the ``degree`` based on the shape of ``nodes``. Args: nodes (numpy.ndarray): The nodes in the surface. The columns represent each node while the rows are the dimension of the ambient space. _copy (bool): Flag indicating if the nodes should be copied before being stored. Defaults to :data:`True` since callers may freely mutate ``nodes`` after passing in. Returns: Surface: The constructed surface. """ _, num_nodes = nodes.shape degree = cls._get_degree(num_nodes) return cls(nodes, degree, _copy=_copy)
[ "def", "from_nodes", "(", "cls", ",", "nodes", ",", "_copy", "=", "True", ")", ":", "_", ",", "num_nodes", "=", "nodes", ".", "shape", "degree", "=", "cls", ".", "_get_degree", "(", "num_nodes", ")", "return", "cls", "(", "nodes", ",", "degree", ",", "_copy", "=", "_copy", ")" ]
Create a :class:`.Surface` from nodes. Computes the ``degree`` based on the shape of ``nodes``. Args: nodes (numpy.ndarray): The nodes in the surface. The columns represent each node while the rows are the dimension of the ambient space. _copy (bool): Flag indicating if the nodes should be copied before being stored. Defaults to :data:`True` since callers may freely mutate ``nodes`` after passing in. Returns: Surface: The constructed surface.
[ "Create", "a", ":", "class", ":", ".", "Surface", "from", "nodes", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/surface.py#L193-L211
dhermes/bezier
src/bezier/surface.py
Surface._get_degree
def _get_degree(num_nodes): """Get the degree of the current surface. Args: num_nodes (int): The number of control points for a B |eacute| zier surface. Returns: int: The degree :math:`d` such that :math:`(d + 1)(d + 2)/2` equals ``num_nodes``. Raises: ValueError: If ``num_nodes`` isn't a triangular number. """ # 8 * num_nodes = 4(d + 1)(d + 2) # = 4d^2 + 12d + 8 # = (2d + 3)^2 - 1 d_float = 0.5 * (np.sqrt(8.0 * num_nodes + 1.0) - 3.0) d_int = int(np.round(d_float)) if (d_int + 1) * (d_int + 2) == 2 * num_nodes: return d_int else: raise ValueError(num_nodes, "not a triangular number")
python
def _get_degree(num_nodes): """Get the degree of the current surface. Args: num_nodes (int): The number of control points for a B |eacute| zier surface. Returns: int: The degree :math:`d` such that :math:`(d + 1)(d + 2)/2` equals ``num_nodes``. Raises: ValueError: If ``num_nodes`` isn't a triangular number. """ # 8 * num_nodes = 4(d + 1)(d + 2) # = 4d^2 + 12d + 8 # = (2d + 3)^2 - 1 d_float = 0.5 * (np.sqrt(8.0 * num_nodes + 1.0) - 3.0) d_int = int(np.round(d_float)) if (d_int + 1) * (d_int + 2) == 2 * num_nodes: return d_int else: raise ValueError(num_nodes, "not a triangular number")
[ "def", "_get_degree", "(", "num_nodes", ")", ":", "# 8 * num_nodes = 4(d + 1)(d + 2)", "# = 4d^2 + 12d + 8", "# = (2d + 3)^2 - 1", "d_float", "=", "0.5", "*", "(", "np", ".", "sqrt", "(", "8.0", "*", "num_nodes", "+", "1.0", ")", "-", "3.0", ")", "d_int", "=", "int", "(", "np", ".", "round", "(", "d_float", ")", ")", "if", "(", "d_int", "+", "1", ")", "*", "(", "d_int", "+", "2", ")", "==", "2", "*", "num_nodes", ":", "return", "d_int", "else", ":", "raise", "ValueError", "(", "num_nodes", ",", "\"not a triangular number\"", ")" ]
Get the degree of the current surface. Args: num_nodes (int): The number of control points for a B |eacute| zier surface. Returns: int: The degree :math:`d` such that :math:`(d + 1)(d + 2)/2` equals ``num_nodes``. Raises: ValueError: If ``num_nodes`` isn't a triangular number.
[ "Get", "the", "degree", "of", "the", "current", "surface", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/surface.py#L214-L237
dhermes/bezier
src/bezier/surface.py
Surface.area
def area(self): r"""The area of the current surface. For surfaces in :math:`\mathbf{R}^2`, this computes the area via Green's theorem. Using the vector field :math:`\mathbf{F} = \left[-y, x\right]^T`, since :math:`\partial_x(x) - \partial_y(-y) = 2` Green's theorem says twice the area is equal to .. math:: \int_{B\left(\mathcal{U}\right)} 2 \, d\mathbf{x} = \int_{\partial B\left(\mathcal{U}\right)} -y \, dx + x \, dy. This relies on the assumption that the current surface is valid, which implies that the image of the unit triangle under the B |eacute| zier map --- :math:`B\left(\mathcal{U}\right)` --- has the edges of the surface as its boundary. Note that for a given edge :math:`C(r)` with control points :math:`x_j, y_j`, the integral can be simplified: .. math:: \int_C -y \, dx + x \, dy = \int_0^1 (x y' - y x') \, dr = \sum_{i < j} (x_i y_j - y_i x_j) \int_0^1 b_{i, d} b'_{j, d} \, dr where :math:`b_{i, d}, b_{j, d}` are Bernstein basis polynomials. Returns: float: The area of the current surface. Raises: NotImplementedError: If the current surface isn't in :math:`\mathbf{R}^2`. """ if self._dimension != 2: raise NotImplementedError( "2D is the only supported dimension", "Current dimension", self._dimension, ) edge1, edge2, edge3 = self._get_edges() return _surface_helpers.compute_area( (edge1._nodes, edge2._nodes, edge3._nodes) )
python
def area(self): r"""The area of the current surface. For surfaces in :math:`\mathbf{R}^2`, this computes the area via Green's theorem. Using the vector field :math:`\mathbf{F} = \left[-y, x\right]^T`, since :math:`\partial_x(x) - \partial_y(-y) = 2` Green's theorem says twice the area is equal to .. math:: \int_{B\left(\mathcal{U}\right)} 2 \, d\mathbf{x} = \int_{\partial B\left(\mathcal{U}\right)} -y \, dx + x \, dy. This relies on the assumption that the current surface is valid, which implies that the image of the unit triangle under the B |eacute| zier map --- :math:`B\left(\mathcal{U}\right)` --- has the edges of the surface as its boundary. Note that for a given edge :math:`C(r)` with control points :math:`x_j, y_j`, the integral can be simplified: .. math:: \int_C -y \, dx + x \, dy = \int_0^1 (x y' - y x') \, dr = \sum_{i < j} (x_i y_j - y_i x_j) \int_0^1 b_{i, d} b'_{j, d} \, dr where :math:`b_{i, d}, b_{j, d}` are Bernstein basis polynomials. Returns: float: The area of the current surface. Raises: NotImplementedError: If the current surface isn't in :math:`\mathbf{R}^2`. """ if self._dimension != 2: raise NotImplementedError( "2D is the only supported dimension", "Current dimension", self._dimension, ) edge1, edge2, edge3 = self._get_edges() return _surface_helpers.compute_area( (edge1._nodes, edge2._nodes, edge3._nodes) )
[ "def", "area", "(", "self", ")", ":", "if", "self", ".", "_dimension", "!=", "2", ":", "raise", "NotImplementedError", "(", "\"2D is the only supported dimension\"", ",", "\"Current dimension\"", ",", "self", ".", "_dimension", ",", ")", "edge1", ",", "edge2", ",", "edge3", "=", "self", ".", "_get_edges", "(", ")", "return", "_surface_helpers", ".", "compute_area", "(", "(", "edge1", ".", "_nodes", ",", "edge2", ".", "_nodes", ",", "edge3", ".", "_nodes", ")", ")" ]
r"""The area of the current surface. For surfaces in :math:`\mathbf{R}^2`, this computes the area via Green's theorem. Using the vector field :math:`\mathbf{F} = \left[-y, x\right]^T`, since :math:`\partial_x(x) - \partial_y(-y) = 2` Green's theorem says twice the area is equal to .. math:: \int_{B\left(\mathcal{U}\right)} 2 \, d\mathbf{x} = \int_{\partial B\left(\mathcal{U}\right)} -y \, dx + x \, dy. This relies on the assumption that the current surface is valid, which implies that the image of the unit triangle under the B |eacute| zier map --- :math:`B\left(\mathcal{U}\right)` --- has the edges of the surface as its boundary. Note that for a given edge :math:`C(r)` with control points :math:`x_j, y_j`, the integral can be simplified: .. math:: \int_C -y \, dx + x \, dy = \int_0^1 (x y' - y x') \, dr = \sum_{i < j} (x_i y_j - y_i x_j) \int_0^1 b_{i, d} b'_{j, d} \, dr where :math:`b_{i, d}, b_{j, d}` are Bernstein basis polynomials. Returns: float: The area of the current surface. Raises: NotImplementedError: If the current surface isn't in :math:`\mathbf{R}^2`.
[ "r", "The", "area", "of", "the", "current", "surface", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/surface.py#L240-L286
dhermes/bezier
src/bezier/surface.py
Surface._compute_edges
def _compute_edges(self): """Compute the edges of the current surface. Returns: Tuple[~curve.Curve, ~curve.Curve, ~curve.Curve]: The edges of the surface. """ nodes1, nodes2, nodes3 = _surface_helpers.compute_edge_nodes( self._nodes, self._degree ) edge1 = _curve_mod.Curve(nodes1, self._degree, _copy=False) edge2 = _curve_mod.Curve(nodes2, self._degree, _copy=False) edge3 = _curve_mod.Curve(nodes3, self._degree, _copy=False) return edge1, edge2, edge3
python
def _compute_edges(self): """Compute the edges of the current surface. Returns: Tuple[~curve.Curve, ~curve.Curve, ~curve.Curve]: The edges of the surface. """ nodes1, nodes2, nodes3 = _surface_helpers.compute_edge_nodes( self._nodes, self._degree ) edge1 = _curve_mod.Curve(nodes1, self._degree, _copy=False) edge2 = _curve_mod.Curve(nodes2, self._degree, _copy=False) edge3 = _curve_mod.Curve(nodes3, self._degree, _copy=False) return edge1, edge2, edge3
[ "def", "_compute_edges", "(", "self", ")", ":", "nodes1", ",", "nodes2", ",", "nodes3", "=", "_surface_helpers", ".", "compute_edge_nodes", "(", "self", ".", "_nodes", ",", "self", ".", "_degree", ")", "edge1", "=", "_curve_mod", ".", "Curve", "(", "nodes1", ",", "self", ".", "_degree", ",", "_copy", "=", "False", ")", "edge2", "=", "_curve_mod", ".", "Curve", "(", "nodes2", ",", "self", ".", "_degree", ",", "_copy", "=", "False", ")", "edge3", "=", "_curve_mod", ".", "Curve", "(", "nodes3", ",", "self", ".", "_degree", ",", "_copy", "=", "False", ")", "return", "edge1", ",", "edge2", ",", "edge3" ]
Compute the edges of the current surface. Returns: Tuple[~curve.Curve, ~curve.Curve, ~curve.Curve]: The edges of the surface.
[ "Compute", "the", "edges", "of", "the", "current", "surface", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/surface.py#L288-L301
dhermes/bezier
src/bezier/surface.py
Surface._get_edges
def _get_edges(self): """Get the edges for the current surface. If they haven't been computed yet, first compute and store them. This is provided as a means for internal calls to get the edges without copying (since :attr:`.edges` copies before giving to a user to keep the stored data immutable). Returns: Tuple[~bezier.curve.Curve, ~bezier.curve.Curve, \ ~bezier.curve.Curve]: The edges of the surface. """ if self._edges is None: self._edges = self._compute_edges() return self._edges
python
def _get_edges(self): """Get the edges for the current surface. If they haven't been computed yet, first compute and store them. This is provided as a means for internal calls to get the edges without copying (since :attr:`.edges` copies before giving to a user to keep the stored data immutable). Returns: Tuple[~bezier.curve.Curve, ~bezier.curve.Curve, \ ~bezier.curve.Curve]: The edges of the surface. """ if self._edges is None: self._edges = self._compute_edges() return self._edges
[ "def", "_get_edges", "(", "self", ")", ":", "if", "self", ".", "_edges", "is", "None", ":", "self", ".", "_edges", "=", "self", ".", "_compute_edges", "(", ")", "return", "self", ".", "_edges" ]
Get the edges for the current surface. If they haven't been computed yet, first compute and store them. This is provided as a means for internal calls to get the edges without copying (since :attr:`.edges` copies before giving to a user to keep the stored data immutable). Returns: Tuple[~bezier.curve.Curve, ~bezier.curve.Curve, \ ~bezier.curve.Curve]: The edges of the surface.
[ "Get", "the", "edges", "for", "the", "current", "surface", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/surface.py#L303-L319
dhermes/bezier
src/bezier/surface.py
Surface.edges
def edges(self): """The edges of the surface. .. doctest:: surface-edges :options: +NORMALIZE_WHITESPACE >>> nodes = np.asfortranarray([ ... [0.0, 0.5 , 1.0, 0.1875, 0.625, 0.0], ... [0.0, -0.1875, 0.0, 0.5 , 0.625, 1.0], ... ]) >>> surface = bezier.Surface(nodes, degree=2) >>> edge1, _, _ = surface.edges >>> edge1 <Curve (degree=2, dimension=2)> >>> edge1.nodes array([[ 0. , 0.5 , 1. ], [ 0. , -0.1875, 0. ]]) Returns: Tuple[~bezier.curve.Curve, ~bezier.curve.Curve, \ ~bezier.curve.Curve]: The edges of the surface. """ edge1, edge2, edge3 = self._get_edges() # NOTE: It is crucial that we return copies here. Since the edges # are cached, if they were mutable, callers could # inadvertently mutate the cached value. edge1 = edge1._copy() # pylint: disable=protected-access edge2 = edge2._copy() # pylint: disable=protected-access edge3 = edge3._copy() # pylint: disable=protected-access return edge1, edge2, edge3
python
def edges(self): """The edges of the surface. .. doctest:: surface-edges :options: +NORMALIZE_WHITESPACE >>> nodes = np.asfortranarray([ ... [0.0, 0.5 , 1.0, 0.1875, 0.625, 0.0], ... [0.0, -0.1875, 0.0, 0.5 , 0.625, 1.0], ... ]) >>> surface = bezier.Surface(nodes, degree=2) >>> edge1, _, _ = surface.edges >>> edge1 <Curve (degree=2, dimension=2)> >>> edge1.nodes array([[ 0. , 0.5 , 1. ], [ 0. , -0.1875, 0. ]]) Returns: Tuple[~bezier.curve.Curve, ~bezier.curve.Curve, \ ~bezier.curve.Curve]: The edges of the surface. """ edge1, edge2, edge3 = self._get_edges() # NOTE: It is crucial that we return copies here. Since the edges # are cached, if they were mutable, callers could # inadvertently mutate the cached value. edge1 = edge1._copy() # pylint: disable=protected-access edge2 = edge2._copy() # pylint: disable=protected-access edge3 = edge3._copy() # pylint: disable=protected-access return edge1, edge2, edge3
[ "def", "edges", "(", "self", ")", ":", "edge1", ",", "edge2", ",", "edge3", "=", "self", ".", "_get_edges", "(", ")", "# NOTE: It is crucial that we return copies here. Since the edges", "# are cached, if they were mutable, callers could", "# inadvertently mutate the cached value.", "edge1", "=", "edge1", ".", "_copy", "(", ")", "# pylint: disable=protected-access", "edge2", "=", "edge2", ".", "_copy", "(", ")", "# pylint: disable=protected-access", "edge3", "=", "edge3", ".", "_copy", "(", ")", "# pylint: disable=protected-access", "return", "edge1", ",", "edge2", ",", "edge3" ]
The edges of the surface. .. doctest:: surface-edges :options: +NORMALIZE_WHITESPACE >>> nodes = np.asfortranarray([ ... [0.0, 0.5 , 1.0, 0.1875, 0.625, 0.0], ... [0.0, -0.1875, 0.0, 0.5 , 0.625, 1.0], ... ]) >>> surface = bezier.Surface(nodes, degree=2) >>> edge1, _, _ = surface.edges >>> edge1 <Curve (degree=2, dimension=2)> >>> edge1.nodes array([[ 0. , 0.5 , 1. ], [ 0. , -0.1875, 0. ]]) Returns: Tuple[~bezier.curve.Curve, ~bezier.curve.Curve, \ ~bezier.curve.Curve]: The edges of the surface.
[ "The", "edges", "of", "the", "surface", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/surface.py#L322-L352
dhermes/bezier
src/bezier/surface.py
Surface._verify_barycentric
def _verify_barycentric(lambda1, lambda2, lambda3): """Verifies that weights are barycentric and on the reference triangle. I.e., checks that they sum to one and are all non-negative. Args: lambda1 (float): Parameter along the reference triangle. lambda2 (float): Parameter along the reference triangle. lambda3 (float): Parameter along the reference triangle. Raises: ValueError: If the weights are not valid barycentric coordinates, i.e. they don't sum to ``1``. ValueError: If some weights are negative. """ weights_total = lambda1 + lambda2 + lambda3 if not np.allclose(weights_total, 1.0, atol=0.0): raise ValueError( "Weights do not sum to 1", lambda1, lambda2, lambda3 ) if lambda1 < 0.0 or lambda2 < 0.0 or lambda3 < 0.0: raise ValueError( "Weights must be positive", lambda1, lambda2, lambda3 )
python
def _verify_barycentric(lambda1, lambda2, lambda3): """Verifies that weights are barycentric and on the reference triangle. I.e., checks that they sum to one and are all non-negative. Args: lambda1 (float): Parameter along the reference triangle. lambda2 (float): Parameter along the reference triangle. lambda3 (float): Parameter along the reference triangle. Raises: ValueError: If the weights are not valid barycentric coordinates, i.e. they don't sum to ``1``. ValueError: If some weights are negative. """ weights_total = lambda1 + lambda2 + lambda3 if not np.allclose(weights_total, 1.0, atol=0.0): raise ValueError( "Weights do not sum to 1", lambda1, lambda2, lambda3 ) if lambda1 < 0.0 or lambda2 < 0.0 or lambda3 < 0.0: raise ValueError( "Weights must be positive", lambda1, lambda2, lambda3 )
[ "def", "_verify_barycentric", "(", "lambda1", ",", "lambda2", ",", "lambda3", ")", ":", "weights_total", "=", "lambda1", "+", "lambda2", "+", "lambda3", "if", "not", "np", ".", "allclose", "(", "weights_total", ",", "1.0", ",", "atol", "=", "0.0", ")", ":", "raise", "ValueError", "(", "\"Weights do not sum to 1\"", ",", "lambda1", ",", "lambda2", ",", "lambda3", ")", "if", "lambda1", "<", "0.0", "or", "lambda2", "<", "0.0", "or", "lambda3", "<", "0.0", ":", "raise", "ValueError", "(", "\"Weights must be positive\"", ",", "lambda1", ",", "lambda2", ",", "lambda3", ")" ]
Verifies that weights are barycentric and on the reference triangle. I.e., checks that they sum to one and are all non-negative. Args: lambda1 (float): Parameter along the reference triangle. lambda2 (float): Parameter along the reference triangle. lambda3 (float): Parameter along the reference triangle. Raises: ValueError: If the weights are not valid barycentric coordinates, i.e. they don't sum to ``1``. ValueError: If some weights are negative.
[ "Verifies", "that", "weights", "are", "barycentric", "and", "on", "the", "reference", "triangle", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/surface.py#L355-L379
dhermes/bezier
src/bezier/surface.py
Surface.evaluate_barycentric
def evaluate_barycentric(self, lambda1, lambda2, lambda3, _verify=True): r"""Compute a point on the surface. Evaluates :math:`B\left(\lambda_1, \lambda_2, \lambda_3\right)`. .. image:: ../../images/surface_evaluate_barycentric.png :align: center .. testsetup:: surface-barycentric, surface-barycentric-fail1, surface-barycentric-fail2, surface-barycentric-no-verify import numpy as np import bezier nodes = np.asfortranarray([ [0.0, 0.5, 1.0 , 0.125, 0.375, 0.25], [0.0, 0.0, 0.25, 0.5 , 0.375, 1.0 ], ]) surface = bezier.Surface(nodes, degree=2) .. doctest:: surface-barycentric :options: +NORMALIZE_WHITESPACE >>> nodes = np.asfortranarray([ ... [0.0, 0.5, 1.0 , 0.125, 0.375, 0.25], ... [0.0, 0.0, 0.25, 0.5 , 0.375, 1.0 ], ... ]) >>> surface = bezier.Surface(nodes, degree=2) >>> point = surface.evaluate_barycentric(0.125, 0.125, 0.75) >>> point array([[0.265625 ], [0.73046875]]) .. testcleanup:: surface-barycentric import make_images make_images.surface_evaluate_barycentric(surface, point) However, this can't be used for points **outside** the reference triangle: .. doctest:: surface-barycentric-fail1 >>> surface.evaluate_barycentric(-0.25, 0.75, 0.5) Traceback (most recent call last): ... ValueError: ('Weights must be positive', -0.25, 0.75, 0.5) or for non-barycentric coordinates; .. doctest:: surface-barycentric-fail2 >>> surface.evaluate_barycentric(0.25, 0.25, 0.25) Traceback (most recent call last): ... ValueError: ('Weights do not sum to 1', 0.25, 0.25, 0.25) However, these "invalid" inputs can be used if ``_verify`` is :data:`False`. .. doctest:: surface-barycentric-no-verify :options: +NORMALIZE_WHITESPACE >>> surface.evaluate_barycentric(-0.25, 0.75, 0.5, _verify=False) array([[0.6875 ], [0.546875]]) >>> surface.evaluate_barycentric(0.25, 0.25, 0.25, _verify=False) array([[0.203125], [0.1875 ]]) Args: lambda1 (float): Parameter along the reference triangle. lambda2 (float): Parameter along the reference triangle. lambda3 (float): Parameter along the reference triangle. _verify (Optional[bool]): Indicates if the barycentric coordinates should be verified as summing to one and all non-negative (i.e. verified as barycentric). Can either be used to evaluate at points outside the domain, or to save time when the caller already knows the input is verified. Defaults to :data:`True`. Returns: numpy.ndarray: The point on the surface (as a two dimensional NumPy array with a single column). Raises: ValueError: If the weights are not valid barycentric coordinates, i.e. they don't sum to ``1``. (Won't raise if ``_verify=False``.) ValueError: If some weights are negative. (Won't raise if ``_verify=False``.) """ if _verify: self._verify_barycentric(lambda1, lambda2, lambda3) return _surface_helpers.evaluate_barycentric( self._nodes, self._degree, lambda1, lambda2, lambda3 )
python
def evaluate_barycentric(self, lambda1, lambda2, lambda3, _verify=True): r"""Compute a point on the surface. Evaluates :math:`B\left(\lambda_1, \lambda_2, \lambda_3\right)`. .. image:: ../../images/surface_evaluate_barycentric.png :align: center .. testsetup:: surface-barycentric, surface-barycentric-fail1, surface-barycentric-fail2, surface-barycentric-no-verify import numpy as np import bezier nodes = np.asfortranarray([ [0.0, 0.5, 1.0 , 0.125, 0.375, 0.25], [0.0, 0.0, 0.25, 0.5 , 0.375, 1.0 ], ]) surface = bezier.Surface(nodes, degree=2) .. doctest:: surface-barycentric :options: +NORMALIZE_WHITESPACE >>> nodes = np.asfortranarray([ ... [0.0, 0.5, 1.0 , 0.125, 0.375, 0.25], ... [0.0, 0.0, 0.25, 0.5 , 0.375, 1.0 ], ... ]) >>> surface = bezier.Surface(nodes, degree=2) >>> point = surface.evaluate_barycentric(0.125, 0.125, 0.75) >>> point array([[0.265625 ], [0.73046875]]) .. testcleanup:: surface-barycentric import make_images make_images.surface_evaluate_barycentric(surface, point) However, this can't be used for points **outside** the reference triangle: .. doctest:: surface-barycentric-fail1 >>> surface.evaluate_barycentric(-0.25, 0.75, 0.5) Traceback (most recent call last): ... ValueError: ('Weights must be positive', -0.25, 0.75, 0.5) or for non-barycentric coordinates; .. doctest:: surface-barycentric-fail2 >>> surface.evaluate_barycentric(0.25, 0.25, 0.25) Traceback (most recent call last): ... ValueError: ('Weights do not sum to 1', 0.25, 0.25, 0.25) However, these "invalid" inputs can be used if ``_verify`` is :data:`False`. .. doctest:: surface-barycentric-no-verify :options: +NORMALIZE_WHITESPACE >>> surface.evaluate_barycentric(-0.25, 0.75, 0.5, _verify=False) array([[0.6875 ], [0.546875]]) >>> surface.evaluate_barycentric(0.25, 0.25, 0.25, _verify=False) array([[0.203125], [0.1875 ]]) Args: lambda1 (float): Parameter along the reference triangle. lambda2 (float): Parameter along the reference triangle. lambda3 (float): Parameter along the reference triangle. _verify (Optional[bool]): Indicates if the barycentric coordinates should be verified as summing to one and all non-negative (i.e. verified as barycentric). Can either be used to evaluate at points outside the domain, or to save time when the caller already knows the input is verified. Defaults to :data:`True`. Returns: numpy.ndarray: The point on the surface (as a two dimensional NumPy array with a single column). Raises: ValueError: If the weights are not valid barycentric coordinates, i.e. they don't sum to ``1``. (Won't raise if ``_verify=False``.) ValueError: If some weights are negative. (Won't raise if ``_verify=False``.) """ if _verify: self._verify_barycentric(lambda1, lambda2, lambda3) return _surface_helpers.evaluate_barycentric( self._nodes, self._degree, lambda1, lambda2, lambda3 )
[ "def", "evaluate_barycentric", "(", "self", ",", "lambda1", ",", "lambda2", ",", "lambda3", ",", "_verify", "=", "True", ")", ":", "if", "_verify", ":", "self", ".", "_verify_barycentric", "(", "lambda1", ",", "lambda2", ",", "lambda3", ")", "return", "_surface_helpers", ".", "evaluate_barycentric", "(", "self", ".", "_nodes", ",", "self", ".", "_degree", ",", "lambda1", ",", "lambda2", ",", "lambda3", ")" ]
r"""Compute a point on the surface. Evaluates :math:`B\left(\lambda_1, \lambda_2, \lambda_3\right)`. .. image:: ../../images/surface_evaluate_barycentric.png :align: center .. testsetup:: surface-barycentric, surface-barycentric-fail1, surface-barycentric-fail2, surface-barycentric-no-verify import numpy as np import bezier nodes = np.asfortranarray([ [0.0, 0.5, 1.0 , 0.125, 0.375, 0.25], [0.0, 0.0, 0.25, 0.5 , 0.375, 1.0 ], ]) surface = bezier.Surface(nodes, degree=2) .. doctest:: surface-barycentric :options: +NORMALIZE_WHITESPACE >>> nodes = np.asfortranarray([ ... [0.0, 0.5, 1.0 , 0.125, 0.375, 0.25], ... [0.0, 0.0, 0.25, 0.5 , 0.375, 1.0 ], ... ]) >>> surface = bezier.Surface(nodes, degree=2) >>> point = surface.evaluate_barycentric(0.125, 0.125, 0.75) >>> point array([[0.265625 ], [0.73046875]]) .. testcleanup:: surface-barycentric import make_images make_images.surface_evaluate_barycentric(surface, point) However, this can't be used for points **outside** the reference triangle: .. doctest:: surface-barycentric-fail1 >>> surface.evaluate_barycentric(-0.25, 0.75, 0.5) Traceback (most recent call last): ... ValueError: ('Weights must be positive', -0.25, 0.75, 0.5) or for non-barycentric coordinates; .. doctest:: surface-barycentric-fail2 >>> surface.evaluate_barycentric(0.25, 0.25, 0.25) Traceback (most recent call last): ... ValueError: ('Weights do not sum to 1', 0.25, 0.25, 0.25) However, these "invalid" inputs can be used if ``_verify`` is :data:`False`. .. doctest:: surface-barycentric-no-verify :options: +NORMALIZE_WHITESPACE >>> surface.evaluate_barycentric(-0.25, 0.75, 0.5, _verify=False) array([[0.6875 ], [0.546875]]) >>> surface.evaluate_barycentric(0.25, 0.25, 0.25, _verify=False) array([[0.203125], [0.1875 ]]) Args: lambda1 (float): Parameter along the reference triangle. lambda2 (float): Parameter along the reference triangle. lambda3 (float): Parameter along the reference triangle. _verify (Optional[bool]): Indicates if the barycentric coordinates should be verified as summing to one and all non-negative (i.e. verified as barycentric). Can either be used to evaluate at points outside the domain, or to save time when the caller already knows the input is verified. Defaults to :data:`True`. Returns: numpy.ndarray: The point on the surface (as a two dimensional NumPy array with a single column). Raises: ValueError: If the weights are not valid barycentric coordinates, i.e. they don't sum to ``1``. (Won't raise if ``_verify=False``.) ValueError: If some weights are negative. (Won't raise if ``_verify=False``.)
[ "r", "Compute", "a", "point", "on", "the", "surface", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/surface.py#L381-L475
dhermes/bezier
src/bezier/surface.py
Surface.evaluate_barycentric_multi
def evaluate_barycentric_multi(self, param_vals, _verify=True): r"""Compute multiple points on the surface. Assumes ``param_vals`` has three columns of barycentric coordinates. See :meth:`evaluate_barycentric` for more details on how each row of parameter values is evaluated. .. image:: ../../images/surface_evaluate_barycentric_multi.png :align: center .. doctest:: surface-eval-multi2 :options: +NORMALIZE_WHITESPACE >>> nodes = np.asfortranarray([ ... [0.0, 1.0 , 2.0, -1.5, -0.5, -3.0], ... [0.0, 0.75, 1.0, 1.0, 1.5, 2.0], ... ]) >>> surface = bezier.Surface(nodes, degree=2) >>> surface <Surface (degree=2, dimension=2)> >>> param_vals = np.asfortranarray([ ... [0. , 0.25, 0.75 ], ... [1. , 0. , 0. ], ... [0.25 , 0.5 , 0.25 ], ... [0.375, 0.25, 0.375], ... ]) >>> points = surface.evaluate_barycentric_multi(param_vals) >>> points array([[-1.75 , 0. , 0.25 , -0.625 ], [ 1.75 , 0. , 1.0625 , 1.046875]]) .. testcleanup:: surface-eval-multi2 import make_images make_images.surface_evaluate_barycentric_multi(surface, points) Args: param_vals (numpy.ndarray): Array of parameter values (as a ``N x 3`` array). _verify (Optional[bool]): Indicates if the coordinates should be verified. See :meth:`evaluate_barycentric`. Defaults to :data:`True`. Will also double check that ``param_vals`` is the right shape. Returns: numpy.ndarray: The points on the surface. Raises: ValueError: If ``param_vals`` is not a 2D array and ``_verify=True``. """ if _verify: if param_vals.ndim != 2: raise ValueError("Parameter values must be 2D array") for lambda1, lambda2, lambda3 in param_vals: self._verify_barycentric(lambda1, lambda2, lambda3) return _surface_helpers.evaluate_barycentric_multi( self._nodes, self._degree, param_vals, self._dimension )
python
def evaluate_barycentric_multi(self, param_vals, _verify=True): r"""Compute multiple points on the surface. Assumes ``param_vals`` has three columns of barycentric coordinates. See :meth:`evaluate_barycentric` for more details on how each row of parameter values is evaluated. .. image:: ../../images/surface_evaluate_barycentric_multi.png :align: center .. doctest:: surface-eval-multi2 :options: +NORMALIZE_WHITESPACE >>> nodes = np.asfortranarray([ ... [0.0, 1.0 , 2.0, -1.5, -0.5, -3.0], ... [0.0, 0.75, 1.0, 1.0, 1.5, 2.0], ... ]) >>> surface = bezier.Surface(nodes, degree=2) >>> surface <Surface (degree=2, dimension=2)> >>> param_vals = np.asfortranarray([ ... [0. , 0.25, 0.75 ], ... [1. , 0. , 0. ], ... [0.25 , 0.5 , 0.25 ], ... [0.375, 0.25, 0.375], ... ]) >>> points = surface.evaluate_barycentric_multi(param_vals) >>> points array([[-1.75 , 0. , 0.25 , -0.625 ], [ 1.75 , 0. , 1.0625 , 1.046875]]) .. testcleanup:: surface-eval-multi2 import make_images make_images.surface_evaluate_barycentric_multi(surface, points) Args: param_vals (numpy.ndarray): Array of parameter values (as a ``N x 3`` array). _verify (Optional[bool]): Indicates if the coordinates should be verified. See :meth:`evaluate_barycentric`. Defaults to :data:`True`. Will also double check that ``param_vals`` is the right shape. Returns: numpy.ndarray: The points on the surface. Raises: ValueError: If ``param_vals`` is not a 2D array and ``_verify=True``. """ if _verify: if param_vals.ndim != 2: raise ValueError("Parameter values must be 2D array") for lambda1, lambda2, lambda3 in param_vals: self._verify_barycentric(lambda1, lambda2, lambda3) return _surface_helpers.evaluate_barycentric_multi( self._nodes, self._degree, param_vals, self._dimension )
[ "def", "evaluate_barycentric_multi", "(", "self", ",", "param_vals", ",", "_verify", "=", "True", ")", ":", "if", "_verify", ":", "if", "param_vals", ".", "ndim", "!=", "2", ":", "raise", "ValueError", "(", "\"Parameter values must be 2D array\"", ")", "for", "lambda1", ",", "lambda2", ",", "lambda3", "in", "param_vals", ":", "self", ".", "_verify_barycentric", "(", "lambda1", ",", "lambda2", ",", "lambda3", ")", "return", "_surface_helpers", ".", "evaluate_barycentric_multi", "(", "self", ".", "_nodes", ",", "self", ".", "_degree", ",", "param_vals", ",", "self", ".", "_dimension", ")" ]
r"""Compute multiple points on the surface. Assumes ``param_vals`` has three columns of barycentric coordinates. See :meth:`evaluate_barycentric` for more details on how each row of parameter values is evaluated. .. image:: ../../images/surface_evaluate_barycentric_multi.png :align: center .. doctest:: surface-eval-multi2 :options: +NORMALIZE_WHITESPACE >>> nodes = np.asfortranarray([ ... [0.0, 1.0 , 2.0, -1.5, -0.5, -3.0], ... [0.0, 0.75, 1.0, 1.0, 1.5, 2.0], ... ]) >>> surface = bezier.Surface(nodes, degree=2) >>> surface <Surface (degree=2, dimension=2)> >>> param_vals = np.asfortranarray([ ... [0. , 0.25, 0.75 ], ... [1. , 0. , 0. ], ... [0.25 , 0.5 , 0.25 ], ... [0.375, 0.25, 0.375], ... ]) >>> points = surface.evaluate_barycentric_multi(param_vals) >>> points array([[-1.75 , 0. , 0.25 , -0.625 ], [ 1.75 , 0. , 1.0625 , 1.046875]]) .. testcleanup:: surface-eval-multi2 import make_images make_images.surface_evaluate_barycentric_multi(surface, points) Args: param_vals (numpy.ndarray): Array of parameter values (as a ``N x 3`` array). _verify (Optional[bool]): Indicates if the coordinates should be verified. See :meth:`evaluate_barycentric`. Defaults to :data:`True`. Will also double check that ``param_vals`` is the right shape. Returns: numpy.ndarray: The points on the surface. Raises: ValueError: If ``param_vals`` is not a 2D array and ``_verify=True``.
[ "r", "Compute", "multiple", "points", "on", "the", "surface", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/surface.py#L477-L536
dhermes/bezier
src/bezier/surface.py
Surface._verify_cartesian
def _verify_cartesian(s, t): """Verifies that a point is in the reference triangle. I.e., checks that they sum to <= one and are each non-negative. Args: s (float): Parameter along the reference triangle. t (float): Parameter along the reference triangle. Raises: ValueError: If the point lies outside the reference triangle. """ if s < 0.0 or t < 0.0 or s + t > 1.0: raise ValueError("Point lies outside reference triangle", s, t)
python
def _verify_cartesian(s, t): """Verifies that a point is in the reference triangle. I.e., checks that they sum to <= one and are each non-negative. Args: s (float): Parameter along the reference triangle. t (float): Parameter along the reference triangle. Raises: ValueError: If the point lies outside the reference triangle. """ if s < 0.0 or t < 0.0 or s + t > 1.0: raise ValueError("Point lies outside reference triangle", s, t)
[ "def", "_verify_cartesian", "(", "s", ",", "t", ")", ":", "if", "s", "<", "0.0", "or", "t", "<", "0.0", "or", "s", "+", "t", ">", "1.0", ":", "raise", "ValueError", "(", "\"Point lies outside reference triangle\"", ",", "s", ",", "t", ")" ]
Verifies that a point is in the reference triangle. I.e., checks that they sum to <= one and are each non-negative. Args: s (float): Parameter along the reference triangle. t (float): Parameter along the reference triangle. Raises: ValueError: If the point lies outside the reference triangle.
[ "Verifies", "that", "a", "point", "is", "in", "the", "reference", "triangle", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/surface.py#L539-L552
dhermes/bezier
src/bezier/surface.py
Surface.evaluate_cartesian
def evaluate_cartesian(self, s, t, _verify=True): r"""Compute a point on the surface. Evaluates :math:`B\left(1 - s - t, s, t\right)` by calling :meth:`evaluate_barycentric`: This method acts as a (partial) inverse to :meth:`locate`. .. testsetup:: surface-cartesian import numpy as np import bezier .. doctest:: surface-cartesian :options: +NORMALIZE_WHITESPACE >>> nodes = np.asfortranarray([ ... [0.0, 0.5, 1.0 , 0.0, 0.5, 0.25], ... [0.0, 0.5, 0.625, 0.5, 0.5, 1.0 ], ... ]) >>> surface = bezier.Surface(nodes, degree=2) >>> point = surface.evaluate_cartesian(0.125, 0.375) >>> point array([[0.16015625], [0.44726562]]) >>> surface.evaluate_barycentric(0.5, 0.125, 0.375) array([[0.16015625], [0.44726562]]) Args: s (float): Parameter along the reference triangle. t (float): Parameter along the reference triangle. _verify (Optional[bool]): Indicates if the coordinates should be verified inside of the reference triangle. Defaults to :data:`True`. Returns: numpy.ndarray: The point on the surface (as a two dimensional NumPy array). """ if _verify: self._verify_cartesian(s, t) return _surface_helpers.evaluate_barycentric( self._nodes, self._degree, 1.0 - s - t, s, t )
python
def evaluate_cartesian(self, s, t, _verify=True): r"""Compute a point on the surface. Evaluates :math:`B\left(1 - s - t, s, t\right)` by calling :meth:`evaluate_barycentric`: This method acts as a (partial) inverse to :meth:`locate`. .. testsetup:: surface-cartesian import numpy as np import bezier .. doctest:: surface-cartesian :options: +NORMALIZE_WHITESPACE >>> nodes = np.asfortranarray([ ... [0.0, 0.5, 1.0 , 0.0, 0.5, 0.25], ... [0.0, 0.5, 0.625, 0.5, 0.5, 1.0 ], ... ]) >>> surface = bezier.Surface(nodes, degree=2) >>> point = surface.evaluate_cartesian(0.125, 0.375) >>> point array([[0.16015625], [0.44726562]]) >>> surface.evaluate_barycentric(0.5, 0.125, 0.375) array([[0.16015625], [0.44726562]]) Args: s (float): Parameter along the reference triangle. t (float): Parameter along the reference triangle. _verify (Optional[bool]): Indicates if the coordinates should be verified inside of the reference triangle. Defaults to :data:`True`. Returns: numpy.ndarray: The point on the surface (as a two dimensional NumPy array). """ if _verify: self._verify_cartesian(s, t) return _surface_helpers.evaluate_barycentric( self._nodes, self._degree, 1.0 - s - t, s, t )
[ "def", "evaluate_cartesian", "(", "self", ",", "s", ",", "t", ",", "_verify", "=", "True", ")", ":", "if", "_verify", ":", "self", ".", "_verify_cartesian", "(", "s", ",", "t", ")", "return", "_surface_helpers", ".", "evaluate_barycentric", "(", "self", ".", "_nodes", ",", "self", ".", "_degree", ",", "1.0", "-", "s", "-", "t", ",", "s", ",", "t", ")" ]
r"""Compute a point on the surface. Evaluates :math:`B\left(1 - s - t, s, t\right)` by calling :meth:`evaluate_barycentric`: This method acts as a (partial) inverse to :meth:`locate`. .. testsetup:: surface-cartesian import numpy as np import bezier .. doctest:: surface-cartesian :options: +NORMALIZE_WHITESPACE >>> nodes = np.asfortranarray([ ... [0.0, 0.5, 1.0 , 0.0, 0.5, 0.25], ... [0.0, 0.5, 0.625, 0.5, 0.5, 1.0 ], ... ]) >>> surface = bezier.Surface(nodes, degree=2) >>> point = surface.evaluate_cartesian(0.125, 0.375) >>> point array([[0.16015625], [0.44726562]]) >>> surface.evaluate_barycentric(0.5, 0.125, 0.375) array([[0.16015625], [0.44726562]]) Args: s (float): Parameter along the reference triangle. t (float): Parameter along the reference triangle. _verify (Optional[bool]): Indicates if the coordinates should be verified inside of the reference triangle. Defaults to :data:`True`. Returns: numpy.ndarray: The point on the surface (as a two dimensional NumPy array).
[ "r", "Compute", "a", "point", "on", "the", "surface", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/surface.py#L554-L598
dhermes/bezier
src/bezier/surface.py
Surface.evaluate_cartesian_multi
def evaluate_cartesian_multi(self, param_vals, _verify=True): r"""Compute multiple points on the surface. Assumes ``param_vals`` has two columns of Cartesian coordinates. See :meth:`evaluate_cartesian` for more details on how each row of parameter values is evaluated. .. image:: ../../images/surface_evaluate_cartesian_multi.png :align: center .. doctest:: surface-eval-multi1 :options: +NORMALIZE_WHITESPACE >>> nodes = np.asfortranarray([ ... [0.0, 2.0, -3.0], ... [0.0, 1.0, 2.0], ... ]) >>> surface = bezier.Surface(nodes, degree=1) >>> surface <Surface (degree=1, dimension=2)> >>> param_vals = np.asfortranarray([ ... [0.0 , 0.0 ], ... [0.125, 0.625], ... [0.5 , 0.5 ], ... ]) >>> points = surface.evaluate_cartesian_multi(param_vals) >>> points array([[ 0. , -1.625, -0.5 ], [ 0. , 1.375, 1.5 ]]) .. testcleanup:: surface-eval-multi1 import make_images make_images.surface_evaluate_cartesian_multi(surface, points) Args: param_vals (numpy.ndarray): Array of parameter values (as a ``N x 2`` array). _verify (Optional[bool]): Indicates if the coordinates should be verified. See :meth:`evaluate_cartesian`. Defaults to :data:`True`. Will also double check that ``param_vals`` is the right shape. Returns: numpy.ndarray: The points on the surface. Raises: ValueError: If ``param_vals`` is not a 2D array and ``_verify=True``. """ if _verify: if param_vals.ndim != 2: raise ValueError("Parameter values must be 2D array") for s, t in param_vals: self._verify_cartesian(s, t) return _surface_helpers.evaluate_cartesian_multi( self._nodes, self._degree, param_vals, self._dimension )
python
def evaluate_cartesian_multi(self, param_vals, _verify=True): r"""Compute multiple points on the surface. Assumes ``param_vals`` has two columns of Cartesian coordinates. See :meth:`evaluate_cartesian` for more details on how each row of parameter values is evaluated. .. image:: ../../images/surface_evaluate_cartesian_multi.png :align: center .. doctest:: surface-eval-multi1 :options: +NORMALIZE_WHITESPACE >>> nodes = np.asfortranarray([ ... [0.0, 2.0, -3.0], ... [0.0, 1.0, 2.0], ... ]) >>> surface = bezier.Surface(nodes, degree=1) >>> surface <Surface (degree=1, dimension=2)> >>> param_vals = np.asfortranarray([ ... [0.0 , 0.0 ], ... [0.125, 0.625], ... [0.5 , 0.5 ], ... ]) >>> points = surface.evaluate_cartesian_multi(param_vals) >>> points array([[ 0. , -1.625, -0.5 ], [ 0. , 1.375, 1.5 ]]) .. testcleanup:: surface-eval-multi1 import make_images make_images.surface_evaluate_cartesian_multi(surface, points) Args: param_vals (numpy.ndarray): Array of parameter values (as a ``N x 2`` array). _verify (Optional[bool]): Indicates if the coordinates should be verified. See :meth:`evaluate_cartesian`. Defaults to :data:`True`. Will also double check that ``param_vals`` is the right shape. Returns: numpy.ndarray: The points on the surface. Raises: ValueError: If ``param_vals`` is not a 2D array and ``_verify=True``. """ if _verify: if param_vals.ndim != 2: raise ValueError("Parameter values must be 2D array") for s, t in param_vals: self._verify_cartesian(s, t) return _surface_helpers.evaluate_cartesian_multi( self._nodes, self._degree, param_vals, self._dimension )
[ "def", "evaluate_cartesian_multi", "(", "self", ",", "param_vals", ",", "_verify", "=", "True", ")", ":", "if", "_verify", ":", "if", "param_vals", ".", "ndim", "!=", "2", ":", "raise", "ValueError", "(", "\"Parameter values must be 2D array\"", ")", "for", "s", ",", "t", "in", "param_vals", ":", "self", ".", "_verify_cartesian", "(", "s", ",", "t", ")", "return", "_surface_helpers", ".", "evaluate_cartesian_multi", "(", "self", ".", "_nodes", ",", "self", ".", "_degree", ",", "param_vals", ",", "self", ".", "_dimension", ")" ]
r"""Compute multiple points on the surface. Assumes ``param_vals`` has two columns of Cartesian coordinates. See :meth:`evaluate_cartesian` for more details on how each row of parameter values is evaluated. .. image:: ../../images/surface_evaluate_cartesian_multi.png :align: center .. doctest:: surface-eval-multi1 :options: +NORMALIZE_WHITESPACE >>> nodes = np.asfortranarray([ ... [0.0, 2.0, -3.0], ... [0.0, 1.0, 2.0], ... ]) >>> surface = bezier.Surface(nodes, degree=1) >>> surface <Surface (degree=1, dimension=2)> >>> param_vals = np.asfortranarray([ ... [0.0 , 0.0 ], ... [0.125, 0.625], ... [0.5 , 0.5 ], ... ]) >>> points = surface.evaluate_cartesian_multi(param_vals) >>> points array([[ 0. , -1.625, -0.5 ], [ 0. , 1.375, 1.5 ]]) .. testcleanup:: surface-eval-multi1 import make_images make_images.surface_evaluate_cartesian_multi(surface, points) Args: param_vals (numpy.ndarray): Array of parameter values (as a ``N x 2`` array). _verify (Optional[bool]): Indicates if the coordinates should be verified. See :meth:`evaluate_cartesian`. Defaults to :data:`True`. Will also double check that ``param_vals`` is the right shape. Returns: numpy.ndarray: The points on the surface. Raises: ValueError: If ``param_vals`` is not a 2D array and ``_verify=True``.
[ "r", "Compute", "multiple", "points", "on", "the", "surface", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/surface.py#L600-L658
dhermes/bezier
src/bezier/surface.py
Surface.plot
def plot(self, pts_per_edge, color=None, ax=None, with_nodes=False): """Plot the current surface. Args: pts_per_edge (int): Number of points to plot per edge. color (Optional[Tuple[float, float, float]]): Color as RGB profile. ax (Optional[matplotlib.artist.Artist]): matplotlib axis object to add plot to. with_nodes (Optional[bool]): Determines if the control points should be added to the plot. Off by default. Returns: matplotlib.artist.Artist: The axis containing the plot. This may be a newly created axis. Raises: NotImplementedError: If the surface's dimension is not ``2``. """ if self._dimension != 2: raise NotImplementedError( "2D is the only supported dimension", "Current dimension", self._dimension, ) if ax is None: ax = _plot_helpers.new_axis() _plot_helpers.add_patch(ax, color, pts_per_edge, *self._get_edges()) if with_nodes: ax.plot( self._nodes[0, :], self._nodes[1, :], color="black", marker="o", linestyle="None", ) return ax
python
def plot(self, pts_per_edge, color=None, ax=None, with_nodes=False): """Plot the current surface. Args: pts_per_edge (int): Number of points to plot per edge. color (Optional[Tuple[float, float, float]]): Color as RGB profile. ax (Optional[matplotlib.artist.Artist]): matplotlib axis object to add plot to. with_nodes (Optional[bool]): Determines if the control points should be added to the plot. Off by default. Returns: matplotlib.artist.Artist: The axis containing the plot. This may be a newly created axis. Raises: NotImplementedError: If the surface's dimension is not ``2``. """ if self._dimension != 2: raise NotImplementedError( "2D is the only supported dimension", "Current dimension", self._dimension, ) if ax is None: ax = _plot_helpers.new_axis() _plot_helpers.add_patch(ax, color, pts_per_edge, *self._get_edges()) if with_nodes: ax.plot( self._nodes[0, :], self._nodes[1, :], color="black", marker="o", linestyle="None", ) return ax
[ "def", "plot", "(", "self", ",", "pts_per_edge", ",", "color", "=", "None", ",", "ax", "=", "None", ",", "with_nodes", "=", "False", ")", ":", "if", "self", ".", "_dimension", "!=", "2", ":", "raise", "NotImplementedError", "(", "\"2D is the only supported dimension\"", ",", "\"Current dimension\"", ",", "self", ".", "_dimension", ",", ")", "if", "ax", "is", "None", ":", "ax", "=", "_plot_helpers", ".", "new_axis", "(", ")", "_plot_helpers", ".", "add_patch", "(", "ax", ",", "color", ",", "pts_per_edge", ",", "*", "self", ".", "_get_edges", "(", ")", ")", "if", "with_nodes", ":", "ax", ".", "plot", "(", "self", ".", "_nodes", "[", "0", ",", ":", "]", ",", "self", ".", "_nodes", "[", "1", ",", ":", "]", ",", "color", "=", "\"black\"", ",", "marker", "=", "\"o\"", ",", "linestyle", "=", "\"None\"", ",", ")", "return", "ax" ]
Plot the current surface. Args: pts_per_edge (int): Number of points to plot per edge. color (Optional[Tuple[float, float, float]]): Color as RGB profile. ax (Optional[matplotlib.artist.Artist]): matplotlib axis object to add plot to. with_nodes (Optional[bool]): Determines if the control points should be added to the plot. Off by default. Returns: matplotlib.artist.Artist: The axis containing the plot. This may be a newly created axis. Raises: NotImplementedError: If the surface's dimension is not ``2``.
[ "Plot", "the", "current", "surface", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/surface.py#L660-L696
dhermes/bezier
src/bezier/surface.py
Surface.subdivide
def subdivide(self): r"""Split the surface into four sub-surfaces. Does so by taking the unit triangle (i.e. the domain of the surface) and splitting it into four sub-triangles .. image:: ../../images/surface_subdivide1.png :align: center Then the surface is re-parameterized via the map to / from the given sub-triangles and the unit triangle. For example, when a degree two surface is subdivided: .. image:: ../../images/surface_subdivide2.png :align: center .. doctest:: surface-subdivide :options: +NORMALIZE_WHITESPACE >>> nodes = np.asfortranarray([ ... [-1.0, 0.5, 2.0, 0.25, 2.0, 0.0], ... [ 0.0, 0.5, 0.0, 1.75, 3.0, 4.0], ... ]) >>> surface = bezier.Surface(nodes, degree=2) >>> _, sub_surface_b, _, _ = surface.subdivide() >>> sub_surface_b <Surface (degree=2, dimension=2)> >>> sub_surface_b.nodes array([[ 1.5 , 0.6875, -0.125 , 1.1875, 0.4375, 0.5 ], [ 2.5 , 2.3125, 1.875 , 1.3125, 1.3125, 0.25 ]]) .. testcleanup:: surface-subdivide import make_images make_images.surface_subdivide1() make_images.surface_subdivide2(surface, sub_surface_b) Returns: Tuple[Surface, Surface, Surface, Surface]: The lower left, central, lower right and upper left sub-surfaces (in that order). """ nodes_a, nodes_b, nodes_c, nodes_d = _surface_helpers.subdivide_nodes( self._nodes, self._degree ) return ( Surface(nodes_a, self._degree, _copy=False), Surface(nodes_b, self._degree, _copy=False), Surface(nodes_c, self._degree, _copy=False), Surface(nodes_d, self._degree, _copy=False), )
python
def subdivide(self): r"""Split the surface into four sub-surfaces. Does so by taking the unit triangle (i.e. the domain of the surface) and splitting it into four sub-triangles .. image:: ../../images/surface_subdivide1.png :align: center Then the surface is re-parameterized via the map to / from the given sub-triangles and the unit triangle. For example, when a degree two surface is subdivided: .. image:: ../../images/surface_subdivide2.png :align: center .. doctest:: surface-subdivide :options: +NORMALIZE_WHITESPACE >>> nodes = np.asfortranarray([ ... [-1.0, 0.5, 2.0, 0.25, 2.0, 0.0], ... [ 0.0, 0.5, 0.0, 1.75, 3.0, 4.0], ... ]) >>> surface = bezier.Surface(nodes, degree=2) >>> _, sub_surface_b, _, _ = surface.subdivide() >>> sub_surface_b <Surface (degree=2, dimension=2)> >>> sub_surface_b.nodes array([[ 1.5 , 0.6875, -0.125 , 1.1875, 0.4375, 0.5 ], [ 2.5 , 2.3125, 1.875 , 1.3125, 1.3125, 0.25 ]]) .. testcleanup:: surface-subdivide import make_images make_images.surface_subdivide1() make_images.surface_subdivide2(surface, sub_surface_b) Returns: Tuple[Surface, Surface, Surface, Surface]: The lower left, central, lower right and upper left sub-surfaces (in that order). """ nodes_a, nodes_b, nodes_c, nodes_d = _surface_helpers.subdivide_nodes( self._nodes, self._degree ) return ( Surface(nodes_a, self._degree, _copy=False), Surface(nodes_b, self._degree, _copy=False), Surface(nodes_c, self._degree, _copy=False), Surface(nodes_d, self._degree, _copy=False), )
[ "def", "subdivide", "(", "self", ")", ":", "nodes_a", ",", "nodes_b", ",", "nodes_c", ",", "nodes_d", "=", "_surface_helpers", ".", "subdivide_nodes", "(", "self", ".", "_nodes", ",", "self", ".", "_degree", ")", "return", "(", "Surface", "(", "nodes_a", ",", "self", ".", "_degree", ",", "_copy", "=", "False", ")", ",", "Surface", "(", "nodes_b", ",", "self", ".", "_degree", ",", "_copy", "=", "False", ")", ",", "Surface", "(", "nodes_c", ",", "self", ".", "_degree", ",", "_copy", "=", "False", ")", ",", "Surface", "(", "nodes_d", ",", "self", ".", "_degree", ",", "_copy", "=", "False", ")", ",", ")" ]
r"""Split the surface into four sub-surfaces. Does so by taking the unit triangle (i.e. the domain of the surface) and splitting it into four sub-triangles .. image:: ../../images/surface_subdivide1.png :align: center Then the surface is re-parameterized via the map to / from the given sub-triangles and the unit triangle. For example, when a degree two surface is subdivided: .. image:: ../../images/surface_subdivide2.png :align: center .. doctest:: surface-subdivide :options: +NORMALIZE_WHITESPACE >>> nodes = np.asfortranarray([ ... [-1.0, 0.5, 2.0, 0.25, 2.0, 0.0], ... [ 0.0, 0.5, 0.0, 1.75, 3.0, 4.0], ... ]) >>> surface = bezier.Surface(nodes, degree=2) >>> _, sub_surface_b, _, _ = surface.subdivide() >>> sub_surface_b <Surface (degree=2, dimension=2)> >>> sub_surface_b.nodes array([[ 1.5 , 0.6875, -0.125 , 1.1875, 0.4375, 0.5 ], [ 2.5 , 2.3125, 1.875 , 1.3125, 1.3125, 0.25 ]]) .. testcleanup:: surface-subdivide import make_images make_images.surface_subdivide1() make_images.surface_subdivide2(surface, sub_surface_b) Returns: Tuple[Surface, Surface, Surface, Surface]: The lower left, central, lower right and upper left sub-surfaces (in that order).
[ "r", "Split", "the", "surface", "into", "four", "sub", "-", "surfaces", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/surface.py#L698-L748
dhermes/bezier
src/bezier/surface.py
Surface._compute_valid
def _compute_valid(self): r"""Determines if the current surface is "valid". Does this by checking if the Jacobian of the map from the reference triangle is everywhere positive. Returns: bool: Flag indicating if the current surface is valid. Raises: NotImplementedError: If the surface is in a dimension other than :math:`\mathbf{R}^2`. .UnsupportedDegree: If the degree is not 1, 2 or 3. """ if self._dimension != 2: raise NotImplementedError("Validity check only implemented in R^2") poly_sign = None if self._degree == 1: # In the linear case, we are only invalid if the points # are collinear. first_deriv = self._nodes[:, 1:] - self._nodes[:, :-1] poly_sign = _SIGN(np.linalg.det(first_deriv)) elif self._degree == 2: bernstein = _surface_helpers.quadratic_jacobian_polynomial( self._nodes ) poly_sign = _surface_helpers.polynomial_sign(bernstein, 2) elif self._degree == 3: bernstein = _surface_helpers.cubic_jacobian_polynomial(self._nodes) poly_sign = _surface_helpers.polynomial_sign(bernstein, 4) else: raise _helpers.UnsupportedDegree(self._degree, supported=(1, 2, 3)) return poly_sign == 1
python
def _compute_valid(self): r"""Determines if the current surface is "valid". Does this by checking if the Jacobian of the map from the reference triangle is everywhere positive. Returns: bool: Flag indicating if the current surface is valid. Raises: NotImplementedError: If the surface is in a dimension other than :math:`\mathbf{R}^2`. .UnsupportedDegree: If the degree is not 1, 2 or 3. """ if self._dimension != 2: raise NotImplementedError("Validity check only implemented in R^2") poly_sign = None if self._degree == 1: # In the linear case, we are only invalid if the points # are collinear. first_deriv = self._nodes[:, 1:] - self._nodes[:, :-1] poly_sign = _SIGN(np.linalg.det(first_deriv)) elif self._degree == 2: bernstein = _surface_helpers.quadratic_jacobian_polynomial( self._nodes ) poly_sign = _surface_helpers.polynomial_sign(bernstein, 2) elif self._degree == 3: bernstein = _surface_helpers.cubic_jacobian_polynomial(self._nodes) poly_sign = _surface_helpers.polynomial_sign(bernstein, 4) else: raise _helpers.UnsupportedDegree(self._degree, supported=(1, 2, 3)) return poly_sign == 1
[ "def", "_compute_valid", "(", "self", ")", ":", "if", "self", ".", "_dimension", "!=", "2", ":", "raise", "NotImplementedError", "(", "\"Validity check only implemented in R^2\"", ")", "poly_sign", "=", "None", "if", "self", ".", "_degree", "==", "1", ":", "# In the linear case, we are only invalid if the points", "# are collinear.", "first_deriv", "=", "self", ".", "_nodes", "[", ":", ",", "1", ":", "]", "-", "self", ".", "_nodes", "[", ":", ",", ":", "-", "1", "]", "poly_sign", "=", "_SIGN", "(", "np", ".", "linalg", ".", "det", "(", "first_deriv", ")", ")", "elif", "self", ".", "_degree", "==", "2", ":", "bernstein", "=", "_surface_helpers", ".", "quadratic_jacobian_polynomial", "(", "self", ".", "_nodes", ")", "poly_sign", "=", "_surface_helpers", ".", "polynomial_sign", "(", "bernstein", ",", "2", ")", "elif", "self", ".", "_degree", "==", "3", ":", "bernstein", "=", "_surface_helpers", ".", "cubic_jacobian_polynomial", "(", "self", ".", "_nodes", ")", "poly_sign", "=", "_surface_helpers", ".", "polynomial_sign", "(", "bernstein", ",", "4", ")", "else", ":", "raise", "_helpers", ".", "UnsupportedDegree", "(", "self", ".", "_degree", ",", "supported", "=", "(", "1", ",", "2", ",", "3", ")", ")", "return", "poly_sign", "==", "1" ]
r"""Determines if the current surface is "valid". Does this by checking if the Jacobian of the map from the reference triangle is everywhere positive. Returns: bool: Flag indicating if the current surface is valid. Raises: NotImplementedError: If the surface is in a dimension other than :math:`\mathbf{R}^2`. .UnsupportedDegree: If the degree is not 1, 2 or 3.
[ "r", "Determines", "if", "the", "current", "surface", "is", "valid", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/surface.py#L750-L784
dhermes/bezier
src/bezier/surface.py
Surface.locate
def locate(self, point, _verify=True): r"""Find a point on the current surface. Solves for :math:`s` and :math:`t` in :math:`B(s, t) = p`. This method acts as a (partial) inverse to :meth:`evaluate_cartesian`. .. warning:: A unique solution is only guaranteed if the current surface is valid. This code assumes a valid surface, but doesn't check. .. image:: ../../images/surface_locate.png :align: center .. doctest:: surface-locate >>> nodes = np.asfortranarray([ ... [0.0, 0.5 , 1.0, 0.25, 0.75, 0.0], ... [0.0, -0.25, 0.0, 0.5 , 0.75, 1.0], ... ]) >>> surface = bezier.Surface(nodes, degree=2) >>> point = np.asfortranarray([ ... [0.59375], ... [0.25 ], ... ]) >>> s, t = surface.locate(point) >>> s 0.5 >>> t 0.25 .. testcleanup:: surface-locate import make_images make_images.surface_locate(surface, point) Args: point (numpy.ndarray): A (``D x 1``) point on the surface, where :math:`D` is the dimension of the surface. _verify (Optional[bool]): Indicates if extra caution should be used to verify assumptions about the inputs. Can be disabled to speed up execution time. Defaults to :data:`True`. Returns: Optional[Tuple[float, float]]: The :math:`s` and :math:`t` values corresponding to ``point`` or :data:`None` if the point is not on the surface. Raises: NotImplementedError: If the surface isn't in :math:`\mathbf{R}^2`. ValueError: If the dimension of the ``point`` doesn't match the dimension of the current surface. """ if _verify: if self._dimension != 2: raise NotImplementedError("Only 2D surfaces supported.") if point.shape != (self._dimension, 1): point_dimensions = " x ".join( str(dimension) for dimension in point.shape ) msg = _LOCATE_ERROR_TEMPLATE.format( self._dimension, self._dimension, point, point_dimensions ) raise ValueError(msg) return _surface_intersection.locate_point( self._nodes, self._degree, point[0, 0], point[1, 0] )
python
def locate(self, point, _verify=True): r"""Find a point on the current surface. Solves for :math:`s` and :math:`t` in :math:`B(s, t) = p`. This method acts as a (partial) inverse to :meth:`evaluate_cartesian`. .. warning:: A unique solution is only guaranteed if the current surface is valid. This code assumes a valid surface, but doesn't check. .. image:: ../../images/surface_locate.png :align: center .. doctest:: surface-locate >>> nodes = np.asfortranarray([ ... [0.0, 0.5 , 1.0, 0.25, 0.75, 0.0], ... [0.0, -0.25, 0.0, 0.5 , 0.75, 1.0], ... ]) >>> surface = bezier.Surface(nodes, degree=2) >>> point = np.asfortranarray([ ... [0.59375], ... [0.25 ], ... ]) >>> s, t = surface.locate(point) >>> s 0.5 >>> t 0.25 .. testcleanup:: surface-locate import make_images make_images.surface_locate(surface, point) Args: point (numpy.ndarray): A (``D x 1``) point on the surface, where :math:`D` is the dimension of the surface. _verify (Optional[bool]): Indicates if extra caution should be used to verify assumptions about the inputs. Can be disabled to speed up execution time. Defaults to :data:`True`. Returns: Optional[Tuple[float, float]]: The :math:`s` and :math:`t` values corresponding to ``point`` or :data:`None` if the point is not on the surface. Raises: NotImplementedError: If the surface isn't in :math:`\mathbf{R}^2`. ValueError: If the dimension of the ``point`` doesn't match the dimension of the current surface. """ if _verify: if self._dimension != 2: raise NotImplementedError("Only 2D surfaces supported.") if point.shape != (self._dimension, 1): point_dimensions = " x ".join( str(dimension) for dimension in point.shape ) msg = _LOCATE_ERROR_TEMPLATE.format( self._dimension, self._dimension, point, point_dimensions ) raise ValueError(msg) return _surface_intersection.locate_point( self._nodes, self._degree, point[0, 0], point[1, 0] )
[ "def", "locate", "(", "self", ",", "point", ",", "_verify", "=", "True", ")", ":", "if", "_verify", ":", "if", "self", ".", "_dimension", "!=", "2", ":", "raise", "NotImplementedError", "(", "\"Only 2D surfaces supported.\"", ")", "if", "point", ".", "shape", "!=", "(", "self", ".", "_dimension", ",", "1", ")", ":", "point_dimensions", "=", "\" x \"", ".", "join", "(", "str", "(", "dimension", ")", "for", "dimension", "in", "point", ".", "shape", ")", "msg", "=", "_LOCATE_ERROR_TEMPLATE", ".", "format", "(", "self", ".", "_dimension", ",", "self", ".", "_dimension", ",", "point", ",", "point_dimensions", ")", "raise", "ValueError", "(", "msg", ")", "return", "_surface_intersection", ".", "locate_point", "(", "self", ".", "_nodes", ",", "self", ".", "_degree", ",", "point", "[", "0", ",", "0", "]", ",", "point", "[", "1", ",", "0", "]", ")" ]
r"""Find a point on the current surface. Solves for :math:`s` and :math:`t` in :math:`B(s, t) = p`. This method acts as a (partial) inverse to :meth:`evaluate_cartesian`. .. warning:: A unique solution is only guaranteed if the current surface is valid. This code assumes a valid surface, but doesn't check. .. image:: ../../images/surface_locate.png :align: center .. doctest:: surface-locate >>> nodes = np.asfortranarray([ ... [0.0, 0.5 , 1.0, 0.25, 0.75, 0.0], ... [0.0, -0.25, 0.0, 0.5 , 0.75, 1.0], ... ]) >>> surface = bezier.Surface(nodes, degree=2) >>> point = np.asfortranarray([ ... [0.59375], ... [0.25 ], ... ]) >>> s, t = surface.locate(point) >>> s 0.5 >>> t 0.25 .. testcleanup:: surface-locate import make_images make_images.surface_locate(surface, point) Args: point (numpy.ndarray): A (``D x 1``) point on the surface, where :math:`D` is the dimension of the surface. _verify (Optional[bool]): Indicates if extra caution should be used to verify assumptions about the inputs. Can be disabled to speed up execution time. Defaults to :data:`True`. Returns: Optional[Tuple[float, float]]: The :math:`s` and :math:`t` values corresponding to ``point`` or :data:`None` if the point is not on the surface. Raises: NotImplementedError: If the surface isn't in :math:`\mathbf{R}^2`. ValueError: If the dimension of the ``point`` doesn't match the dimension of the current surface.
[ "r", "Find", "a", "point", "on", "the", "current", "surface", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/surface.py#L877-L946
dhermes/bezier
src/bezier/surface.py
Surface.intersect
def intersect(self, other, strategy=_STRATEGY.GEOMETRIC, _verify=True): """Find the common intersection with another surface. Args: other (Surface): Other surface to intersect with. strategy (Optional[~bezier.curve.IntersectionStrategy]): The intersection algorithm to use. Defaults to geometric. _verify (Optional[bool]): Indicates if extra caution should be used to verify assumptions about the algorithm as it proceeds. Can be disabled to speed up execution time. Defaults to :data:`True`. Returns: List[Union[~bezier.curved_polygon.CurvedPolygon, \ ~bezier.surface.Surface]]: List of intersections (possibly empty). Raises: TypeError: If ``other`` is not a surface (and ``_verify=True``). NotImplementedError: If at least one of the surfaces isn't two-dimensional (and ``_verify=True``). ValueError: If ``strategy`` is not a valid :class:`.IntersectionStrategy`. """ if _verify: if not isinstance(other, Surface): raise TypeError( "Can only intersect with another surface", "Received", other, ) if self._dimension != 2 or other._dimension != 2: raise NotImplementedError( "Intersection only implemented in 2D" ) if strategy == _STRATEGY.GEOMETRIC: do_intersect = _surface_intersection.geometric_intersect elif strategy == _STRATEGY.ALGEBRAIC: do_intersect = _surface_intersection.algebraic_intersect else: raise ValueError("Unexpected strategy.", strategy) edge_infos, contained, all_edge_nodes = do_intersect( self._nodes, self._degree, other._nodes, other._degree, _verify ) if edge_infos is None: if contained: return [self] else: return [other] else: return [ _make_intersection(edge_info, all_edge_nodes) for edge_info in edge_infos ]
python
def intersect(self, other, strategy=_STRATEGY.GEOMETRIC, _verify=True): """Find the common intersection with another surface. Args: other (Surface): Other surface to intersect with. strategy (Optional[~bezier.curve.IntersectionStrategy]): The intersection algorithm to use. Defaults to geometric. _verify (Optional[bool]): Indicates if extra caution should be used to verify assumptions about the algorithm as it proceeds. Can be disabled to speed up execution time. Defaults to :data:`True`. Returns: List[Union[~bezier.curved_polygon.CurvedPolygon, \ ~bezier.surface.Surface]]: List of intersections (possibly empty). Raises: TypeError: If ``other`` is not a surface (and ``_verify=True``). NotImplementedError: If at least one of the surfaces isn't two-dimensional (and ``_verify=True``). ValueError: If ``strategy`` is not a valid :class:`.IntersectionStrategy`. """ if _verify: if not isinstance(other, Surface): raise TypeError( "Can only intersect with another surface", "Received", other, ) if self._dimension != 2 or other._dimension != 2: raise NotImplementedError( "Intersection only implemented in 2D" ) if strategy == _STRATEGY.GEOMETRIC: do_intersect = _surface_intersection.geometric_intersect elif strategy == _STRATEGY.ALGEBRAIC: do_intersect = _surface_intersection.algebraic_intersect else: raise ValueError("Unexpected strategy.", strategy) edge_infos, contained, all_edge_nodes = do_intersect( self._nodes, self._degree, other._nodes, other._degree, _verify ) if edge_infos is None: if contained: return [self] else: return [other] else: return [ _make_intersection(edge_info, all_edge_nodes) for edge_info in edge_infos ]
[ "def", "intersect", "(", "self", ",", "other", ",", "strategy", "=", "_STRATEGY", ".", "GEOMETRIC", ",", "_verify", "=", "True", ")", ":", "if", "_verify", ":", "if", "not", "isinstance", "(", "other", ",", "Surface", ")", ":", "raise", "TypeError", "(", "\"Can only intersect with another surface\"", ",", "\"Received\"", ",", "other", ",", ")", "if", "self", ".", "_dimension", "!=", "2", "or", "other", ".", "_dimension", "!=", "2", ":", "raise", "NotImplementedError", "(", "\"Intersection only implemented in 2D\"", ")", "if", "strategy", "==", "_STRATEGY", ".", "GEOMETRIC", ":", "do_intersect", "=", "_surface_intersection", ".", "geometric_intersect", "elif", "strategy", "==", "_STRATEGY", ".", "ALGEBRAIC", ":", "do_intersect", "=", "_surface_intersection", ".", "algebraic_intersect", "else", ":", "raise", "ValueError", "(", "\"Unexpected strategy.\"", ",", "strategy", ")", "edge_infos", ",", "contained", ",", "all_edge_nodes", "=", "do_intersect", "(", "self", ".", "_nodes", ",", "self", ".", "_degree", ",", "other", ".", "_nodes", ",", "other", ".", "_degree", ",", "_verify", ")", "if", "edge_infos", "is", "None", ":", "if", "contained", ":", "return", "[", "self", "]", "else", ":", "return", "[", "other", "]", "else", ":", "return", "[", "_make_intersection", "(", "edge_info", ",", "all_edge_nodes", ")", "for", "edge_info", "in", "edge_infos", "]" ]
Find the common intersection with another surface. Args: other (Surface): Other surface to intersect with. strategy (Optional[~bezier.curve.IntersectionStrategy]): The intersection algorithm to use. Defaults to geometric. _verify (Optional[bool]): Indicates if extra caution should be used to verify assumptions about the algorithm as it proceeds. Can be disabled to speed up execution time. Defaults to :data:`True`. Returns: List[Union[~bezier.curved_polygon.CurvedPolygon, \ ~bezier.surface.Surface]]: List of intersections (possibly empty). Raises: TypeError: If ``other`` is not a surface (and ``_verify=True``). NotImplementedError: If at least one of the surfaces isn't two-dimensional (and ``_verify=True``). ValueError: If ``strategy`` is not a valid :class:`.IntersectionStrategy`.
[ "Find", "the", "common", "intersection", "with", "another", "surface", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/surface.py#L948-L1005
dhermes/bezier
src/bezier/surface.py
Surface.elevate
def elevate(self): r"""Return a degree-elevated version of the current surface. Does this by converting the current nodes :math:`\left\{v_{i, j, k}\right\}_{i + j + k = d}` to new nodes :math:`\left\{w_{i, j, k}\right\}_{i + j + k = d + 1}`. Does so by re-writing .. math:: E\left(\lambda_1, \lambda_2, \lambda_3\right) = \left(\lambda_1 + \lambda_2 + \lambda_3\right) B\left(\lambda_1, \lambda_2, \lambda_3\right) = \sum_{i + j + k = d + 1} \binom{d + 1}{i \, j \, k} \lambda_1^i \lambda_2^j \lambda_3^k \cdot w_{i, j, k} In this form, we must have .. math:: \begin{align*} \binom{d + 1}{i \, j \, k} \cdot w_{i, j, k} &= \binom{d}{i - 1 \, j \, k} \cdot v_{i - 1, j, k} + \binom{d}{i \, j - 1 \, k} \cdot v_{i, j - 1, k} + \binom{d}{i \, j \, k - 1} \cdot v_{i, j, k - 1} \\ \Longleftrightarrow (d + 1) \cdot w_{i, j, k} &= i \cdot v_{i - 1, j, k} + j \cdot v_{i, j - 1, k} + k \cdot v_{i, j, k - 1} \end{align*} where we define, for example, :math:`v_{i, j, k - 1} = 0` if :math:`k = 0`. .. image:: ../../images/surface_elevate.png :align: center .. doctest:: surface-elevate :options: +NORMALIZE_WHITESPACE >>> nodes = np.asfortranarray([ ... [0.0, 1.5, 3.0, 0.75, 2.25, 0.0], ... [0.0, 0.0, 0.0, 1.5 , 2.25, 3.0], ... ]) >>> surface = bezier.Surface(nodes, degree=2) >>> elevated = surface.elevate() >>> elevated <Surface (degree=3, dimension=2)> >>> elevated.nodes array([[0. , 1. , 2. , 3. , 0.5 , 1.5 , 2.5 , 0.5 , 1.5 , 0. ], [0. , 0. , 0. , 0. , 1. , 1.25, 1.5 , 2. , 2.5 , 3. ]]) .. testcleanup:: surface-elevate import make_images make_images.surface_elevate(surface, elevated) Returns: Surface: The degree-elevated surface. """ _, num_nodes = self._nodes.shape # (d + 1)(d + 2)/2 --> (d + 2)(d + 3)/2 num_new = num_nodes + self._degree + 2 new_nodes = np.zeros((self._dimension, num_new), order="F") # NOTE: We start from the index triples (i, j, k) for the current # nodes and map them onto (i + 1, j, k), etc. This index # tracking is also done in :func:`.de_casteljau_one_round`. index = 0 # parent_i1 = index + k # parent_i2 = index + k + 1 # parent_i3 = index + degree + 2 parent_i1 = 0 parent_i2 = 1 parent_i3 = self._degree + 2 for k in six.moves.xrange(self._degree + 1): for j in six.moves.xrange(self._degree + 1 - k): i = self._degree - j - k new_nodes[:, parent_i1] += (i + 1) * self._nodes[:, index] new_nodes[:, parent_i2] += (j + 1) * self._nodes[:, index] new_nodes[:, parent_i3] += (k + 1) * self._nodes[:, index] # Update all the indices. parent_i1 += 1 parent_i2 += 1 parent_i3 += 1 index += 1 # Update the indices that depend on k. parent_i1 += 1 parent_i2 += 1 # Hold off on division until the end, to (attempt to) avoid round-off. denominator = self._degree + 1.0 new_nodes /= denominator return Surface(new_nodes, self._degree + 1, _copy=False)
python
def elevate(self): r"""Return a degree-elevated version of the current surface. Does this by converting the current nodes :math:`\left\{v_{i, j, k}\right\}_{i + j + k = d}` to new nodes :math:`\left\{w_{i, j, k}\right\}_{i + j + k = d + 1}`. Does so by re-writing .. math:: E\left(\lambda_1, \lambda_2, \lambda_3\right) = \left(\lambda_1 + \lambda_2 + \lambda_3\right) B\left(\lambda_1, \lambda_2, \lambda_3\right) = \sum_{i + j + k = d + 1} \binom{d + 1}{i \, j \, k} \lambda_1^i \lambda_2^j \lambda_3^k \cdot w_{i, j, k} In this form, we must have .. math:: \begin{align*} \binom{d + 1}{i \, j \, k} \cdot w_{i, j, k} &= \binom{d}{i - 1 \, j \, k} \cdot v_{i - 1, j, k} + \binom{d}{i \, j - 1 \, k} \cdot v_{i, j - 1, k} + \binom{d}{i \, j \, k - 1} \cdot v_{i, j, k - 1} \\ \Longleftrightarrow (d + 1) \cdot w_{i, j, k} &= i \cdot v_{i - 1, j, k} + j \cdot v_{i, j - 1, k} + k \cdot v_{i, j, k - 1} \end{align*} where we define, for example, :math:`v_{i, j, k - 1} = 0` if :math:`k = 0`. .. image:: ../../images/surface_elevate.png :align: center .. doctest:: surface-elevate :options: +NORMALIZE_WHITESPACE >>> nodes = np.asfortranarray([ ... [0.0, 1.5, 3.0, 0.75, 2.25, 0.0], ... [0.0, 0.0, 0.0, 1.5 , 2.25, 3.0], ... ]) >>> surface = bezier.Surface(nodes, degree=2) >>> elevated = surface.elevate() >>> elevated <Surface (degree=3, dimension=2)> >>> elevated.nodes array([[0. , 1. , 2. , 3. , 0.5 , 1.5 , 2.5 , 0.5 , 1.5 , 0. ], [0. , 0. , 0. , 0. , 1. , 1.25, 1.5 , 2. , 2.5 , 3. ]]) .. testcleanup:: surface-elevate import make_images make_images.surface_elevate(surface, elevated) Returns: Surface: The degree-elevated surface. """ _, num_nodes = self._nodes.shape # (d + 1)(d + 2)/2 --> (d + 2)(d + 3)/2 num_new = num_nodes + self._degree + 2 new_nodes = np.zeros((self._dimension, num_new), order="F") # NOTE: We start from the index triples (i, j, k) for the current # nodes and map them onto (i + 1, j, k), etc. This index # tracking is also done in :func:`.de_casteljau_one_round`. index = 0 # parent_i1 = index + k # parent_i2 = index + k + 1 # parent_i3 = index + degree + 2 parent_i1 = 0 parent_i2 = 1 parent_i3 = self._degree + 2 for k in six.moves.xrange(self._degree + 1): for j in six.moves.xrange(self._degree + 1 - k): i = self._degree - j - k new_nodes[:, parent_i1] += (i + 1) * self._nodes[:, index] new_nodes[:, parent_i2] += (j + 1) * self._nodes[:, index] new_nodes[:, parent_i3] += (k + 1) * self._nodes[:, index] # Update all the indices. parent_i1 += 1 parent_i2 += 1 parent_i3 += 1 index += 1 # Update the indices that depend on k. parent_i1 += 1 parent_i2 += 1 # Hold off on division until the end, to (attempt to) avoid round-off. denominator = self._degree + 1.0 new_nodes /= denominator return Surface(new_nodes, self._degree + 1, _copy=False)
[ "def", "elevate", "(", "self", ")", ":", "_", ",", "num_nodes", "=", "self", ".", "_nodes", ".", "shape", "# (d + 1)(d + 2)/2 --> (d + 2)(d + 3)/2", "num_new", "=", "num_nodes", "+", "self", ".", "_degree", "+", "2", "new_nodes", "=", "np", ".", "zeros", "(", "(", "self", ".", "_dimension", ",", "num_new", ")", ",", "order", "=", "\"F\"", ")", "# NOTE: We start from the index triples (i, j, k) for the current", "# nodes and map them onto (i + 1, j, k), etc. This index", "# tracking is also done in :func:`.de_casteljau_one_round`.", "index", "=", "0", "# parent_i1 = index + k", "# parent_i2 = index + k + 1", "# parent_i3 = index + degree + 2", "parent_i1", "=", "0", "parent_i2", "=", "1", "parent_i3", "=", "self", ".", "_degree", "+", "2", "for", "k", "in", "six", ".", "moves", ".", "xrange", "(", "self", ".", "_degree", "+", "1", ")", ":", "for", "j", "in", "six", ".", "moves", ".", "xrange", "(", "self", ".", "_degree", "+", "1", "-", "k", ")", ":", "i", "=", "self", ".", "_degree", "-", "j", "-", "k", "new_nodes", "[", ":", ",", "parent_i1", "]", "+=", "(", "i", "+", "1", ")", "*", "self", ".", "_nodes", "[", ":", ",", "index", "]", "new_nodes", "[", ":", ",", "parent_i2", "]", "+=", "(", "j", "+", "1", ")", "*", "self", ".", "_nodes", "[", ":", ",", "index", "]", "new_nodes", "[", ":", ",", "parent_i3", "]", "+=", "(", "k", "+", "1", ")", "*", "self", ".", "_nodes", "[", ":", ",", "index", "]", "# Update all the indices.", "parent_i1", "+=", "1", "parent_i2", "+=", "1", "parent_i3", "+=", "1", "index", "+=", "1", "# Update the indices that depend on k.", "parent_i1", "+=", "1", "parent_i2", "+=", "1", "# Hold off on division until the end, to (attempt to) avoid round-off.", "denominator", "=", "self", ".", "_degree", "+", "1.0", "new_nodes", "/=", "denominator", "return", "Surface", "(", "new_nodes", ",", "self", ".", "_degree", "+", "1", ",", "_copy", "=", "False", ")" ]
r"""Return a degree-elevated version of the current surface. Does this by converting the current nodes :math:`\left\{v_{i, j, k}\right\}_{i + j + k = d}` to new nodes :math:`\left\{w_{i, j, k}\right\}_{i + j + k = d + 1}`. Does so by re-writing .. math:: E\left(\lambda_1, \lambda_2, \lambda_3\right) = \left(\lambda_1 + \lambda_2 + \lambda_3\right) B\left(\lambda_1, \lambda_2, \lambda_3\right) = \sum_{i + j + k = d + 1} \binom{d + 1}{i \, j \, k} \lambda_1^i \lambda_2^j \lambda_3^k \cdot w_{i, j, k} In this form, we must have .. math:: \begin{align*} \binom{d + 1}{i \, j \, k} \cdot w_{i, j, k} &= \binom{d}{i - 1 \, j \, k} \cdot v_{i - 1, j, k} + \binom{d}{i \, j - 1 \, k} \cdot v_{i, j - 1, k} + \binom{d}{i \, j \, k - 1} \cdot v_{i, j, k - 1} \\ \Longleftrightarrow (d + 1) \cdot w_{i, j, k} &= i \cdot v_{i - 1, j, k} + j \cdot v_{i, j - 1, k} + k \cdot v_{i, j, k - 1} \end{align*} where we define, for example, :math:`v_{i, j, k - 1} = 0` if :math:`k = 0`. .. image:: ../../images/surface_elevate.png :align: center .. doctest:: surface-elevate :options: +NORMALIZE_WHITESPACE >>> nodes = np.asfortranarray([ ... [0.0, 1.5, 3.0, 0.75, 2.25, 0.0], ... [0.0, 0.0, 0.0, 1.5 , 2.25, 3.0], ... ]) >>> surface = bezier.Surface(nodes, degree=2) >>> elevated = surface.elevate() >>> elevated <Surface (degree=3, dimension=2)> >>> elevated.nodes array([[0. , 1. , 2. , 3. , 0.5 , 1.5 , 2.5 , 0.5 , 1.5 , 0. ], [0. , 0. , 0. , 0. , 1. , 1.25, 1.5 , 2. , 2.5 , 3. ]]) .. testcleanup:: surface-elevate import make_images make_images.surface_elevate(surface, elevated) Returns: Surface: The degree-elevated surface.
[ "r", "Return", "a", "degree", "-", "elevated", "version", "of", "the", "current", "surface", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/surface.py#L1007-L1097
dhermes/bezier
src/bezier/_intersection_helpers.py
_newton_refine
def _newton_refine(s, nodes1, t, nodes2): r"""Apply one step of 2D Newton's method. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. We want to use Newton's method on the function .. math:: F(s, t) = B_1(s) - B_2(t) to refine :math:`\left(s_{\ast}, t_{\ast}\right)`. Using this, and the Jacobian :math:`DF`, we "solve" .. math:: \left[\begin{array}{c} 0 \\ 0 \end{array}\right] \approx F\left(s_{\ast} + \Delta s, t_{\ast} + \Delta t\right) \approx F\left(s_{\ast}, t_{\ast}\right) + \left[\begin{array}{c c} B_1'\left(s_{\ast}\right) & - B_2'\left(t_{\ast}\right) \end{array}\right] \left[\begin{array}{c} \Delta s \\ \Delta t \end{array}\right] and refine with the component updates :math:`\Delta s` and :math:`\Delta t`. .. note:: This implementation assumes the curves live in :math:`\mathbf{R}^2`. For example, the curves .. math:: \begin{align*} B_1(s) &= \left[\begin{array}{c} 0 \\ 0 \end{array}\right] (1 - s)^2 + \left[\begin{array}{c} 2 \\ 4 \end{array}\right] 2s(1 - s) + \left[\begin{array}{c} 4 \\ 0 \end{array}\right] s^2 \\ B_2(t) &= \left[\begin{array}{c} 2 \\ 0 \end{array}\right] (1 - t) + \left[\begin{array}{c} 0 \\ 3 \end{array}\right] t \end{align*} intersect at the point :math:`B_1\left(\frac{1}{4}\right) = B_2\left(\frac{1}{2}\right) = \frac{1}{2} \left[\begin{array}{c} 2 \\ 3 \end{array}\right]`. However, starting from the wrong point we have .. math:: \begin{align*} F\left(\frac{3}{8}, \frac{1}{4}\right) &= \frac{1}{8} \left[\begin{array}{c} 0 \\ 9 \end{array}\right] \\ DF\left(\frac{3}{8}, \frac{1}{4}\right) &= \left[\begin{array}{c c} 4 & 2 \\ 2 & -3 \end{array}\right] \\ \Longrightarrow \left[\begin{array}{c} \Delta s \\ \Delta t \end{array}\right] &= \frac{9}{64} \left[\begin{array}{c} -1 \\ 2 \end{array}\right]. \end{align*} .. image:: ../images/newton_refine1.png :align: center .. testsetup:: newton-refine1, newton-refine2, newton-refine3 import numpy as np import bezier from bezier._intersection_helpers import newton_refine machine_eps = np.finfo(np.float64).eps def cuberoot(value): return np.cbrt(value) .. doctest:: newton-refine1 >>> nodes1 = np.asfortranarray([ ... [0.0, 2.0, 4.0], ... [0.0, 4.0, 0.0], ... ]) >>> nodes2 = np.asfortranarray([ ... [2.0, 0.0], ... [0.0, 3.0], ... ]) >>> s, t = 0.375, 0.25 >>> new_s, new_t = newton_refine(s, nodes1, t, nodes2) >>> 64.0 * (new_s - s) -9.0 >>> 64.0 * (new_t - t) 18.0 .. testcleanup:: newton-refine1 import make_images curve1 = bezier.Curve(nodes1, degree=2) curve2 = bezier.Curve(nodes2, degree=1) make_images.newton_refine1(s, new_s, curve1, t, new_t, curve2) For "typical" curves, we converge to a solution quadratically. This means that the number of correct digits doubles every iteration (until machine precision is reached). .. image:: ../images/newton_refine2.png :align: center .. doctest:: newton-refine2 >>> nodes1 = np.asfortranarray([ ... [0.0, 0.25, 0.5, 0.75, 1.0], ... [0.0, 2.0 , -2.0, 2.0 , 0.0], ... ]) >>> nodes2 = np.asfortranarray([ ... [0.0, 0.25, 0.5, 0.75, 1.0], ... [1.0, 0.5 , 0.5, 0.5 , 0.0], ... ]) >>> # The expected intersection is the only real root of >>> # 28 s^3 - 30 s^2 + 9 s - 1. >>> omega = cuberoot(28.0 * np.sqrt(17.0) + 132.0) / 28.0 >>> expected = 5.0 / 14.0 + omega + 1 / (49.0 * omega) >>> s_vals = [0.625, None, None, None, None] >>> t = 0.625 >>> np.log2(abs(expected - s_vals[0])) -4.399... >>> s_vals[1], t = newton_refine(s_vals[0], nodes1, t, nodes2) >>> np.log2(abs(expected - s_vals[1])) -7.901... >>> s_vals[2], t = newton_refine(s_vals[1], nodes1, t, nodes2) >>> np.log2(abs(expected - s_vals[2])) -16.010... >>> s_vals[3], t = newton_refine(s_vals[2], nodes1, t, nodes2) >>> np.log2(abs(expected - s_vals[3])) -32.110... >>> s_vals[4], t = newton_refine(s_vals[3], nodes1, t, nodes2) >>> np.allclose(s_vals[4], expected, rtol=machine_eps, atol=0.0) True .. testcleanup:: newton-refine2 import make_images curve1 = bezier.Curve(nodes1, degree=4) curve2 = bezier.Curve(nodes2, degree=4) make_images.newton_refine2(s_vals, curve1, curve2) However, when the intersection occurs at a point of tangency, the convergence becomes linear. This means that the number of correct digits added each iteration is roughly constant. .. image:: ../images/newton_refine3.png :align: center .. doctest:: newton-refine3 >>> nodes1 = np.asfortranarray([ ... [0.0, 0.5, 1.0], ... [0.0, 1.0, 0.0], ... ]) >>> nodes2 = np.asfortranarray([ ... [0.0, 1.0], ... [0.5, 0.5], ... ]) >>> expected = 0.5 >>> s_vals = [0.375, None, None, None, None, None] >>> t = 0.375 >>> np.log2(abs(expected - s_vals[0])) -3.0 >>> s_vals[1], t = newton_refine(s_vals[0], nodes1, t, nodes2) >>> np.log2(abs(expected - s_vals[1])) -4.0 >>> s_vals[2], t = newton_refine(s_vals[1], nodes1, t, nodes2) >>> np.log2(abs(expected - s_vals[2])) -5.0 >>> s_vals[3], t = newton_refine(s_vals[2], nodes1, t, nodes2) >>> np.log2(abs(expected - s_vals[3])) -6.0 >>> s_vals[4], t = newton_refine(s_vals[3], nodes1, t, nodes2) >>> np.log2(abs(expected - s_vals[4])) -7.0 >>> s_vals[5], t = newton_refine(s_vals[4], nodes1, t, nodes2) >>> np.log2(abs(expected - s_vals[5])) -8.0 .. testcleanup:: newton-refine3 import make_images curve1 = bezier.Curve(nodes1, degree=2) curve2 = bezier.Curve(nodes2, degree=1) make_images.newton_refine3(s_vals, curve1, curve2) Unfortunately, the process terminates with an error that is not close to machine precision :math:`\varepsilon` when :math:`\Delta s = \Delta t = 0`. .. testsetup:: newton-refine3-continued import numpy as np import bezier from bezier._intersection_helpers import newton_refine nodes1 = np.asfortranarray([ [0.0, 0.5, 1.0], [0.0, 1.0, 0.0], ]) nodes2 = np.asfortranarray([ [0.0, 1.0], [0.5, 0.5], ]) .. doctest:: newton-refine3-continued >>> s1 = t1 = 0.5 - 0.5**27 >>> np.log2(0.5 - s1) -27.0 >>> s2, t2 = newton_refine(s1, nodes1, t1, nodes2) >>> s2 == t2 True >>> np.log2(0.5 - s2) -28.0 >>> s3, t3 = newton_refine(s2, nodes1, t2, nodes2) >>> s3 == t3 == s2 True Due to round-off near the point of tangency, the final error resembles :math:`\sqrt{\varepsilon}` rather than machine precision as expected. .. note:: The following is not implemented in this function. It's just an exploration on how the shortcomings might be addressed. However, this can be overcome. At the point of tangency, we want :math:`B_1'(s) \parallel B_2'(t)`. This can be checked numerically via .. math:: B_1'(s) \times B_2'(t) = 0. For the last example (the one that converges linearly), this is .. math:: 0 = \left[\begin{array}{c} 1 \\ 2 - 4s \end{array}\right] \times \left[\begin{array}{c} 1 \\ 0 \end{array}\right] = 4 s - 2. With this, we can modify Newton's method to find a zero of the over-determined system .. math:: G(s, t) = \left[\begin{array}{c} B_0(s) - B_1(t) \\ B_1'(s) \times B_2'(t) \end{array}\right] = \left[\begin{array}{c} s - t \\ 2 s (1 - s) - \frac{1}{2} \\ 4 s - 2\end{array}\right]. Since :math:`DG` is :math:`3 \times 2`, we can't invert it. However, we can find a least-squares solution: .. math:: \left(DG^T DG\right) \left[\begin{array}{c} \Delta s \\ \Delta t \end{array}\right] = -DG^T G. This only works if :math:`DG` has full rank. In this case, it does since the submatrix containing the first and last rows has rank two: .. math:: DG = \left[\begin{array}{c c} 1 & -1 \\ 2 - 4 s & 0 \\ 4 & 0 \end{array}\right]. Though this avoids a singular system, the normal equations have a condition number that is the square of the condition number of the matrix. Starting from :math:`s = t = \frac{3}{8}` as above: .. testsetup:: newton-refine4 import numpy as np from bezier import _helpers def modified_update(s, t): minus_G = np.asfortranarray([ [t - s], [0.5 - 2.0 * s * (1.0 - s)], [2.0 - 4.0 * s], ]) DG = np.asfortranarray([ [1.0, -1.0], [2.0 - 4.0 * s, 0.0], [4.0, 0.0], ]) DG_t = np.asfortranarray(DG.T) LHS = _helpers.matrix_product(DG_t, DG) RHS = _helpers.matrix_product(DG_t, minus_G) delta_params = np.linalg.solve(LHS, RHS) delta_s, delta_t = delta_params.flatten() return s + delta_s, t + delta_t .. doctest:: newton-refine4 >>> s0, t0 = 0.375, 0.375 >>> np.log2(0.5 - s0) -3.0 >>> s1, t1 = modified_update(s0, t0) >>> s1 == t1 True >>> 1040.0 * s1 519.0 >>> np.log2(0.5 - s1) -10.022... >>> s2, t2 = modified_update(s1, t1) >>> s2 == t2 True >>> np.log2(0.5 - s2) -31.067... >>> s3, t3 = modified_update(s2, t2) >>> s3 == t3 == 0.5 True Args: s (float): Parameter of a near-intersection along the first curve. nodes1 (numpy.ndarray): Nodes of first curve forming intersection. t (float): Parameter of a near-intersection along the second curve. nodes2 (numpy.ndarray): Nodes of second curve forming intersection. Returns: Tuple[float, float]: The refined parameters from a single Newton step. Raises: ValueError: If the Jacobian is singular at ``(s, t)``. """ # NOTE: We form -F(s, t) since we want to solve -DF^{-1} F(s, t). func_val = _curve_helpers.evaluate_multi( nodes2, np.asfortranarray([t]) ) - _curve_helpers.evaluate_multi(nodes1, np.asfortranarray([s])) if np.all(func_val == 0.0): # No refinement is needed. return s, t # NOTE: This assumes the curves are 2D. jac_mat = np.empty((2, 2), order="F") jac_mat[:, :1] = _curve_helpers.evaluate_hodograph(s, nodes1) jac_mat[:, 1:] = -_curve_helpers.evaluate_hodograph(t, nodes2) # Solve the system. singular, delta_s, delta_t = _helpers.solve2x2(jac_mat, func_val[:, 0]) if singular: raise ValueError("Jacobian is singular.") else: return s + delta_s, t + delta_t
python
def _newton_refine(s, nodes1, t, nodes2): r"""Apply one step of 2D Newton's method. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. We want to use Newton's method on the function .. math:: F(s, t) = B_1(s) - B_2(t) to refine :math:`\left(s_{\ast}, t_{\ast}\right)`. Using this, and the Jacobian :math:`DF`, we "solve" .. math:: \left[\begin{array}{c} 0 \\ 0 \end{array}\right] \approx F\left(s_{\ast} + \Delta s, t_{\ast} + \Delta t\right) \approx F\left(s_{\ast}, t_{\ast}\right) + \left[\begin{array}{c c} B_1'\left(s_{\ast}\right) & - B_2'\left(t_{\ast}\right) \end{array}\right] \left[\begin{array}{c} \Delta s \\ \Delta t \end{array}\right] and refine with the component updates :math:`\Delta s` and :math:`\Delta t`. .. note:: This implementation assumes the curves live in :math:`\mathbf{R}^2`. For example, the curves .. math:: \begin{align*} B_1(s) &= \left[\begin{array}{c} 0 \\ 0 \end{array}\right] (1 - s)^2 + \left[\begin{array}{c} 2 \\ 4 \end{array}\right] 2s(1 - s) + \left[\begin{array}{c} 4 \\ 0 \end{array}\right] s^2 \\ B_2(t) &= \left[\begin{array}{c} 2 \\ 0 \end{array}\right] (1 - t) + \left[\begin{array}{c} 0 \\ 3 \end{array}\right] t \end{align*} intersect at the point :math:`B_1\left(\frac{1}{4}\right) = B_2\left(\frac{1}{2}\right) = \frac{1}{2} \left[\begin{array}{c} 2 \\ 3 \end{array}\right]`. However, starting from the wrong point we have .. math:: \begin{align*} F\left(\frac{3}{8}, \frac{1}{4}\right) &= \frac{1}{8} \left[\begin{array}{c} 0 \\ 9 \end{array}\right] \\ DF\left(\frac{3}{8}, \frac{1}{4}\right) &= \left[\begin{array}{c c} 4 & 2 \\ 2 & -3 \end{array}\right] \\ \Longrightarrow \left[\begin{array}{c} \Delta s \\ \Delta t \end{array}\right] &= \frac{9}{64} \left[\begin{array}{c} -1 \\ 2 \end{array}\right]. \end{align*} .. image:: ../images/newton_refine1.png :align: center .. testsetup:: newton-refine1, newton-refine2, newton-refine3 import numpy as np import bezier from bezier._intersection_helpers import newton_refine machine_eps = np.finfo(np.float64).eps def cuberoot(value): return np.cbrt(value) .. doctest:: newton-refine1 >>> nodes1 = np.asfortranarray([ ... [0.0, 2.0, 4.0], ... [0.0, 4.0, 0.0], ... ]) >>> nodes2 = np.asfortranarray([ ... [2.0, 0.0], ... [0.0, 3.0], ... ]) >>> s, t = 0.375, 0.25 >>> new_s, new_t = newton_refine(s, nodes1, t, nodes2) >>> 64.0 * (new_s - s) -9.0 >>> 64.0 * (new_t - t) 18.0 .. testcleanup:: newton-refine1 import make_images curve1 = bezier.Curve(nodes1, degree=2) curve2 = bezier.Curve(nodes2, degree=1) make_images.newton_refine1(s, new_s, curve1, t, new_t, curve2) For "typical" curves, we converge to a solution quadratically. This means that the number of correct digits doubles every iteration (until machine precision is reached). .. image:: ../images/newton_refine2.png :align: center .. doctest:: newton-refine2 >>> nodes1 = np.asfortranarray([ ... [0.0, 0.25, 0.5, 0.75, 1.0], ... [0.0, 2.0 , -2.0, 2.0 , 0.0], ... ]) >>> nodes2 = np.asfortranarray([ ... [0.0, 0.25, 0.5, 0.75, 1.0], ... [1.0, 0.5 , 0.5, 0.5 , 0.0], ... ]) >>> # The expected intersection is the only real root of >>> # 28 s^3 - 30 s^2 + 9 s - 1. >>> omega = cuberoot(28.0 * np.sqrt(17.0) + 132.0) / 28.0 >>> expected = 5.0 / 14.0 + omega + 1 / (49.0 * omega) >>> s_vals = [0.625, None, None, None, None] >>> t = 0.625 >>> np.log2(abs(expected - s_vals[0])) -4.399... >>> s_vals[1], t = newton_refine(s_vals[0], nodes1, t, nodes2) >>> np.log2(abs(expected - s_vals[1])) -7.901... >>> s_vals[2], t = newton_refine(s_vals[1], nodes1, t, nodes2) >>> np.log2(abs(expected - s_vals[2])) -16.010... >>> s_vals[3], t = newton_refine(s_vals[2], nodes1, t, nodes2) >>> np.log2(abs(expected - s_vals[3])) -32.110... >>> s_vals[4], t = newton_refine(s_vals[3], nodes1, t, nodes2) >>> np.allclose(s_vals[4], expected, rtol=machine_eps, atol=0.0) True .. testcleanup:: newton-refine2 import make_images curve1 = bezier.Curve(nodes1, degree=4) curve2 = bezier.Curve(nodes2, degree=4) make_images.newton_refine2(s_vals, curve1, curve2) However, when the intersection occurs at a point of tangency, the convergence becomes linear. This means that the number of correct digits added each iteration is roughly constant. .. image:: ../images/newton_refine3.png :align: center .. doctest:: newton-refine3 >>> nodes1 = np.asfortranarray([ ... [0.0, 0.5, 1.0], ... [0.0, 1.0, 0.0], ... ]) >>> nodes2 = np.asfortranarray([ ... [0.0, 1.0], ... [0.5, 0.5], ... ]) >>> expected = 0.5 >>> s_vals = [0.375, None, None, None, None, None] >>> t = 0.375 >>> np.log2(abs(expected - s_vals[0])) -3.0 >>> s_vals[1], t = newton_refine(s_vals[0], nodes1, t, nodes2) >>> np.log2(abs(expected - s_vals[1])) -4.0 >>> s_vals[2], t = newton_refine(s_vals[1], nodes1, t, nodes2) >>> np.log2(abs(expected - s_vals[2])) -5.0 >>> s_vals[3], t = newton_refine(s_vals[2], nodes1, t, nodes2) >>> np.log2(abs(expected - s_vals[3])) -6.0 >>> s_vals[4], t = newton_refine(s_vals[3], nodes1, t, nodes2) >>> np.log2(abs(expected - s_vals[4])) -7.0 >>> s_vals[5], t = newton_refine(s_vals[4], nodes1, t, nodes2) >>> np.log2(abs(expected - s_vals[5])) -8.0 .. testcleanup:: newton-refine3 import make_images curve1 = bezier.Curve(nodes1, degree=2) curve2 = bezier.Curve(nodes2, degree=1) make_images.newton_refine3(s_vals, curve1, curve2) Unfortunately, the process terminates with an error that is not close to machine precision :math:`\varepsilon` when :math:`\Delta s = \Delta t = 0`. .. testsetup:: newton-refine3-continued import numpy as np import bezier from bezier._intersection_helpers import newton_refine nodes1 = np.asfortranarray([ [0.0, 0.5, 1.0], [0.0, 1.0, 0.0], ]) nodes2 = np.asfortranarray([ [0.0, 1.0], [0.5, 0.5], ]) .. doctest:: newton-refine3-continued >>> s1 = t1 = 0.5 - 0.5**27 >>> np.log2(0.5 - s1) -27.0 >>> s2, t2 = newton_refine(s1, nodes1, t1, nodes2) >>> s2 == t2 True >>> np.log2(0.5 - s2) -28.0 >>> s3, t3 = newton_refine(s2, nodes1, t2, nodes2) >>> s3 == t3 == s2 True Due to round-off near the point of tangency, the final error resembles :math:`\sqrt{\varepsilon}` rather than machine precision as expected. .. note:: The following is not implemented in this function. It's just an exploration on how the shortcomings might be addressed. However, this can be overcome. At the point of tangency, we want :math:`B_1'(s) \parallel B_2'(t)`. This can be checked numerically via .. math:: B_1'(s) \times B_2'(t) = 0. For the last example (the one that converges linearly), this is .. math:: 0 = \left[\begin{array}{c} 1 \\ 2 - 4s \end{array}\right] \times \left[\begin{array}{c} 1 \\ 0 \end{array}\right] = 4 s - 2. With this, we can modify Newton's method to find a zero of the over-determined system .. math:: G(s, t) = \left[\begin{array}{c} B_0(s) - B_1(t) \\ B_1'(s) \times B_2'(t) \end{array}\right] = \left[\begin{array}{c} s - t \\ 2 s (1 - s) - \frac{1}{2} \\ 4 s - 2\end{array}\right]. Since :math:`DG` is :math:`3 \times 2`, we can't invert it. However, we can find a least-squares solution: .. math:: \left(DG^T DG\right) \left[\begin{array}{c} \Delta s \\ \Delta t \end{array}\right] = -DG^T G. This only works if :math:`DG` has full rank. In this case, it does since the submatrix containing the first and last rows has rank two: .. math:: DG = \left[\begin{array}{c c} 1 & -1 \\ 2 - 4 s & 0 \\ 4 & 0 \end{array}\right]. Though this avoids a singular system, the normal equations have a condition number that is the square of the condition number of the matrix. Starting from :math:`s = t = \frac{3}{8}` as above: .. testsetup:: newton-refine4 import numpy as np from bezier import _helpers def modified_update(s, t): minus_G = np.asfortranarray([ [t - s], [0.5 - 2.0 * s * (1.0 - s)], [2.0 - 4.0 * s], ]) DG = np.asfortranarray([ [1.0, -1.0], [2.0 - 4.0 * s, 0.0], [4.0, 0.0], ]) DG_t = np.asfortranarray(DG.T) LHS = _helpers.matrix_product(DG_t, DG) RHS = _helpers.matrix_product(DG_t, minus_G) delta_params = np.linalg.solve(LHS, RHS) delta_s, delta_t = delta_params.flatten() return s + delta_s, t + delta_t .. doctest:: newton-refine4 >>> s0, t0 = 0.375, 0.375 >>> np.log2(0.5 - s0) -3.0 >>> s1, t1 = modified_update(s0, t0) >>> s1 == t1 True >>> 1040.0 * s1 519.0 >>> np.log2(0.5 - s1) -10.022... >>> s2, t2 = modified_update(s1, t1) >>> s2 == t2 True >>> np.log2(0.5 - s2) -31.067... >>> s3, t3 = modified_update(s2, t2) >>> s3 == t3 == 0.5 True Args: s (float): Parameter of a near-intersection along the first curve. nodes1 (numpy.ndarray): Nodes of first curve forming intersection. t (float): Parameter of a near-intersection along the second curve. nodes2 (numpy.ndarray): Nodes of second curve forming intersection. Returns: Tuple[float, float]: The refined parameters from a single Newton step. Raises: ValueError: If the Jacobian is singular at ``(s, t)``. """ # NOTE: We form -F(s, t) since we want to solve -DF^{-1} F(s, t). func_val = _curve_helpers.evaluate_multi( nodes2, np.asfortranarray([t]) ) - _curve_helpers.evaluate_multi(nodes1, np.asfortranarray([s])) if np.all(func_val == 0.0): # No refinement is needed. return s, t # NOTE: This assumes the curves are 2D. jac_mat = np.empty((2, 2), order="F") jac_mat[:, :1] = _curve_helpers.evaluate_hodograph(s, nodes1) jac_mat[:, 1:] = -_curve_helpers.evaluate_hodograph(t, nodes2) # Solve the system. singular, delta_s, delta_t = _helpers.solve2x2(jac_mat, func_val[:, 0]) if singular: raise ValueError("Jacobian is singular.") else: return s + delta_s, t + delta_t
[ "def", "_newton_refine", "(", "s", ",", "nodes1", ",", "t", ",", "nodes2", ")", ":", "# NOTE: We form -F(s, t) since we want to solve -DF^{-1} F(s, t).", "func_val", "=", "_curve_helpers", ".", "evaluate_multi", "(", "nodes2", ",", "np", ".", "asfortranarray", "(", "[", "t", "]", ")", ")", "-", "_curve_helpers", ".", "evaluate_multi", "(", "nodes1", ",", "np", ".", "asfortranarray", "(", "[", "s", "]", ")", ")", "if", "np", ".", "all", "(", "func_val", "==", "0.0", ")", ":", "# No refinement is needed.", "return", "s", ",", "t", "# NOTE: This assumes the curves are 2D.", "jac_mat", "=", "np", ".", "empty", "(", "(", "2", ",", "2", ")", ",", "order", "=", "\"F\"", ")", "jac_mat", "[", ":", ",", ":", "1", "]", "=", "_curve_helpers", ".", "evaluate_hodograph", "(", "s", ",", "nodes1", ")", "jac_mat", "[", ":", ",", "1", ":", "]", "=", "-", "_curve_helpers", ".", "evaluate_hodograph", "(", "t", ",", "nodes2", ")", "# Solve the system.", "singular", ",", "delta_s", ",", "delta_t", "=", "_helpers", ".", "solve2x2", "(", "jac_mat", ",", "func_val", "[", ":", ",", "0", "]", ")", "if", "singular", ":", "raise", "ValueError", "(", "\"Jacobian is singular.\"", ")", "else", ":", "return", "s", "+", "delta_s", ",", "t", "+", "delta_t" ]
r"""Apply one step of 2D Newton's method. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. We want to use Newton's method on the function .. math:: F(s, t) = B_1(s) - B_2(t) to refine :math:`\left(s_{\ast}, t_{\ast}\right)`. Using this, and the Jacobian :math:`DF`, we "solve" .. math:: \left[\begin{array}{c} 0 \\ 0 \end{array}\right] \approx F\left(s_{\ast} + \Delta s, t_{\ast} + \Delta t\right) \approx F\left(s_{\ast}, t_{\ast}\right) + \left[\begin{array}{c c} B_1'\left(s_{\ast}\right) & - B_2'\left(t_{\ast}\right) \end{array}\right] \left[\begin{array}{c} \Delta s \\ \Delta t \end{array}\right] and refine with the component updates :math:`\Delta s` and :math:`\Delta t`. .. note:: This implementation assumes the curves live in :math:`\mathbf{R}^2`. For example, the curves .. math:: \begin{align*} B_1(s) &= \left[\begin{array}{c} 0 \\ 0 \end{array}\right] (1 - s)^2 + \left[\begin{array}{c} 2 \\ 4 \end{array}\right] 2s(1 - s) + \left[\begin{array}{c} 4 \\ 0 \end{array}\right] s^2 \\ B_2(t) &= \left[\begin{array}{c} 2 \\ 0 \end{array}\right] (1 - t) + \left[\begin{array}{c} 0 \\ 3 \end{array}\right] t \end{align*} intersect at the point :math:`B_1\left(\frac{1}{4}\right) = B_2\left(\frac{1}{2}\right) = \frac{1}{2} \left[\begin{array}{c} 2 \\ 3 \end{array}\right]`. However, starting from the wrong point we have .. math:: \begin{align*} F\left(\frac{3}{8}, \frac{1}{4}\right) &= \frac{1}{8} \left[\begin{array}{c} 0 \\ 9 \end{array}\right] \\ DF\left(\frac{3}{8}, \frac{1}{4}\right) &= \left[\begin{array}{c c} 4 & 2 \\ 2 & -3 \end{array}\right] \\ \Longrightarrow \left[\begin{array}{c} \Delta s \\ \Delta t \end{array}\right] &= \frac{9}{64} \left[\begin{array}{c} -1 \\ 2 \end{array}\right]. \end{align*} .. image:: ../images/newton_refine1.png :align: center .. testsetup:: newton-refine1, newton-refine2, newton-refine3 import numpy as np import bezier from bezier._intersection_helpers import newton_refine machine_eps = np.finfo(np.float64).eps def cuberoot(value): return np.cbrt(value) .. doctest:: newton-refine1 >>> nodes1 = np.asfortranarray([ ... [0.0, 2.0, 4.0], ... [0.0, 4.0, 0.0], ... ]) >>> nodes2 = np.asfortranarray([ ... [2.0, 0.0], ... [0.0, 3.0], ... ]) >>> s, t = 0.375, 0.25 >>> new_s, new_t = newton_refine(s, nodes1, t, nodes2) >>> 64.0 * (new_s - s) -9.0 >>> 64.0 * (new_t - t) 18.0 .. testcleanup:: newton-refine1 import make_images curve1 = bezier.Curve(nodes1, degree=2) curve2 = bezier.Curve(nodes2, degree=1) make_images.newton_refine1(s, new_s, curve1, t, new_t, curve2) For "typical" curves, we converge to a solution quadratically. This means that the number of correct digits doubles every iteration (until machine precision is reached). .. image:: ../images/newton_refine2.png :align: center .. doctest:: newton-refine2 >>> nodes1 = np.asfortranarray([ ... [0.0, 0.25, 0.5, 0.75, 1.0], ... [0.0, 2.0 , -2.0, 2.0 , 0.0], ... ]) >>> nodes2 = np.asfortranarray([ ... [0.0, 0.25, 0.5, 0.75, 1.0], ... [1.0, 0.5 , 0.5, 0.5 , 0.0], ... ]) >>> # The expected intersection is the only real root of >>> # 28 s^3 - 30 s^2 + 9 s - 1. >>> omega = cuberoot(28.0 * np.sqrt(17.0) + 132.0) / 28.0 >>> expected = 5.0 / 14.0 + omega + 1 / (49.0 * omega) >>> s_vals = [0.625, None, None, None, None] >>> t = 0.625 >>> np.log2(abs(expected - s_vals[0])) -4.399... >>> s_vals[1], t = newton_refine(s_vals[0], nodes1, t, nodes2) >>> np.log2(abs(expected - s_vals[1])) -7.901... >>> s_vals[2], t = newton_refine(s_vals[1], nodes1, t, nodes2) >>> np.log2(abs(expected - s_vals[2])) -16.010... >>> s_vals[3], t = newton_refine(s_vals[2], nodes1, t, nodes2) >>> np.log2(abs(expected - s_vals[3])) -32.110... >>> s_vals[4], t = newton_refine(s_vals[3], nodes1, t, nodes2) >>> np.allclose(s_vals[4], expected, rtol=machine_eps, atol=0.0) True .. testcleanup:: newton-refine2 import make_images curve1 = bezier.Curve(nodes1, degree=4) curve2 = bezier.Curve(nodes2, degree=4) make_images.newton_refine2(s_vals, curve1, curve2) However, when the intersection occurs at a point of tangency, the convergence becomes linear. This means that the number of correct digits added each iteration is roughly constant. .. image:: ../images/newton_refine3.png :align: center .. doctest:: newton-refine3 >>> nodes1 = np.asfortranarray([ ... [0.0, 0.5, 1.0], ... [0.0, 1.0, 0.0], ... ]) >>> nodes2 = np.asfortranarray([ ... [0.0, 1.0], ... [0.5, 0.5], ... ]) >>> expected = 0.5 >>> s_vals = [0.375, None, None, None, None, None] >>> t = 0.375 >>> np.log2(abs(expected - s_vals[0])) -3.0 >>> s_vals[1], t = newton_refine(s_vals[0], nodes1, t, nodes2) >>> np.log2(abs(expected - s_vals[1])) -4.0 >>> s_vals[2], t = newton_refine(s_vals[1], nodes1, t, nodes2) >>> np.log2(abs(expected - s_vals[2])) -5.0 >>> s_vals[3], t = newton_refine(s_vals[2], nodes1, t, nodes2) >>> np.log2(abs(expected - s_vals[3])) -6.0 >>> s_vals[4], t = newton_refine(s_vals[3], nodes1, t, nodes2) >>> np.log2(abs(expected - s_vals[4])) -7.0 >>> s_vals[5], t = newton_refine(s_vals[4], nodes1, t, nodes2) >>> np.log2(abs(expected - s_vals[5])) -8.0 .. testcleanup:: newton-refine3 import make_images curve1 = bezier.Curve(nodes1, degree=2) curve2 = bezier.Curve(nodes2, degree=1) make_images.newton_refine3(s_vals, curve1, curve2) Unfortunately, the process terminates with an error that is not close to machine precision :math:`\varepsilon` when :math:`\Delta s = \Delta t = 0`. .. testsetup:: newton-refine3-continued import numpy as np import bezier from bezier._intersection_helpers import newton_refine nodes1 = np.asfortranarray([ [0.0, 0.5, 1.0], [0.0, 1.0, 0.0], ]) nodes2 = np.asfortranarray([ [0.0, 1.0], [0.5, 0.5], ]) .. doctest:: newton-refine3-continued >>> s1 = t1 = 0.5 - 0.5**27 >>> np.log2(0.5 - s1) -27.0 >>> s2, t2 = newton_refine(s1, nodes1, t1, nodes2) >>> s2 == t2 True >>> np.log2(0.5 - s2) -28.0 >>> s3, t3 = newton_refine(s2, nodes1, t2, nodes2) >>> s3 == t3 == s2 True Due to round-off near the point of tangency, the final error resembles :math:`\sqrt{\varepsilon}` rather than machine precision as expected. .. note:: The following is not implemented in this function. It's just an exploration on how the shortcomings might be addressed. However, this can be overcome. At the point of tangency, we want :math:`B_1'(s) \parallel B_2'(t)`. This can be checked numerically via .. math:: B_1'(s) \times B_2'(t) = 0. For the last example (the one that converges linearly), this is .. math:: 0 = \left[\begin{array}{c} 1 \\ 2 - 4s \end{array}\right] \times \left[\begin{array}{c} 1 \\ 0 \end{array}\right] = 4 s - 2. With this, we can modify Newton's method to find a zero of the over-determined system .. math:: G(s, t) = \left[\begin{array}{c} B_0(s) - B_1(t) \\ B_1'(s) \times B_2'(t) \end{array}\right] = \left[\begin{array}{c} s - t \\ 2 s (1 - s) - \frac{1}{2} \\ 4 s - 2\end{array}\right]. Since :math:`DG` is :math:`3 \times 2`, we can't invert it. However, we can find a least-squares solution: .. math:: \left(DG^T DG\right) \left[\begin{array}{c} \Delta s \\ \Delta t \end{array}\right] = -DG^T G. This only works if :math:`DG` has full rank. In this case, it does since the submatrix containing the first and last rows has rank two: .. math:: DG = \left[\begin{array}{c c} 1 & -1 \\ 2 - 4 s & 0 \\ 4 & 0 \end{array}\right]. Though this avoids a singular system, the normal equations have a condition number that is the square of the condition number of the matrix. Starting from :math:`s = t = \frac{3}{8}` as above: .. testsetup:: newton-refine4 import numpy as np from bezier import _helpers def modified_update(s, t): minus_G = np.asfortranarray([ [t - s], [0.5 - 2.0 * s * (1.0 - s)], [2.0 - 4.0 * s], ]) DG = np.asfortranarray([ [1.0, -1.0], [2.0 - 4.0 * s, 0.0], [4.0, 0.0], ]) DG_t = np.asfortranarray(DG.T) LHS = _helpers.matrix_product(DG_t, DG) RHS = _helpers.matrix_product(DG_t, minus_G) delta_params = np.linalg.solve(LHS, RHS) delta_s, delta_t = delta_params.flatten() return s + delta_s, t + delta_t .. doctest:: newton-refine4 >>> s0, t0 = 0.375, 0.375 >>> np.log2(0.5 - s0) -3.0 >>> s1, t1 = modified_update(s0, t0) >>> s1 == t1 True >>> 1040.0 * s1 519.0 >>> np.log2(0.5 - s1) -10.022... >>> s2, t2 = modified_update(s1, t1) >>> s2 == t2 True >>> np.log2(0.5 - s2) -31.067... >>> s3, t3 = modified_update(s2, t2) >>> s3 == t3 == 0.5 True Args: s (float): Parameter of a near-intersection along the first curve. nodes1 (numpy.ndarray): Nodes of first curve forming intersection. t (float): Parameter of a near-intersection along the second curve. nodes2 (numpy.ndarray): Nodes of second curve forming intersection. Returns: Tuple[float, float]: The refined parameters from a single Newton step. Raises: ValueError: If the Jacobian is singular at ``(s, t)``.
[ "r", "Apply", "one", "step", "of", "2D", "Newton", "s", "method", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_intersection_helpers.py#L67-L427
dhermes/bezier
src/bezier/_intersection_helpers.py
newton_iterate
def newton_iterate(evaluate_fn, s, t): r"""Perform a Newton iteration. In this function, we assume that :math:`s` and :math:`t` are nonzero, this makes convergence easier to detect since "relative error" at ``0.0`` is not a useful measure. There are several tolerance / threshold quantities used below: * :math:`10` (:attr:`MAX_NEWTON_ITERATIONS`) iterations will be done before "giving up". This is based on the assumption that we are already starting near a root, so quadratic convergence should terminate quickly. * :math:`\tau = \frac{1}{4}` is used as the boundary between linear and superlinear convergence. So if the current error :math:`\|p_{n + 1} - p_n\|` is not smaller than :math:`\tau` times the previous error :math:`\|p_n - p_{n - 1}\|`, then convergence is considered to be linear at that point. * :math:`\frac{2}{3}` of all iterations must be converging linearly for convergence to be stopped (and moved to the next regime). This will only be checked after 4 or more updates have occurred. * :math:`\tau = 2^{-42}` (:attr:`NEWTON_ERROR_RATIO`) is used to determine that an update is sufficiently small to stop iterating. So if the error :math:`\|p_{n + 1} - p_n\|` smaller than :math:`\tau` times size of the term being updated :math:`\|p_n\|`, then we exit with the "correct" answer. It is assumed that ``evaluate_fn`` will use a Jacobian return value of :data:`None` to indicate that :math:`F(s, t)` is exactly ``0.0``. We **assume** that if the function evaluates to exactly ``0.0``, then we are at a solution. It is possible however, that badly parameterized curves can evaluate to exactly ``0.0`` for inputs that are relatively far away from a solution (see issue #21). Args: evaluate_fn (Callable[Tuple[float, float], tuple]): A callable which takes :math:`s` and :math:`t` and produces an evaluated function value and the Jacobian matrix. s (float): The (first) parameter where the iteration will start. t (float): The (second) parameter where the iteration will start. Returns: Tuple[bool, float, float]: The triple of * Flag indicating if the iteration converged. * The current :math:`s` value when the iteration stopped. * The current :math:`t` value when the iteration stopped. """ # Several quantities will be tracked throughout the iteration: # * norm_update_prev: ||p{n} - p{n-1}|| = ||dp{n-1}|| # * norm_update : ||p{n+1} - p{n} || = ||dp{n} || # * linear_updates : This is a count on the number of times that # ``dp{n}`` "looks like" ``dp{n-1}`` (i.e. # is within a constant factor of it). norm_update_prev = None norm_update = None linear_updates = 0 # Track the number of "linear" updates. current_s = s current_t = t for index in six.moves.xrange(MAX_NEWTON_ITERATIONS): jacobian, func_val = evaluate_fn(current_s, current_t) if jacobian is None: return True, current_s, current_t singular, delta_s, delta_t = _helpers.solve2x2( jacobian, func_val[:, 0] ) if singular: break norm_update_prev = norm_update norm_update = np.linalg.norm([delta_s, delta_t], ord=2) # If ||p{n} - p{n-1}|| > 0.25 ||p{n-1} - p{n-2}||, then that means # our convergence is acting linear at the current step. if index > 0 and norm_update > 0.25 * norm_update_prev: linear_updates += 1 # If ``>=2/3`` of the updates have been linear, we are near a # non-simple root. (Make sure at least 5 updates have occurred.) if index >= 4 and 3 * linear_updates >= 2 * index: break # Determine the norm of the "old" solution before updating. norm_soln = np.linalg.norm([current_s, current_t], ord=2) current_s -= delta_s current_t -= delta_t if norm_update < NEWTON_ERROR_RATIO * norm_soln: return True, current_s, current_t return False, current_s, current_t
python
def newton_iterate(evaluate_fn, s, t): r"""Perform a Newton iteration. In this function, we assume that :math:`s` and :math:`t` are nonzero, this makes convergence easier to detect since "relative error" at ``0.0`` is not a useful measure. There are several tolerance / threshold quantities used below: * :math:`10` (:attr:`MAX_NEWTON_ITERATIONS`) iterations will be done before "giving up". This is based on the assumption that we are already starting near a root, so quadratic convergence should terminate quickly. * :math:`\tau = \frac{1}{4}` is used as the boundary between linear and superlinear convergence. So if the current error :math:`\|p_{n + 1} - p_n\|` is not smaller than :math:`\tau` times the previous error :math:`\|p_n - p_{n - 1}\|`, then convergence is considered to be linear at that point. * :math:`\frac{2}{3}` of all iterations must be converging linearly for convergence to be stopped (and moved to the next regime). This will only be checked after 4 or more updates have occurred. * :math:`\tau = 2^{-42}` (:attr:`NEWTON_ERROR_RATIO`) is used to determine that an update is sufficiently small to stop iterating. So if the error :math:`\|p_{n + 1} - p_n\|` smaller than :math:`\tau` times size of the term being updated :math:`\|p_n\|`, then we exit with the "correct" answer. It is assumed that ``evaluate_fn`` will use a Jacobian return value of :data:`None` to indicate that :math:`F(s, t)` is exactly ``0.0``. We **assume** that if the function evaluates to exactly ``0.0``, then we are at a solution. It is possible however, that badly parameterized curves can evaluate to exactly ``0.0`` for inputs that are relatively far away from a solution (see issue #21). Args: evaluate_fn (Callable[Tuple[float, float], tuple]): A callable which takes :math:`s` and :math:`t` and produces an evaluated function value and the Jacobian matrix. s (float): The (first) parameter where the iteration will start. t (float): The (second) parameter where the iteration will start. Returns: Tuple[bool, float, float]: The triple of * Flag indicating if the iteration converged. * The current :math:`s` value when the iteration stopped. * The current :math:`t` value when the iteration stopped. """ # Several quantities will be tracked throughout the iteration: # * norm_update_prev: ||p{n} - p{n-1}|| = ||dp{n-1}|| # * norm_update : ||p{n+1} - p{n} || = ||dp{n} || # * linear_updates : This is a count on the number of times that # ``dp{n}`` "looks like" ``dp{n-1}`` (i.e. # is within a constant factor of it). norm_update_prev = None norm_update = None linear_updates = 0 # Track the number of "linear" updates. current_s = s current_t = t for index in six.moves.xrange(MAX_NEWTON_ITERATIONS): jacobian, func_val = evaluate_fn(current_s, current_t) if jacobian is None: return True, current_s, current_t singular, delta_s, delta_t = _helpers.solve2x2( jacobian, func_val[:, 0] ) if singular: break norm_update_prev = norm_update norm_update = np.linalg.norm([delta_s, delta_t], ord=2) # If ||p{n} - p{n-1}|| > 0.25 ||p{n-1} - p{n-2}||, then that means # our convergence is acting linear at the current step. if index > 0 and norm_update > 0.25 * norm_update_prev: linear_updates += 1 # If ``>=2/3`` of the updates have been linear, we are near a # non-simple root. (Make sure at least 5 updates have occurred.) if index >= 4 and 3 * linear_updates >= 2 * index: break # Determine the norm of the "old" solution before updating. norm_soln = np.linalg.norm([current_s, current_t], ord=2) current_s -= delta_s current_t -= delta_t if norm_update < NEWTON_ERROR_RATIO * norm_soln: return True, current_s, current_t return False, current_s, current_t
[ "def", "newton_iterate", "(", "evaluate_fn", ",", "s", ",", "t", ")", ":", "# Several quantities will be tracked throughout the iteration:", "# * norm_update_prev: ||p{n} - p{n-1}|| = ||dp{n-1}||", "# * norm_update : ||p{n+1} - p{n} || = ||dp{n} ||", "# * linear_updates : This is a count on the number of times that", "# ``dp{n}`` \"looks like\" ``dp{n-1}`` (i.e.", "# is within a constant factor of it).", "norm_update_prev", "=", "None", "norm_update", "=", "None", "linear_updates", "=", "0", "# Track the number of \"linear\" updates.", "current_s", "=", "s", "current_t", "=", "t", "for", "index", "in", "six", ".", "moves", ".", "xrange", "(", "MAX_NEWTON_ITERATIONS", ")", ":", "jacobian", ",", "func_val", "=", "evaluate_fn", "(", "current_s", ",", "current_t", ")", "if", "jacobian", "is", "None", ":", "return", "True", ",", "current_s", ",", "current_t", "singular", ",", "delta_s", ",", "delta_t", "=", "_helpers", ".", "solve2x2", "(", "jacobian", ",", "func_val", "[", ":", ",", "0", "]", ")", "if", "singular", ":", "break", "norm_update_prev", "=", "norm_update", "norm_update", "=", "np", ".", "linalg", ".", "norm", "(", "[", "delta_s", ",", "delta_t", "]", ",", "ord", "=", "2", ")", "# If ||p{n} - p{n-1}|| > 0.25 ||p{n-1} - p{n-2}||, then that means", "# our convergence is acting linear at the current step.", "if", "index", ">", "0", "and", "norm_update", ">", "0.25", "*", "norm_update_prev", ":", "linear_updates", "+=", "1", "# If ``>=2/3`` of the updates have been linear, we are near a", "# non-simple root. (Make sure at least 5 updates have occurred.)", "if", "index", ">=", "4", "and", "3", "*", "linear_updates", ">=", "2", "*", "index", ":", "break", "# Determine the norm of the \"old\" solution before updating.", "norm_soln", "=", "np", ".", "linalg", ".", "norm", "(", "[", "current_s", ",", "current_t", "]", ",", "ord", "=", "2", ")", "current_s", "-=", "delta_s", "current_t", "-=", "delta_t", "if", "norm_update", "<", "NEWTON_ERROR_RATIO", "*", "norm_soln", ":", "return", "True", ",", "current_s", ",", "current_t", "return", "False", ",", "current_s", ",", "current_t" ]
r"""Perform a Newton iteration. In this function, we assume that :math:`s` and :math:`t` are nonzero, this makes convergence easier to detect since "relative error" at ``0.0`` is not a useful measure. There are several tolerance / threshold quantities used below: * :math:`10` (:attr:`MAX_NEWTON_ITERATIONS`) iterations will be done before "giving up". This is based on the assumption that we are already starting near a root, so quadratic convergence should terminate quickly. * :math:`\tau = \frac{1}{4}` is used as the boundary between linear and superlinear convergence. So if the current error :math:`\|p_{n + 1} - p_n\|` is not smaller than :math:`\tau` times the previous error :math:`\|p_n - p_{n - 1}\|`, then convergence is considered to be linear at that point. * :math:`\frac{2}{3}` of all iterations must be converging linearly for convergence to be stopped (and moved to the next regime). This will only be checked after 4 or more updates have occurred. * :math:`\tau = 2^{-42}` (:attr:`NEWTON_ERROR_RATIO`) is used to determine that an update is sufficiently small to stop iterating. So if the error :math:`\|p_{n + 1} - p_n\|` smaller than :math:`\tau` times size of the term being updated :math:`\|p_n\|`, then we exit with the "correct" answer. It is assumed that ``evaluate_fn`` will use a Jacobian return value of :data:`None` to indicate that :math:`F(s, t)` is exactly ``0.0``. We **assume** that if the function evaluates to exactly ``0.0``, then we are at a solution. It is possible however, that badly parameterized curves can evaluate to exactly ``0.0`` for inputs that are relatively far away from a solution (see issue #21). Args: evaluate_fn (Callable[Tuple[float, float], tuple]): A callable which takes :math:`s` and :math:`t` and produces an evaluated function value and the Jacobian matrix. s (float): The (first) parameter where the iteration will start. t (float): The (second) parameter where the iteration will start. Returns: Tuple[bool, float, float]: The triple of * Flag indicating if the iteration converged. * The current :math:`s` value when the iteration stopped. * The current :math:`t` value when the iteration stopped.
[ "r", "Perform", "a", "Newton", "iteration", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_intersection_helpers.py#L645-L732
dhermes/bezier
src/bezier/_intersection_helpers.py
full_newton_nonzero
def full_newton_nonzero(s, nodes1, t, nodes2): r"""Perform a Newton iteration until convergence to a solution. This is the "implementation" for :func:`full_newton`. In this function, we assume that :math:`s` and :math:`t` are nonzero. Args: s (float): The parameter along the first curve where the iteration will start. nodes1 (numpy.ndarray): Control points of the first curve. t (float): The parameter along the second curve where the iteration will start. nodes2 (numpy.ndarray): Control points of the second curve. Returns: Tuple[float, float]: The pair of :math:`s` and :math:`t` values that Newton's method converged to. Raises: NotImplementedError: If Newton's method doesn't converge in either the multiplicity 1 or 2 cases. """ # NOTE: We somewhat replicate code in ``evaluate_hodograph()`` # here. This is so we don't re-compute the nodes for the first # (and possibly second) derivatives every time they are evaluated. _, num_nodes1 = np.shape(nodes1) first_deriv1 = (num_nodes1 - 1) * (nodes1[:, 1:] - nodes1[:, :-1]) _, num_nodes2 = np.shape(nodes2) first_deriv2 = (num_nodes2 - 1) * (nodes2[:, 1:] - nodes2[:, :-1]) evaluate_fn = NewtonSimpleRoot(nodes1, first_deriv1, nodes2, first_deriv2) converged, current_s, current_t = newton_iterate(evaluate_fn, s, t) if converged: return current_s, current_t # If Newton's method did not converge, then assume the root is not simple. second_deriv1 = (num_nodes1 - 2) * ( first_deriv1[:, 1:] - first_deriv1[:, :-1] ) second_deriv2 = (num_nodes2 - 2) * ( first_deriv2[:, 1:] - first_deriv2[:, :-1] ) evaluate_fn = NewtonDoubleRoot( nodes1, first_deriv1, second_deriv1, nodes2, first_deriv2, second_deriv2, ) converged, current_s, current_t = newton_iterate( evaluate_fn, current_s, current_t ) if converged: return current_s, current_t raise NotImplementedError(NEWTON_NO_CONVERGE)
python
def full_newton_nonzero(s, nodes1, t, nodes2): r"""Perform a Newton iteration until convergence to a solution. This is the "implementation" for :func:`full_newton`. In this function, we assume that :math:`s` and :math:`t` are nonzero. Args: s (float): The parameter along the first curve where the iteration will start. nodes1 (numpy.ndarray): Control points of the first curve. t (float): The parameter along the second curve where the iteration will start. nodes2 (numpy.ndarray): Control points of the second curve. Returns: Tuple[float, float]: The pair of :math:`s` and :math:`t` values that Newton's method converged to. Raises: NotImplementedError: If Newton's method doesn't converge in either the multiplicity 1 or 2 cases. """ # NOTE: We somewhat replicate code in ``evaluate_hodograph()`` # here. This is so we don't re-compute the nodes for the first # (and possibly second) derivatives every time they are evaluated. _, num_nodes1 = np.shape(nodes1) first_deriv1 = (num_nodes1 - 1) * (nodes1[:, 1:] - nodes1[:, :-1]) _, num_nodes2 = np.shape(nodes2) first_deriv2 = (num_nodes2 - 1) * (nodes2[:, 1:] - nodes2[:, :-1]) evaluate_fn = NewtonSimpleRoot(nodes1, first_deriv1, nodes2, first_deriv2) converged, current_s, current_t = newton_iterate(evaluate_fn, s, t) if converged: return current_s, current_t # If Newton's method did not converge, then assume the root is not simple. second_deriv1 = (num_nodes1 - 2) * ( first_deriv1[:, 1:] - first_deriv1[:, :-1] ) second_deriv2 = (num_nodes2 - 2) * ( first_deriv2[:, 1:] - first_deriv2[:, :-1] ) evaluate_fn = NewtonDoubleRoot( nodes1, first_deriv1, second_deriv1, nodes2, first_deriv2, second_deriv2, ) converged, current_s, current_t = newton_iterate( evaluate_fn, current_s, current_t ) if converged: return current_s, current_t raise NotImplementedError(NEWTON_NO_CONVERGE)
[ "def", "full_newton_nonzero", "(", "s", ",", "nodes1", ",", "t", ",", "nodes2", ")", ":", "# NOTE: We somewhat replicate code in ``evaluate_hodograph()``", "# here. This is so we don't re-compute the nodes for the first", "# (and possibly second) derivatives every time they are evaluated.", "_", ",", "num_nodes1", "=", "np", ".", "shape", "(", "nodes1", ")", "first_deriv1", "=", "(", "num_nodes1", "-", "1", ")", "*", "(", "nodes1", "[", ":", ",", "1", ":", "]", "-", "nodes1", "[", ":", ",", ":", "-", "1", "]", ")", "_", ",", "num_nodes2", "=", "np", ".", "shape", "(", "nodes2", ")", "first_deriv2", "=", "(", "num_nodes2", "-", "1", ")", "*", "(", "nodes2", "[", ":", ",", "1", ":", "]", "-", "nodes2", "[", ":", ",", ":", "-", "1", "]", ")", "evaluate_fn", "=", "NewtonSimpleRoot", "(", "nodes1", ",", "first_deriv1", ",", "nodes2", ",", "first_deriv2", ")", "converged", ",", "current_s", ",", "current_t", "=", "newton_iterate", "(", "evaluate_fn", ",", "s", ",", "t", ")", "if", "converged", ":", "return", "current_s", ",", "current_t", "# If Newton's method did not converge, then assume the root is not simple.", "second_deriv1", "=", "(", "num_nodes1", "-", "2", ")", "*", "(", "first_deriv1", "[", ":", ",", "1", ":", "]", "-", "first_deriv1", "[", ":", ",", ":", "-", "1", "]", ")", "second_deriv2", "=", "(", "num_nodes2", "-", "2", ")", "*", "(", "first_deriv2", "[", ":", ",", "1", ":", "]", "-", "first_deriv2", "[", ":", ",", ":", "-", "1", "]", ")", "evaluate_fn", "=", "NewtonDoubleRoot", "(", "nodes1", ",", "first_deriv1", ",", "second_deriv1", ",", "nodes2", ",", "first_deriv2", ",", "second_deriv2", ",", ")", "converged", ",", "current_s", ",", "current_t", "=", "newton_iterate", "(", "evaluate_fn", ",", "current_s", ",", "current_t", ")", "if", "converged", ":", "return", "current_s", ",", "current_t", "raise", "NotImplementedError", "(", "NEWTON_NO_CONVERGE", ")" ]
r"""Perform a Newton iteration until convergence to a solution. This is the "implementation" for :func:`full_newton`. In this function, we assume that :math:`s` and :math:`t` are nonzero. Args: s (float): The parameter along the first curve where the iteration will start. nodes1 (numpy.ndarray): Control points of the first curve. t (float): The parameter along the second curve where the iteration will start. nodes2 (numpy.ndarray): Control points of the second curve. Returns: Tuple[float, float]: The pair of :math:`s` and :math:`t` values that Newton's method converged to. Raises: NotImplementedError: If Newton's method doesn't converge in either the multiplicity 1 or 2 cases.
[ "r", "Perform", "a", "Newton", "iteration", "until", "convergence", "to", "a", "solution", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_intersection_helpers.py#L735-L790
dhermes/bezier
src/bezier/_intersection_helpers.py
full_newton
def full_newton(s, nodes1, t, nodes2): r"""Perform a Newton iteration until convergence to a solution. This assumes :math:`s` and :math:`t` are sufficiently close to an intersection. It **does not** govern the maximum distance away that the solution can lie, though the subdivided intervals that contain :math:`s` and :math:`t` could be used. To avoid round-off issues near ``0.0``, this reverses the direction of a curve and replaces the parameter value :math:`\nu` with :math:`1 - \nu` whenever :math:`\nu < \tau` (here we use a threshold :math:`\tau` equal to :math:`2^{-10}`, i.e. ``ZERO_THRESHOLD``). Args: s (float): The parameter along the first curve where the iteration will start. nodes1 (numpy.ndarray): Control points of the first curve. t (float): The parameter along the second curve where the iteration will start. nodes2 (numpy.ndarray): Control points of the second curve. Returns: Tuple[float, float]: The pair of :math:`s` and :math:`t` values that Newton's method converged to. """ if s < ZERO_THRESHOLD: reversed1 = np.asfortranarray(nodes1[:, ::-1]) if t < ZERO_THRESHOLD: reversed2 = np.asfortranarray(nodes2[:, ::-1]) refined_s, refined_t = full_newton_nonzero( 1.0 - s, reversed1, 1.0 - t, reversed2 ) return 1.0 - refined_s, 1.0 - refined_t else: refined_s, refined_t = full_newton_nonzero( 1.0 - s, reversed1, t, nodes2 ) return 1.0 - refined_s, refined_t else: if t < ZERO_THRESHOLD: reversed2 = np.asfortranarray(nodes2[:, ::-1]) refined_s, refined_t = full_newton_nonzero( s, nodes1, 1.0 - t, reversed2 ) return refined_s, 1.0 - refined_t else: return full_newton_nonzero(s, nodes1, t, nodes2)
python
def full_newton(s, nodes1, t, nodes2): r"""Perform a Newton iteration until convergence to a solution. This assumes :math:`s` and :math:`t` are sufficiently close to an intersection. It **does not** govern the maximum distance away that the solution can lie, though the subdivided intervals that contain :math:`s` and :math:`t` could be used. To avoid round-off issues near ``0.0``, this reverses the direction of a curve and replaces the parameter value :math:`\nu` with :math:`1 - \nu` whenever :math:`\nu < \tau` (here we use a threshold :math:`\tau` equal to :math:`2^{-10}`, i.e. ``ZERO_THRESHOLD``). Args: s (float): The parameter along the first curve where the iteration will start. nodes1 (numpy.ndarray): Control points of the first curve. t (float): The parameter along the second curve where the iteration will start. nodes2 (numpy.ndarray): Control points of the second curve. Returns: Tuple[float, float]: The pair of :math:`s` and :math:`t` values that Newton's method converged to. """ if s < ZERO_THRESHOLD: reversed1 = np.asfortranarray(nodes1[:, ::-1]) if t < ZERO_THRESHOLD: reversed2 = np.asfortranarray(nodes2[:, ::-1]) refined_s, refined_t = full_newton_nonzero( 1.0 - s, reversed1, 1.0 - t, reversed2 ) return 1.0 - refined_s, 1.0 - refined_t else: refined_s, refined_t = full_newton_nonzero( 1.0 - s, reversed1, t, nodes2 ) return 1.0 - refined_s, refined_t else: if t < ZERO_THRESHOLD: reversed2 = np.asfortranarray(nodes2[:, ::-1]) refined_s, refined_t = full_newton_nonzero( s, nodes1, 1.0 - t, reversed2 ) return refined_s, 1.0 - refined_t else: return full_newton_nonzero(s, nodes1, t, nodes2)
[ "def", "full_newton", "(", "s", ",", "nodes1", ",", "t", ",", "nodes2", ")", ":", "if", "s", "<", "ZERO_THRESHOLD", ":", "reversed1", "=", "np", ".", "asfortranarray", "(", "nodes1", "[", ":", ",", ":", ":", "-", "1", "]", ")", "if", "t", "<", "ZERO_THRESHOLD", ":", "reversed2", "=", "np", ".", "asfortranarray", "(", "nodes2", "[", ":", ",", ":", ":", "-", "1", "]", ")", "refined_s", ",", "refined_t", "=", "full_newton_nonzero", "(", "1.0", "-", "s", ",", "reversed1", ",", "1.0", "-", "t", ",", "reversed2", ")", "return", "1.0", "-", "refined_s", ",", "1.0", "-", "refined_t", "else", ":", "refined_s", ",", "refined_t", "=", "full_newton_nonzero", "(", "1.0", "-", "s", ",", "reversed1", ",", "t", ",", "nodes2", ")", "return", "1.0", "-", "refined_s", ",", "refined_t", "else", ":", "if", "t", "<", "ZERO_THRESHOLD", ":", "reversed2", "=", "np", ".", "asfortranarray", "(", "nodes2", "[", ":", ",", ":", ":", "-", "1", "]", ")", "refined_s", ",", "refined_t", "=", "full_newton_nonzero", "(", "s", ",", "nodes1", ",", "1.0", "-", "t", ",", "reversed2", ")", "return", "refined_s", ",", "1.0", "-", "refined_t", "else", ":", "return", "full_newton_nonzero", "(", "s", ",", "nodes1", ",", "t", ",", "nodes2", ")" ]
r"""Perform a Newton iteration until convergence to a solution. This assumes :math:`s` and :math:`t` are sufficiently close to an intersection. It **does not** govern the maximum distance away that the solution can lie, though the subdivided intervals that contain :math:`s` and :math:`t` could be used. To avoid round-off issues near ``0.0``, this reverses the direction of a curve and replaces the parameter value :math:`\nu` with :math:`1 - \nu` whenever :math:`\nu < \tau` (here we use a threshold :math:`\tau` equal to :math:`2^{-10}`, i.e. ``ZERO_THRESHOLD``). Args: s (float): The parameter along the first curve where the iteration will start. nodes1 (numpy.ndarray): Control points of the first curve. t (float): The parameter along the second curve where the iteration will start. nodes2 (numpy.ndarray): Control points of the second curve. Returns: Tuple[float, float]: The pair of :math:`s` and :math:`t` values that Newton's method converged to.
[ "r", "Perform", "a", "Newton", "iteration", "until", "convergence", "to", "a", "solution", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_intersection_helpers.py#L793-L842
dhermes/bezier
setup_helpers.py
gfortran_search_path
def gfortran_search_path(library_dirs): """Get the library directory paths for ``gfortran``. Looks for ``libraries: =`` in the output of ``gfortran -print-search-dirs`` and then parses the paths. If this fails for any reason, this method will print an error and return ``library_dirs``. Args: library_dirs (List[str]): Existing library directories. Returns: List[str]: The library directories for ``gfortran``. """ cmd = ("gfortran", "-print-search-dirs") process = subprocess.Popen(cmd, stdout=subprocess.PIPE) return_code = process.wait() # Bail out if the command failed. if return_code != 0: return library_dirs cmd_output = process.stdout.read().decode("utf-8") # Find single line starting with ``libraries: ``. search_lines = cmd_output.strip().split("\n") library_lines = [ line[len(FORTRAN_LIBRARY_PREFIX) :] for line in search_lines if line.startswith(FORTRAN_LIBRARY_PREFIX) ] if len(library_lines) != 1: msg = GFORTRAN_MISSING_LIBS.format(cmd_output) print(msg, file=sys.stderr) return library_dirs # Go through each library in the ``libraries: = ...`` line. library_line = library_lines[0] accepted = set(library_dirs) for part in library_line.split(os.pathsep): full_path = os.path.abspath(part.strip()) if os.path.isdir(full_path): accepted.add(full_path) else: # Ignore anything that isn't a directory. msg = GFORTRAN_BAD_PATH.format(full_path) print(msg, file=sys.stderr) return sorted(accepted)
python
def gfortran_search_path(library_dirs): """Get the library directory paths for ``gfortran``. Looks for ``libraries: =`` in the output of ``gfortran -print-search-dirs`` and then parses the paths. If this fails for any reason, this method will print an error and return ``library_dirs``. Args: library_dirs (List[str]): Existing library directories. Returns: List[str]: The library directories for ``gfortran``. """ cmd = ("gfortran", "-print-search-dirs") process = subprocess.Popen(cmd, stdout=subprocess.PIPE) return_code = process.wait() # Bail out if the command failed. if return_code != 0: return library_dirs cmd_output = process.stdout.read().decode("utf-8") # Find single line starting with ``libraries: ``. search_lines = cmd_output.strip().split("\n") library_lines = [ line[len(FORTRAN_LIBRARY_PREFIX) :] for line in search_lines if line.startswith(FORTRAN_LIBRARY_PREFIX) ] if len(library_lines) != 1: msg = GFORTRAN_MISSING_LIBS.format(cmd_output) print(msg, file=sys.stderr) return library_dirs # Go through each library in the ``libraries: = ...`` line. library_line = library_lines[0] accepted = set(library_dirs) for part in library_line.split(os.pathsep): full_path = os.path.abspath(part.strip()) if os.path.isdir(full_path): accepted.add(full_path) else: # Ignore anything that isn't a directory. msg = GFORTRAN_BAD_PATH.format(full_path) print(msg, file=sys.stderr) return sorted(accepted)
[ "def", "gfortran_search_path", "(", "library_dirs", ")", ":", "cmd", "=", "(", "\"gfortran\"", ",", "\"-print-search-dirs\"", ")", "process", "=", "subprocess", ".", "Popen", "(", "cmd", ",", "stdout", "=", "subprocess", ".", "PIPE", ")", "return_code", "=", "process", ".", "wait", "(", ")", "# Bail out if the command failed.", "if", "return_code", "!=", "0", ":", "return", "library_dirs", "cmd_output", "=", "process", ".", "stdout", ".", "read", "(", ")", ".", "decode", "(", "\"utf-8\"", ")", "# Find single line starting with ``libraries: ``.", "search_lines", "=", "cmd_output", ".", "strip", "(", ")", ".", "split", "(", "\"\\n\"", ")", "library_lines", "=", "[", "line", "[", "len", "(", "FORTRAN_LIBRARY_PREFIX", ")", ":", "]", "for", "line", "in", "search_lines", "if", "line", ".", "startswith", "(", "FORTRAN_LIBRARY_PREFIX", ")", "]", "if", "len", "(", "library_lines", ")", "!=", "1", ":", "msg", "=", "GFORTRAN_MISSING_LIBS", ".", "format", "(", "cmd_output", ")", "print", "(", "msg", ",", "file", "=", "sys", ".", "stderr", ")", "return", "library_dirs", "# Go through each library in the ``libraries: = ...`` line.", "library_line", "=", "library_lines", "[", "0", "]", "accepted", "=", "set", "(", "library_dirs", ")", "for", "part", "in", "library_line", ".", "split", "(", "os", ".", "pathsep", ")", ":", "full_path", "=", "os", ".", "path", ".", "abspath", "(", "part", ".", "strip", "(", ")", ")", "if", "os", ".", "path", ".", "isdir", "(", "full_path", ")", ":", "accepted", ".", "add", "(", "full_path", ")", "else", ":", "# Ignore anything that isn't a directory.", "msg", "=", "GFORTRAN_BAD_PATH", ".", "format", "(", "full_path", ")", "print", "(", "msg", ",", "file", "=", "sys", ".", "stderr", ")", "return", "sorted", "(", "accepted", ")" ]
Get the library directory paths for ``gfortran``. Looks for ``libraries: =`` in the output of ``gfortran -print-search-dirs`` and then parses the paths. If this fails for any reason, this method will print an error and return ``library_dirs``. Args: library_dirs (List[str]): Existing library directories. Returns: List[str]: The library directories for ``gfortran``.
[ "Get", "the", "library", "directory", "paths", "for", "gfortran", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/setup_helpers.py#L96-L140
dhermes/bezier
setup_helpers.py
_update_flags
def _update_flags(compiler_flags, remove_flags=()): """Update a given set of compiler flags. Args: compiler_flags (List[str]): Existing flags associated with a compiler. remove_flags (Optional[Container[str]]): A container of flags to remove that will override any of the defaults. Returns: List[str]: The modified list (i.e. some flags added and some removed). """ for flag in GFORTRAN_SHARED_FLAGS: if flag not in compiler_flags: compiler_flags.append(flag) if DEBUG_ENV in os.environ: to_add = GFORTRAN_DEBUG_FLAGS to_remove = GFORTRAN_OPTIMIZE_FLAGS else: to_add = GFORTRAN_OPTIMIZE_FLAGS if os.environ.get(WHEEL_ENV) is None: to_add += (GFORTRAN_NATIVE_FLAG,) to_remove = GFORTRAN_DEBUG_FLAGS for flag in to_add: if flag not in compiler_flags: compiler_flags.append(flag) return [ flag for flag in compiler_flags if not (flag in to_remove or flag in remove_flags) ]
python
def _update_flags(compiler_flags, remove_flags=()): """Update a given set of compiler flags. Args: compiler_flags (List[str]): Existing flags associated with a compiler. remove_flags (Optional[Container[str]]): A container of flags to remove that will override any of the defaults. Returns: List[str]: The modified list (i.e. some flags added and some removed). """ for flag in GFORTRAN_SHARED_FLAGS: if flag not in compiler_flags: compiler_flags.append(flag) if DEBUG_ENV in os.environ: to_add = GFORTRAN_DEBUG_FLAGS to_remove = GFORTRAN_OPTIMIZE_FLAGS else: to_add = GFORTRAN_OPTIMIZE_FLAGS if os.environ.get(WHEEL_ENV) is None: to_add += (GFORTRAN_NATIVE_FLAG,) to_remove = GFORTRAN_DEBUG_FLAGS for flag in to_add: if flag not in compiler_flags: compiler_flags.append(flag) return [ flag for flag in compiler_flags if not (flag in to_remove or flag in remove_flags) ]
[ "def", "_update_flags", "(", "compiler_flags", ",", "remove_flags", "=", "(", ")", ")", ":", "for", "flag", "in", "GFORTRAN_SHARED_FLAGS", ":", "if", "flag", "not", "in", "compiler_flags", ":", "compiler_flags", ".", "append", "(", "flag", ")", "if", "DEBUG_ENV", "in", "os", ".", "environ", ":", "to_add", "=", "GFORTRAN_DEBUG_FLAGS", "to_remove", "=", "GFORTRAN_OPTIMIZE_FLAGS", "else", ":", "to_add", "=", "GFORTRAN_OPTIMIZE_FLAGS", "if", "os", ".", "environ", ".", "get", "(", "WHEEL_ENV", ")", "is", "None", ":", "to_add", "+=", "(", "GFORTRAN_NATIVE_FLAG", ",", ")", "to_remove", "=", "GFORTRAN_DEBUG_FLAGS", "for", "flag", "in", "to_add", ":", "if", "flag", "not", "in", "compiler_flags", ":", "compiler_flags", ".", "append", "(", "flag", ")", "return", "[", "flag", "for", "flag", "in", "compiler_flags", "if", "not", "(", "flag", "in", "to_remove", "or", "flag", "in", "remove_flags", ")", "]" ]
Update a given set of compiler flags. Args: compiler_flags (List[str]): Existing flags associated with a compiler. remove_flags (Optional[Container[str]]): A container of flags to remove that will override any of the defaults. Returns: List[str]: The modified list (i.e. some flags added and some removed).
[ "Update", "a", "given", "set", "of", "compiler", "flags", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/setup_helpers.py#L178-L207
dhermes/bezier
setup_helpers.py
patch_f90_compiler
def patch_f90_compiler(f90_compiler): """Patch up ``f90_compiler``. For now, only updates the flags for ``gfortran``. In this case, it add any of ``GFORTRAN_SHARED_FLAGS`` that are missing. In debug mode, it also adds any flags in ``GFORTRAN_DEBUG_FLAGS`` and makes sure none of the flags in ``GFORTRAN_OPTIMIZE_FLAGS`` are present. In standard mode ("OPTIMIZE"), makes sure flags in ``GFORTRAN_OPTIMIZE_FLAGS`` are present and flags in ``GFORTRAN_DEBUG_FLAGS`` are not. Args: f90_compiler (numpy.distutils.fcompiler.FCompiler): A Fortran compiler instance. """ # NOTE: NumPy may not be installed, but we don't want **this** module to # cause an import failure in ``setup.py``. from numpy.distutils.fcompiler import gnu # Only ``gfortran``. if not isinstance(f90_compiler, gnu.Gnu95FCompiler): return False f90_compiler.compiler_f77[:] = _update_flags( f90_compiler.compiler_f77, remove_flags=("-Werror",) ) f90_compiler.compiler_f90[:] = _update_flags(f90_compiler.compiler_f90)
python
def patch_f90_compiler(f90_compiler): """Patch up ``f90_compiler``. For now, only updates the flags for ``gfortran``. In this case, it add any of ``GFORTRAN_SHARED_FLAGS`` that are missing. In debug mode, it also adds any flags in ``GFORTRAN_DEBUG_FLAGS`` and makes sure none of the flags in ``GFORTRAN_OPTIMIZE_FLAGS`` are present. In standard mode ("OPTIMIZE"), makes sure flags in ``GFORTRAN_OPTIMIZE_FLAGS`` are present and flags in ``GFORTRAN_DEBUG_FLAGS`` are not. Args: f90_compiler (numpy.distutils.fcompiler.FCompiler): A Fortran compiler instance. """ # NOTE: NumPy may not be installed, but we don't want **this** module to # cause an import failure in ``setup.py``. from numpy.distutils.fcompiler import gnu # Only ``gfortran``. if not isinstance(f90_compiler, gnu.Gnu95FCompiler): return False f90_compiler.compiler_f77[:] = _update_flags( f90_compiler.compiler_f77, remove_flags=("-Werror",) ) f90_compiler.compiler_f90[:] = _update_flags(f90_compiler.compiler_f90)
[ "def", "patch_f90_compiler", "(", "f90_compiler", ")", ":", "# NOTE: NumPy may not be installed, but we don't want **this** module to", "# cause an import failure in ``setup.py``.", "from", "numpy", ".", "distutils", ".", "fcompiler", "import", "gnu", "# Only ``gfortran``.", "if", "not", "isinstance", "(", "f90_compiler", ",", "gnu", ".", "Gnu95FCompiler", ")", ":", "return", "False", "f90_compiler", ".", "compiler_f77", "[", ":", "]", "=", "_update_flags", "(", "f90_compiler", ".", "compiler_f77", ",", "remove_flags", "=", "(", "\"-Werror\"", ",", ")", ")", "f90_compiler", ".", "compiler_f90", "[", ":", "]", "=", "_update_flags", "(", "f90_compiler", ".", "compiler_f90", ")" ]
Patch up ``f90_compiler``. For now, only updates the flags for ``gfortran``. In this case, it add any of ``GFORTRAN_SHARED_FLAGS`` that are missing. In debug mode, it also adds any flags in ``GFORTRAN_DEBUG_FLAGS`` and makes sure none of the flags in ``GFORTRAN_OPTIMIZE_FLAGS`` are present. In standard mode ("OPTIMIZE"), makes sure flags in ``GFORTRAN_OPTIMIZE_FLAGS`` are present and flags in ``GFORTRAN_DEBUG_FLAGS`` are not. Args: f90_compiler (numpy.distutils.fcompiler.FCompiler): A Fortran compiler instance.
[ "Patch", "up", "f90_compiler", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/setup_helpers.py#L210-L235
dhermes/bezier
setup_helpers.py
BuildFortranThenExt.start_journaling
def start_journaling(self): """Capture calls to the system by compilers. See: https://github.com/numpy/numpy/blob/v1.15.2/\ numpy/distutils/ccompiler.py#L154 Intercepts all calls to ``CCompiler.spawn`` and keeps the arguments around to be stored in the local ``commands`` instance attribute. """ import numpy.distutils.ccompiler if self.journal_file is None: return def journaled_spawn(patched_self, cmd, display=None): self.commands.append(cmd) return numpy.distutils.ccompiler.CCompiler_spawn( patched_self, cmd, display=None ) numpy.distutils.ccompiler.replace_method( distutils.ccompiler.CCompiler, "spawn", journaled_spawn )
python
def start_journaling(self): """Capture calls to the system by compilers. See: https://github.com/numpy/numpy/blob/v1.15.2/\ numpy/distutils/ccompiler.py#L154 Intercepts all calls to ``CCompiler.spawn`` and keeps the arguments around to be stored in the local ``commands`` instance attribute. """ import numpy.distutils.ccompiler if self.journal_file is None: return def journaled_spawn(patched_self, cmd, display=None): self.commands.append(cmd) return numpy.distutils.ccompiler.CCompiler_spawn( patched_self, cmd, display=None ) numpy.distutils.ccompiler.replace_method( distutils.ccompiler.CCompiler, "spawn", journaled_spawn )
[ "def", "start_journaling", "(", "self", ")", ":", "import", "numpy", ".", "distutils", ".", "ccompiler", "if", "self", ".", "journal_file", "is", "None", ":", "return", "def", "journaled_spawn", "(", "patched_self", ",", "cmd", ",", "display", "=", "None", ")", ":", "self", ".", "commands", ".", "append", "(", "cmd", ")", "return", "numpy", ".", "distutils", ".", "ccompiler", ".", "CCompiler_spawn", "(", "patched_self", ",", "cmd", ",", "display", "=", "None", ")", "numpy", ".", "distutils", ".", "ccompiler", ".", "replace_method", "(", "distutils", ".", "ccompiler", ".", "CCompiler", ",", "\"spawn\"", ",", "journaled_spawn", ")" ]
Capture calls to the system by compilers. See: https://github.com/numpy/numpy/blob/v1.15.2/\ numpy/distutils/ccompiler.py#L154 Intercepts all calls to ``CCompiler.spawn`` and keeps the arguments around to be stored in the local ``commands`` instance attribute.
[ "Capture", "calls", "to", "the", "system", "by", "compilers", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/setup_helpers.py#L321-L344
dhermes/bezier
setup_helpers.py
BuildFortranThenExt.save_journal
def save_journal(self): """Save journaled commands to file. If there is no active journal, does nothing. If saving the commands to a file fails, a message will be printed to STDERR but the failure will be swallowed so that the extension can be built successfully. """ if self.journal_file is None: return try: as_text = self._commands_to_text() with open(self.journal_file, "w") as file_obj: file_obj.write(as_text) except Exception as exc: msg = BAD_JOURNAL.format(exc) print(msg, file=sys.stderr)
python
def save_journal(self): """Save journaled commands to file. If there is no active journal, does nothing. If saving the commands to a file fails, a message will be printed to STDERR but the failure will be swallowed so that the extension can be built successfully. """ if self.journal_file is None: return try: as_text = self._commands_to_text() with open(self.journal_file, "w") as file_obj: file_obj.write(as_text) except Exception as exc: msg = BAD_JOURNAL.format(exc) print(msg, file=sys.stderr)
[ "def", "save_journal", "(", "self", ")", ":", "if", "self", ".", "journal_file", "is", "None", ":", "return", "try", ":", "as_text", "=", "self", ".", "_commands_to_text", "(", ")", "with", "open", "(", "self", ".", "journal_file", ",", "\"w\"", ")", "as", "file_obj", ":", "file_obj", ".", "write", "(", "as_text", ")", "except", "Exception", "as", "exc", ":", "msg", "=", "BAD_JOURNAL", ".", "format", "(", "exc", ")", "print", "(", "msg", ",", "file", "=", "sys", ".", "stderr", ")" ]
Save journaled commands to file. If there is no active journal, does nothing. If saving the commands to a file fails, a message will be printed to STDERR but the failure will be swallowed so that the extension can be built successfully.
[ "Save", "journaled", "commands", "to", "file", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/setup_helpers.py#L368-L386
dhermes/bezier
setup_helpers.py
BuildFortranThenExt._default_static_lib
def _default_static_lib(self, obj_files): """Create a static library (i.e. a ``.a`` / ``.lib`` file). Args: obj_files (List[str]): List of paths of compiled object files. """ c_compiler = self.F90_COMPILER.c_compiler static_lib_dir = os.path.join(self.build_lib, "bezier", "lib") if not os.path.exists(static_lib_dir): os.makedirs(static_lib_dir) c_compiler.create_static_lib( obj_files, "bezier", output_dir=static_lib_dir ) # NOTE: We must "modify" the paths for the ``extra_objects`` in # each extension since they were compiled with # ``output_dir=self.build_temp``. for extension in self.extensions: extension.extra_objects[:] = [ os.path.join(self.build_temp, rel_path) for rel_path in extension.extra_objects ]
python
def _default_static_lib(self, obj_files): """Create a static library (i.e. a ``.a`` / ``.lib`` file). Args: obj_files (List[str]): List of paths of compiled object files. """ c_compiler = self.F90_COMPILER.c_compiler static_lib_dir = os.path.join(self.build_lib, "bezier", "lib") if not os.path.exists(static_lib_dir): os.makedirs(static_lib_dir) c_compiler.create_static_lib( obj_files, "bezier", output_dir=static_lib_dir ) # NOTE: We must "modify" the paths for the ``extra_objects`` in # each extension since they were compiled with # ``output_dir=self.build_temp``. for extension in self.extensions: extension.extra_objects[:] = [ os.path.join(self.build_temp, rel_path) for rel_path in extension.extra_objects ]
[ "def", "_default_static_lib", "(", "self", ",", "obj_files", ")", ":", "c_compiler", "=", "self", ".", "F90_COMPILER", ".", "c_compiler", "static_lib_dir", "=", "os", ".", "path", ".", "join", "(", "self", ".", "build_lib", ",", "\"bezier\"", ",", "\"lib\"", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "static_lib_dir", ")", ":", "os", ".", "makedirs", "(", "static_lib_dir", ")", "c_compiler", ".", "create_static_lib", "(", "obj_files", ",", "\"bezier\"", ",", "output_dir", "=", "static_lib_dir", ")", "# NOTE: We must \"modify\" the paths for the ``extra_objects`` in", "# each extension since they were compiled with", "# ``output_dir=self.build_temp``.", "for", "extension", "in", "self", ".", "extensions", ":", "extension", ".", "extra_objects", "[", ":", "]", "=", "[", "os", ".", "path", ".", "join", "(", "self", ".", "build_temp", ",", "rel_path", ")", "for", "rel_path", "in", "extension", ".", "extra_objects", "]" ]
Create a static library (i.e. a ``.a`` / ``.lib`` file). Args: obj_files (List[str]): List of paths of compiled object files.
[ "Create", "a", "static", "library", "(", "i", ".", "e", ".", "a", ".", "a", "/", ".", "lib", "file", ")", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/setup_helpers.py#L388-L408
dhermes/bezier
setup_helpers.py
BuildFortranThenExt._default_cleanup
def _default_cleanup(self): """Default cleanup after :meth:`run`. For in-place builds, moves the built shared library into the source directory. """ if not self.inplace: return shutil.move( os.path.join(self.build_lib, "bezier", "lib"), os.path.join("src", "bezier"), )
python
def _default_cleanup(self): """Default cleanup after :meth:`run`. For in-place builds, moves the built shared library into the source directory. """ if not self.inplace: return shutil.move( os.path.join(self.build_lib, "bezier", "lib"), os.path.join("src", "bezier"), )
[ "def", "_default_cleanup", "(", "self", ")", ":", "if", "not", "self", ".", "inplace", ":", "return", "shutil", ".", "move", "(", "os", ".", "path", ".", "join", "(", "self", ".", "build_lib", ",", "\"bezier\"", ",", "\"lib\"", ")", ",", "os", ".", "path", ".", "join", "(", "\"src\"", ",", "\"bezier\"", ")", ",", ")" ]
Default cleanup after :meth:`run`. For in-place builds, moves the built shared library into the source directory.
[ "Default", "cleanup", "after", ":", "meth", ":", "run", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/setup_helpers.py#L434-L446
dhermes/bezier
src/bezier/curved_polygon.py
CurvedPolygon._verify_pair
def _verify_pair(prev, curr): """Verify a pair of sides share an endpoint. .. note:: This currently checks that edge endpoints match **exactly** but allowing some roundoff may be desired. Args: prev (.Curve): "Previous" curve at piecewise junction. curr (.Curve): "Next" curve at piecewise junction. Raises: ValueError: If the previous side is not in 2D. ValueError: If consecutive sides don't share an endpoint. """ if prev._dimension != 2: raise ValueError("Curve not in R^2", prev) end = prev._nodes[:, -1] start = curr._nodes[:, 0] if not _helpers.vector_close(end, start): raise ValueError( "Not sufficiently close", "Consecutive sides do not have common endpoint", prev, curr, )
python
def _verify_pair(prev, curr): """Verify a pair of sides share an endpoint. .. note:: This currently checks that edge endpoints match **exactly** but allowing some roundoff may be desired. Args: prev (.Curve): "Previous" curve at piecewise junction. curr (.Curve): "Next" curve at piecewise junction. Raises: ValueError: If the previous side is not in 2D. ValueError: If consecutive sides don't share an endpoint. """ if prev._dimension != 2: raise ValueError("Curve not in R^2", prev) end = prev._nodes[:, -1] start = curr._nodes[:, 0] if not _helpers.vector_close(end, start): raise ValueError( "Not sufficiently close", "Consecutive sides do not have common endpoint", prev, curr, )
[ "def", "_verify_pair", "(", "prev", ",", "curr", ")", ":", "if", "prev", ".", "_dimension", "!=", "2", ":", "raise", "ValueError", "(", "\"Curve not in R^2\"", ",", "prev", ")", "end", "=", "prev", ".", "_nodes", "[", ":", ",", "-", "1", "]", "start", "=", "curr", ".", "_nodes", "[", ":", ",", "0", "]", "if", "not", "_helpers", ".", "vector_close", "(", "end", ",", "start", ")", ":", "raise", "ValueError", "(", "\"Not sufficiently close\"", ",", "\"Consecutive sides do not have common endpoint\"", ",", "prev", ",", "curr", ",", ")" ]
Verify a pair of sides share an endpoint. .. note:: This currently checks that edge endpoints match **exactly** but allowing some roundoff may be desired. Args: prev (.Curve): "Previous" curve at piecewise junction. curr (.Curve): "Next" curve at piecewise junction. Raises: ValueError: If the previous side is not in 2D. ValueError: If consecutive sides don't share an endpoint.
[ "Verify", "a", "pair", "of", "sides", "share", "an", "endpoint", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/curved_polygon.py#L146-L173
dhermes/bezier
src/bezier/curved_polygon.py
CurvedPolygon._verify
def _verify(self): """Verify that the edges define a curved polygon. This may not be entirely comprehensive, e.g. won't check self-intersection of the defined polygon. .. note:: This currently checks that edge endpoints match **exactly** but allowing some roundoff may be desired. Raises: ValueError: If there are fewer than two sides. ValueError: If one of the sides is not in 2D. ValueError: If consecutive sides don't share an endpoint. """ if self._num_sides < 2: raise ValueError("At least two sides required.") for prev, curr in six.moves.zip(self._edges, self._edges[1:]): self._verify_pair(prev, curr) # Now we check that the final edge wraps around. prev = self._edges[-1] curr = self._edges[0] self._verify_pair(prev, curr)
python
def _verify(self): """Verify that the edges define a curved polygon. This may not be entirely comprehensive, e.g. won't check self-intersection of the defined polygon. .. note:: This currently checks that edge endpoints match **exactly** but allowing some roundoff may be desired. Raises: ValueError: If there are fewer than two sides. ValueError: If one of the sides is not in 2D. ValueError: If consecutive sides don't share an endpoint. """ if self._num_sides < 2: raise ValueError("At least two sides required.") for prev, curr in six.moves.zip(self._edges, self._edges[1:]): self._verify_pair(prev, curr) # Now we check that the final edge wraps around. prev = self._edges[-1] curr = self._edges[0] self._verify_pair(prev, curr)
[ "def", "_verify", "(", "self", ")", ":", "if", "self", ".", "_num_sides", "<", "2", ":", "raise", "ValueError", "(", "\"At least two sides required.\"", ")", "for", "prev", ",", "curr", "in", "six", ".", "moves", ".", "zip", "(", "self", ".", "_edges", ",", "self", ".", "_edges", "[", "1", ":", "]", ")", ":", "self", ".", "_verify_pair", "(", "prev", ",", "curr", ")", "# Now we check that the final edge wraps around.", "prev", "=", "self", ".", "_edges", "[", "-", "1", "]", "curr", "=", "self", ".", "_edges", "[", "0", "]", "self", ".", "_verify_pair", "(", "prev", ",", "curr", ")" ]
Verify that the edges define a curved polygon. This may not be entirely comprehensive, e.g. won't check self-intersection of the defined polygon. .. note:: This currently checks that edge endpoints match **exactly** but allowing some roundoff may be desired. Raises: ValueError: If there are fewer than two sides. ValueError: If one of the sides is not in 2D. ValueError: If consecutive sides don't share an endpoint.
[ "Verify", "that", "the", "edges", "define", "a", "curved", "polygon", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/curved_polygon.py#L175-L199
dhermes/bezier
src/bezier/curved_polygon.py
CurvedPolygon.area
def area(self): r"""The area of the current curved polygon. This assumes, but does not check, that the current curved polygon is valid (i.e. it is bounded by the edges). This computes the area via Green's theorem. Using the vector field :math:`\mathbf{F} = \left[-y, x\right]^T`, since :math:`\partial_x(x) - \partial_y(-y) = 2` Green's theorem says .. math:: \int_{\mathcal{P}} 2 \, d\textbf{x} = \int_{\partial \mathcal{P}} -y \, dx + x \, dy (where :math:`\mathcal{P}` is the current curved polygon). Note that for a given edge :math:`C(r)` with control points :math:`x_j, y_j`, the integral can be simplified: .. math:: \int_C -y \, dx + x \, dy = \int_0^1 (x y' - y x') \, dr = \sum_{i < j} (x_i y_j - y_i x_j) \int_0^1 b_{i, d} b'_{j, d} \, dr where :math:`b_{i, d}, b_{j, d}` are Bernstein basis polynomials. Returns: float: The area of the current curved polygon. """ edges = tuple(edge._nodes for edge in self._edges) return _surface_helpers.compute_area(edges)
python
def area(self): r"""The area of the current curved polygon. This assumes, but does not check, that the current curved polygon is valid (i.e. it is bounded by the edges). This computes the area via Green's theorem. Using the vector field :math:`\mathbf{F} = \left[-y, x\right]^T`, since :math:`\partial_x(x) - \partial_y(-y) = 2` Green's theorem says .. math:: \int_{\mathcal{P}} 2 \, d\textbf{x} = \int_{\partial \mathcal{P}} -y \, dx + x \, dy (where :math:`\mathcal{P}` is the current curved polygon). Note that for a given edge :math:`C(r)` with control points :math:`x_j, y_j`, the integral can be simplified: .. math:: \int_C -y \, dx + x \, dy = \int_0^1 (x y' - y x') \, dr = \sum_{i < j} (x_i y_j - y_i x_j) \int_0^1 b_{i, d} b'_{j, d} \, dr where :math:`b_{i, d}, b_{j, d}` are Bernstein basis polynomials. Returns: float: The area of the current curved polygon. """ edges = tuple(edge._nodes for edge in self._edges) return _surface_helpers.compute_area(edges)
[ "def", "area", "(", "self", ")", ":", "edges", "=", "tuple", "(", "edge", ".", "_nodes", "for", "edge", "in", "self", ".", "_edges", ")", "return", "_surface_helpers", ".", "compute_area", "(", "edges", ")" ]
r"""The area of the current curved polygon. This assumes, but does not check, that the current curved polygon is valid (i.e. it is bounded by the edges). This computes the area via Green's theorem. Using the vector field :math:`\mathbf{F} = \left[-y, x\right]^T`, since :math:`\partial_x(x) - \partial_y(-y) = 2` Green's theorem says .. math:: \int_{\mathcal{P}} 2 \, d\textbf{x} = \int_{\partial \mathcal{P}} -y \, dx + x \, dy (where :math:`\mathcal{P}` is the current curved polygon). Note that for a given edge :math:`C(r)` with control points :math:`x_j, y_j`, the integral can be simplified: .. math:: \int_C -y \, dx + x \, dy = \int_0^1 (x y' - y x') \, dr = \sum_{i < j} (x_i y_j - y_i x_j) \int_0^1 b_{i, d} b'_{j, d} \, dr where :math:`b_{i, d}, b_{j, d}` are Bernstein basis polynomials. Returns: float: The area of the current curved polygon.
[ "r", "The", "area", "of", "the", "current", "curved", "polygon", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/curved_polygon.py#L220-L252
dhermes/bezier
src/bezier/curved_polygon.py
CurvedPolygon.plot
def plot(self, pts_per_edge, color=None, ax=None): """Plot the current curved polygon. Args: pts_per_edge (int): Number of points to plot per curved edge. color (Optional[Tuple[float, float, float]]): Color as RGB profile. ax (Optional[matplotlib.artist.Artist]): matplotlib axis object to add plot to. Returns: matplotlib.artist.Artist: The axis containing the plot. This may be a newly created axis. """ if ax is None: ax = _plot_helpers.new_axis() _plot_helpers.add_patch(ax, color, pts_per_edge, *self._edges) return ax
python
def plot(self, pts_per_edge, color=None, ax=None): """Plot the current curved polygon. Args: pts_per_edge (int): Number of points to plot per curved edge. color (Optional[Tuple[float, float, float]]): Color as RGB profile. ax (Optional[matplotlib.artist.Artist]): matplotlib axis object to add plot to. Returns: matplotlib.artist.Artist: The axis containing the plot. This may be a newly created axis. """ if ax is None: ax = _plot_helpers.new_axis() _plot_helpers.add_patch(ax, color, pts_per_edge, *self._edges) return ax
[ "def", "plot", "(", "self", ",", "pts_per_edge", ",", "color", "=", "None", ",", "ax", "=", "None", ")", ":", "if", "ax", "is", "None", ":", "ax", "=", "_plot_helpers", ".", "new_axis", "(", ")", "_plot_helpers", ".", "add_patch", "(", "ax", ",", "color", ",", "pts_per_edge", ",", "*", "self", ".", "_edges", ")", "return", "ax" ]
Plot the current curved polygon. Args: pts_per_edge (int): Number of points to plot per curved edge. color (Optional[Tuple[float, float, float]]): Color as RGB profile. ax (Optional[matplotlib.artist.Artist]): matplotlib axis object to add plot to. Returns: matplotlib.artist.Artist: The axis containing the plot. This may be a newly created axis.
[ "Plot", "the", "current", "curved", "polygon", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/curved_polygon.py#L264-L280
dhermes/bezier
src/bezier/_clipping.py
compute_implicit_line
def compute_implicit_line(nodes): """Compute the implicit form of the line connecting curve endpoints. .. note:: This assumes, but does not check, that the first and last nodes in ``nodes`` are different. Computes :math:`a, b` and :math:`c` in the normalized implicit equation for the line .. math:: ax + by + c = 0 where :math:`a^2 + b^2 = 1` (only unique up to sign). Args: nodes (numpy.ndarray): ``2 x N`` array of nodes in a curve. The line will be (directed) from the first to last node in ``nodes``. Returns: Tuple[float, float, float]: The triple of * The :math:`x` coefficient :math:`a` * The :math:`y` coefficient :math:`b` * The constant :math:`c` """ delta = nodes[:, -1] - nodes[:, 0] length = np.linalg.norm(delta, ord=2) # Normalize and rotate 90 degrees to the "left". coeff_a = -delta[1] / length coeff_b = delta[0] / length # c = - ax - by = (delta[1] x - delta[0] y) / L # NOTE: We divide by ``length`` at the end to "put off" rounding. coeff_c = (delta[1] * nodes[0, 0] - delta[0] * nodes[1, 0]) / length return coeff_a, coeff_b, coeff_c
python
def compute_implicit_line(nodes): """Compute the implicit form of the line connecting curve endpoints. .. note:: This assumes, but does not check, that the first and last nodes in ``nodes`` are different. Computes :math:`a, b` and :math:`c` in the normalized implicit equation for the line .. math:: ax + by + c = 0 where :math:`a^2 + b^2 = 1` (only unique up to sign). Args: nodes (numpy.ndarray): ``2 x N`` array of nodes in a curve. The line will be (directed) from the first to last node in ``nodes``. Returns: Tuple[float, float, float]: The triple of * The :math:`x` coefficient :math:`a` * The :math:`y` coefficient :math:`b` * The constant :math:`c` """ delta = nodes[:, -1] - nodes[:, 0] length = np.linalg.norm(delta, ord=2) # Normalize and rotate 90 degrees to the "left". coeff_a = -delta[1] / length coeff_b = delta[0] / length # c = - ax - by = (delta[1] x - delta[0] y) / L # NOTE: We divide by ``length`` at the end to "put off" rounding. coeff_c = (delta[1] * nodes[0, 0] - delta[0] * nodes[1, 0]) / length return coeff_a, coeff_b, coeff_c
[ "def", "compute_implicit_line", "(", "nodes", ")", ":", "delta", "=", "nodes", "[", ":", ",", "-", "1", "]", "-", "nodes", "[", ":", ",", "0", "]", "length", "=", "np", ".", "linalg", ".", "norm", "(", "delta", ",", "ord", "=", "2", ")", "# Normalize and rotate 90 degrees to the \"left\".", "coeff_a", "=", "-", "delta", "[", "1", "]", "/", "length", "coeff_b", "=", "delta", "[", "0", "]", "/", "length", "# c = - ax - by = (delta[1] x - delta[0] y) / L", "# NOTE: We divide by ``length`` at the end to \"put off\" rounding.", "coeff_c", "=", "(", "delta", "[", "1", "]", "*", "nodes", "[", "0", ",", "0", "]", "-", "delta", "[", "0", "]", "*", "nodes", "[", "1", ",", "0", "]", ")", "/", "length", "return", "coeff_a", ",", "coeff_b", ",", "coeff_c" ]
Compute the implicit form of the line connecting curve endpoints. .. note:: This assumes, but does not check, that the first and last nodes in ``nodes`` are different. Computes :math:`a, b` and :math:`c` in the normalized implicit equation for the line .. math:: ax + by + c = 0 where :math:`a^2 + b^2 = 1` (only unique up to sign). Args: nodes (numpy.ndarray): ``2 x N`` array of nodes in a curve. The line will be (directed) from the first to last node in ``nodes``. Returns: Tuple[float, float, float]: The triple of * The :math:`x` coefficient :math:`a` * The :math:`y` coefficient :math:`b` * The constant :math:`c`
[ "Compute", "the", "implicit", "form", "of", "the", "line", "connecting", "curve", "endpoints", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_clipping.py#L41-L78
dhermes/bezier
src/bezier/_clipping.py
compute_fat_line
def compute_fat_line(nodes): """Compute the "fat line" around a B |eacute| zier curve. Both computes the implicit (normalized) form .. math:: ax + by + c = 0 for the line connecting the first and last node in ``nodes``. Also computes the maximum and minimum distances to that line from each control point. Args: nodes (numpy.ndarray): ``2 x N`` array of nodes in a curve. Returns: Tuple[float, float, float, float, float]: The 5-tuple of * The :math:`x` coefficient :math:`a` * The :math:`y` coefficient :math:`b` * The constant :math:`c` * The "minimum" distance to the fat line among the control points. * The "maximum" distance to the fat line among the control points. """ coeff_a, coeff_b, coeff_c = compute_implicit_line(nodes) # NOTE: This assumes, but does not check, that there are two rows. _, num_nodes = nodes.shape d_min = 0.0 d_max = 0.0 for index in six.moves.xrange(1, num_nodes - 1): # Only interior nodes. curr_dist = ( coeff_a * nodes[0, index] + coeff_b * nodes[1, index] + coeff_c ) if curr_dist < d_min: d_min = curr_dist elif curr_dist > d_max: d_max = curr_dist return coeff_a, coeff_b, coeff_c, d_min, d_max
python
def compute_fat_line(nodes): """Compute the "fat line" around a B |eacute| zier curve. Both computes the implicit (normalized) form .. math:: ax + by + c = 0 for the line connecting the first and last node in ``nodes``. Also computes the maximum and minimum distances to that line from each control point. Args: nodes (numpy.ndarray): ``2 x N`` array of nodes in a curve. Returns: Tuple[float, float, float, float, float]: The 5-tuple of * The :math:`x` coefficient :math:`a` * The :math:`y` coefficient :math:`b` * The constant :math:`c` * The "minimum" distance to the fat line among the control points. * The "maximum" distance to the fat line among the control points. """ coeff_a, coeff_b, coeff_c = compute_implicit_line(nodes) # NOTE: This assumes, but does not check, that there are two rows. _, num_nodes = nodes.shape d_min = 0.0 d_max = 0.0 for index in six.moves.xrange(1, num_nodes - 1): # Only interior nodes. curr_dist = ( coeff_a * nodes[0, index] + coeff_b * nodes[1, index] + coeff_c ) if curr_dist < d_min: d_min = curr_dist elif curr_dist > d_max: d_max = curr_dist return coeff_a, coeff_b, coeff_c, d_min, d_max
[ "def", "compute_fat_line", "(", "nodes", ")", ":", "coeff_a", ",", "coeff_b", ",", "coeff_c", "=", "compute_implicit_line", "(", "nodes", ")", "# NOTE: This assumes, but does not check, that there are two rows.", "_", ",", "num_nodes", "=", "nodes", ".", "shape", "d_min", "=", "0.0", "d_max", "=", "0.0", "for", "index", "in", "six", ".", "moves", ".", "xrange", "(", "1", ",", "num_nodes", "-", "1", ")", ":", "# Only interior nodes.", "curr_dist", "=", "(", "coeff_a", "*", "nodes", "[", "0", ",", "index", "]", "+", "coeff_b", "*", "nodes", "[", "1", ",", "index", "]", "+", "coeff_c", ")", "if", "curr_dist", "<", "d_min", ":", "d_min", "=", "curr_dist", "elif", "curr_dist", ">", "d_max", ":", "d_max", "=", "curr_dist", "return", "coeff_a", ",", "coeff_b", ",", "coeff_c", ",", "d_min", ",", "d_max" ]
Compute the "fat line" around a B |eacute| zier curve. Both computes the implicit (normalized) form .. math:: ax + by + c = 0 for the line connecting the first and last node in ``nodes``. Also computes the maximum and minimum distances to that line from each control point. Args: nodes (numpy.ndarray): ``2 x N`` array of nodes in a curve. Returns: Tuple[float, float, float, float, float]: The 5-tuple of * The :math:`x` coefficient :math:`a` * The :math:`y` coefficient :math:`b` * The constant :math:`c` * The "minimum" distance to the fat line among the control points. * The "maximum" distance to the fat line among the control points.
[ "Compute", "the", "fat", "line", "around", "a", "B", "|eacute|", "zier", "curve", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_clipping.py#L81-L119
dhermes/bezier
src/bezier/_clipping.py
_update_parameters
def _update_parameters(s_min, s_max, start0, end0, start1, end1): """Update clipped parameter range. .. note:: This is a helper for :func:`clip_range`. Does so by intersecting one of the two fat lines with an edge of the convex hull of the distance polynomial of the curve being clipped. If both of ``s_min`` and ``s_max`` are "unset", then any :math:`s` value that is valid for ``s_min`` would also be valid for ``s_max``. Rather than adding a special case to handle this scenario, **only** ``s_min`` will be updated. In cases where a given parameter :math:`s` would be a valid update for both ``s_min`` and ``s_max`` This function **only** updates ``s_min`` Args: s_min (float): Current start of clipped interval. If "unset", this value will be ``DEFAULT_S_MIN``. s_max (float): Current end of clipped interval. If "unset", this value will be ``DEFAULT_S_MAX``. start0 (numpy.ndarray): A 1D NumPy ``2``-array that is the start vector of one of the two fat lines. end0 (numpy.ndarray): A 1D NumPy ``2``-array that is the end vector of one of the two fat lines. start1 (numpy.ndarray): A 1D NumPy ``2``-array that is the start vector of an edge of the convex hull of the distance polynomial :math:`d(t)` as an explicit B |eacute| zier curve. end1 (numpy.ndarray): A 1D NumPy ``2``-array that is the end vector of an edge of the convex hull of the distance polynomial :math:`d(t)` as an explicit B |eacute| zier curve. Returns: Tuple[float, float]: The (possibly updated) start and end of the clipped parameter range. Raises: NotImplementedError: If the two line segments are parallel. (This case will be supported at some point, just not now.) """ s, t, success = _geometric_intersection.segment_intersection( start0, end0, start1, end1 ) if not success: raise NotImplementedError(NO_PARALLEL) if _helpers.in_interval(t, 0.0, 1.0): if _helpers.in_interval(s, 0.0, s_min): return s, s_max elif _helpers.in_interval(s, s_max, 1.0): return s_min, s return s_min, s_max
python
def _update_parameters(s_min, s_max, start0, end0, start1, end1): """Update clipped parameter range. .. note:: This is a helper for :func:`clip_range`. Does so by intersecting one of the two fat lines with an edge of the convex hull of the distance polynomial of the curve being clipped. If both of ``s_min`` and ``s_max`` are "unset", then any :math:`s` value that is valid for ``s_min`` would also be valid for ``s_max``. Rather than adding a special case to handle this scenario, **only** ``s_min`` will be updated. In cases where a given parameter :math:`s` would be a valid update for both ``s_min`` and ``s_max`` This function **only** updates ``s_min`` Args: s_min (float): Current start of clipped interval. If "unset", this value will be ``DEFAULT_S_MIN``. s_max (float): Current end of clipped interval. If "unset", this value will be ``DEFAULT_S_MAX``. start0 (numpy.ndarray): A 1D NumPy ``2``-array that is the start vector of one of the two fat lines. end0 (numpy.ndarray): A 1D NumPy ``2``-array that is the end vector of one of the two fat lines. start1 (numpy.ndarray): A 1D NumPy ``2``-array that is the start vector of an edge of the convex hull of the distance polynomial :math:`d(t)` as an explicit B |eacute| zier curve. end1 (numpy.ndarray): A 1D NumPy ``2``-array that is the end vector of an edge of the convex hull of the distance polynomial :math:`d(t)` as an explicit B |eacute| zier curve. Returns: Tuple[float, float]: The (possibly updated) start and end of the clipped parameter range. Raises: NotImplementedError: If the two line segments are parallel. (This case will be supported at some point, just not now.) """ s, t, success = _geometric_intersection.segment_intersection( start0, end0, start1, end1 ) if not success: raise NotImplementedError(NO_PARALLEL) if _helpers.in_interval(t, 0.0, 1.0): if _helpers.in_interval(s, 0.0, s_min): return s, s_max elif _helpers.in_interval(s, s_max, 1.0): return s_min, s return s_min, s_max
[ "def", "_update_parameters", "(", "s_min", ",", "s_max", ",", "start0", ",", "end0", ",", "start1", ",", "end1", ")", ":", "s", ",", "t", ",", "success", "=", "_geometric_intersection", ".", "segment_intersection", "(", "start0", ",", "end0", ",", "start1", ",", "end1", ")", "if", "not", "success", ":", "raise", "NotImplementedError", "(", "NO_PARALLEL", ")", "if", "_helpers", ".", "in_interval", "(", "t", ",", "0.0", ",", "1.0", ")", ":", "if", "_helpers", ".", "in_interval", "(", "s", ",", "0.0", ",", "s_min", ")", ":", "return", "s", ",", "s_max", "elif", "_helpers", ".", "in_interval", "(", "s", ",", "s_max", ",", "1.0", ")", ":", "return", "s_min", ",", "s", "return", "s_min", ",", "s_max" ]
Update clipped parameter range. .. note:: This is a helper for :func:`clip_range`. Does so by intersecting one of the two fat lines with an edge of the convex hull of the distance polynomial of the curve being clipped. If both of ``s_min`` and ``s_max`` are "unset", then any :math:`s` value that is valid for ``s_min`` would also be valid for ``s_max``. Rather than adding a special case to handle this scenario, **only** ``s_min`` will be updated. In cases where a given parameter :math:`s` would be a valid update for both ``s_min`` and ``s_max`` This function **only** updates ``s_min`` Args: s_min (float): Current start of clipped interval. If "unset", this value will be ``DEFAULT_S_MIN``. s_max (float): Current end of clipped interval. If "unset", this value will be ``DEFAULT_S_MAX``. start0 (numpy.ndarray): A 1D NumPy ``2``-array that is the start vector of one of the two fat lines. end0 (numpy.ndarray): A 1D NumPy ``2``-array that is the end vector of one of the two fat lines. start1 (numpy.ndarray): A 1D NumPy ``2``-array that is the start vector of an edge of the convex hull of the distance polynomial :math:`d(t)` as an explicit B |eacute| zier curve. end1 (numpy.ndarray): A 1D NumPy ``2``-array that is the end vector of an edge of the convex hull of the distance polynomial :math:`d(t)` as an explicit B |eacute| zier curve. Returns: Tuple[float, float]: The (possibly updated) start and end of the clipped parameter range. Raises: NotImplementedError: If the two line segments are parallel. (This case will be supported at some point, just not now.)
[ "Update", "clipped", "parameter", "range", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_clipping.py#L122-L179
dhermes/bezier
src/bezier/_clipping.py
_check_parameter_range
def _check_parameter_range(s_min, s_max): r"""Performs a final check on a clipped parameter range. .. note:: This is a helper for :func:`clip_range`. If both values are unchanged from the "unset" default, this returns the whole interval :math:`\left[0.0, 1.0\right]`. If only one of the values is set to some parameter :math:`s`, this returns the "degenerate" interval :math:`\left[s, s\right]`. (We rely on the fact that ``s_min`` must be the only set value, based on how :func:`_update_parameters` works.) Otherwise, this simply returns ``[s_min, s_max]``. Args: s_min (float): Current start of clipped interval. If "unset", this value will be ``DEFAULT_S_MIN``. s_max (float): Current end of clipped interval. If "unset", this value will be ``DEFAULT_S_MAX``. Returns: Tuple[float, float]: The (possibly updated) start and end of the clipped parameter range. """ if s_min == DEFAULT_S_MIN: # Based on the way ``_update_parameters`` works, we know # both parameters must be unset if ``s_min``. return 0.0, 1.0 if s_max == DEFAULT_S_MAX: return s_min, s_min return s_min, s_max
python
def _check_parameter_range(s_min, s_max): r"""Performs a final check on a clipped parameter range. .. note:: This is a helper for :func:`clip_range`. If both values are unchanged from the "unset" default, this returns the whole interval :math:`\left[0.0, 1.0\right]`. If only one of the values is set to some parameter :math:`s`, this returns the "degenerate" interval :math:`\left[s, s\right]`. (We rely on the fact that ``s_min`` must be the only set value, based on how :func:`_update_parameters` works.) Otherwise, this simply returns ``[s_min, s_max]``. Args: s_min (float): Current start of clipped interval. If "unset", this value will be ``DEFAULT_S_MIN``. s_max (float): Current end of clipped interval. If "unset", this value will be ``DEFAULT_S_MAX``. Returns: Tuple[float, float]: The (possibly updated) start and end of the clipped parameter range. """ if s_min == DEFAULT_S_MIN: # Based on the way ``_update_parameters`` works, we know # both parameters must be unset if ``s_min``. return 0.0, 1.0 if s_max == DEFAULT_S_MAX: return s_min, s_min return s_min, s_max
[ "def", "_check_parameter_range", "(", "s_min", ",", "s_max", ")", ":", "if", "s_min", "==", "DEFAULT_S_MIN", ":", "# Based on the way ``_update_parameters`` works, we know", "# both parameters must be unset if ``s_min``.", "return", "0.0", ",", "1.0", "if", "s_max", "==", "DEFAULT_S_MAX", ":", "return", "s_min", ",", "s_min", "return", "s_min", ",", "s_max" ]
r"""Performs a final check on a clipped parameter range. .. note:: This is a helper for :func:`clip_range`. If both values are unchanged from the "unset" default, this returns the whole interval :math:`\left[0.0, 1.0\right]`. If only one of the values is set to some parameter :math:`s`, this returns the "degenerate" interval :math:`\left[s, s\right]`. (We rely on the fact that ``s_min`` must be the only set value, based on how :func:`_update_parameters` works.) Otherwise, this simply returns ``[s_min, s_max]``. Args: s_min (float): Current start of clipped interval. If "unset", this value will be ``DEFAULT_S_MIN``. s_max (float): Current end of clipped interval. If "unset", this value will be ``DEFAULT_S_MAX``. Returns: Tuple[float, float]: The (possibly updated) start and end of the clipped parameter range.
[ "r", "Performs", "a", "final", "check", "on", "a", "clipped", "parameter", "range", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_clipping.py#L182-L217
dhermes/bezier
src/bezier/_clipping.py
clip_range
def clip_range(nodes1, nodes2): r"""Reduce the parameter range where two curves can intersect. Does so by using the "fat line" for ``nodes1`` and computing the distance polynomial against ``nodes2``. .. note:: This assumes, but does not check that the curves being considered will only have one intersection in the parameter ranges :math:`s \in \left[0, 1\right]`, :math:`t \in \left[0, 1\right]`. This assumption is based on the fact that B |eacute| zier clipping is meant to be used to find tangent intersections for already subdivided (i.e. sufficiently zoomed in) curve segments. Args: nodes1 (numpy.ndarray): ``2 x N1`` array of nodes in a curve which will define the clipping region. nodes2 (numpy.ndarray): ``2 x N2`` array of nodes in a curve which will be clipped. Returns: Tuple[float, float]: The pair of * The start parameter of the clipped range. * The end parameter of the clipped range. """ # NOTE: There is no corresponding "enable", but the disable only applies # in this lexical scope. # pylint: disable=too-many-locals coeff_a, coeff_b, coeff_c, d_min, d_max = compute_fat_line(nodes1) # NOTE: This assumes, but does not check, that there are two rows. _, num_nodes2 = nodes2.shape polynomial = np.empty((2, num_nodes2), order="F") denominator = float(num_nodes2 - 1) for index in six.moves.xrange(num_nodes2): polynomial[0, index] = index / denominator polynomial[1, index] = ( coeff_a * nodes2[0, index] + coeff_b * nodes2[1, index] + coeff_c ) # Define segments for the top and the bottom of the region # bounded by the fat line. start_bottom = np.asfortranarray([0.0, d_min]) end_bottom = np.asfortranarray([1.0, d_min]) start_top = np.asfortranarray([0.0, d_max]) end_top = np.asfortranarray([1.0, d_max]) s_min = DEFAULT_S_MIN s_max = DEFAULT_S_MAX # NOTE: We avoid computing the convex hull and just compute where # all segments connecting two control points intersect the # fat lines. for start_index in six.moves.xrange(num_nodes2 - 1): for end_index in six.moves.xrange(start_index + 1, num_nodes2): s_min, s_max = _update_parameters( s_min, s_max, start_bottom, end_bottom, polynomial[:, start_index], polynomial[:, end_index], ) s_min, s_max = _update_parameters( s_min, s_max, start_top, end_top, polynomial[:, start_index], polynomial[:, end_index], ) return _check_parameter_range(s_min, s_max)
python
def clip_range(nodes1, nodes2): r"""Reduce the parameter range where two curves can intersect. Does so by using the "fat line" for ``nodes1`` and computing the distance polynomial against ``nodes2``. .. note:: This assumes, but does not check that the curves being considered will only have one intersection in the parameter ranges :math:`s \in \left[0, 1\right]`, :math:`t \in \left[0, 1\right]`. This assumption is based on the fact that B |eacute| zier clipping is meant to be used to find tangent intersections for already subdivided (i.e. sufficiently zoomed in) curve segments. Args: nodes1 (numpy.ndarray): ``2 x N1`` array of nodes in a curve which will define the clipping region. nodes2 (numpy.ndarray): ``2 x N2`` array of nodes in a curve which will be clipped. Returns: Tuple[float, float]: The pair of * The start parameter of the clipped range. * The end parameter of the clipped range. """ # NOTE: There is no corresponding "enable", but the disable only applies # in this lexical scope. # pylint: disable=too-many-locals coeff_a, coeff_b, coeff_c, d_min, d_max = compute_fat_line(nodes1) # NOTE: This assumes, but does not check, that there are two rows. _, num_nodes2 = nodes2.shape polynomial = np.empty((2, num_nodes2), order="F") denominator = float(num_nodes2 - 1) for index in six.moves.xrange(num_nodes2): polynomial[0, index] = index / denominator polynomial[1, index] = ( coeff_a * nodes2[0, index] + coeff_b * nodes2[1, index] + coeff_c ) # Define segments for the top and the bottom of the region # bounded by the fat line. start_bottom = np.asfortranarray([0.0, d_min]) end_bottom = np.asfortranarray([1.0, d_min]) start_top = np.asfortranarray([0.0, d_max]) end_top = np.asfortranarray([1.0, d_max]) s_min = DEFAULT_S_MIN s_max = DEFAULT_S_MAX # NOTE: We avoid computing the convex hull and just compute where # all segments connecting two control points intersect the # fat lines. for start_index in six.moves.xrange(num_nodes2 - 1): for end_index in six.moves.xrange(start_index + 1, num_nodes2): s_min, s_max = _update_parameters( s_min, s_max, start_bottom, end_bottom, polynomial[:, start_index], polynomial[:, end_index], ) s_min, s_max = _update_parameters( s_min, s_max, start_top, end_top, polynomial[:, start_index], polynomial[:, end_index], ) return _check_parameter_range(s_min, s_max)
[ "def", "clip_range", "(", "nodes1", ",", "nodes2", ")", ":", "# NOTE: There is no corresponding \"enable\", but the disable only applies", "# in this lexical scope.", "# pylint: disable=too-many-locals", "coeff_a", ",", "coeff_b", ",", "coeff_c", ",", "d_min", ",", "d_max", "=", "compute_fat_line", "(", "nodes1", ")", "# NOTE: This assumes, but does not check, that there are two rows.", "_", ",", "num_nodes2", "=", "nodes2", ".", "shape", "polynomial", "=", "np", ".", "empty", "(", "(", "2", ",", "num_nodes2", ")", ",", "order", "=", "\"F\"", ")", "denominator", "=", "float", "(", "num_nodes2", "-", "1", ")", "for", "index", "in", "six", ".", "moves", ".", "xrange", "(", "num_nodes2", ")", ":", "polynomial", "[", "0", ",", "index", "]", "=", "index", "/", "denominator", "polynomial", "[", "1", ",", "index", "]", "=", "(", "coeff_a", "*", "nodes2", "[", "0", ",", "index", "]", "+", "coeff_b", "*", "nodes2", "[", "1", ",", "index", "]", "+", "coeff_c", ")", "# Define segments for the top and the bottom of the region", "# bounded by the fat line.", "start_bottom", "=", "np", ".", "asfortranarray", "(", "[", "0.0", ",", "d_min", "]", ")", "end_bottom", "=", "np", ".", "asfortranarray", "(", "[", "1.0", ",", "d_min", "]", ")", "start_top", "=", "np", ".", "asfortranarray", "(", "[", "0.0", ",", "d_max", "]", ")", "end_top", "=", "np", ".", "asfortranarray", "(", "[", "1.0", ",", "d_max", "]", ")", "s_min", "=", "DEFAULT_S_MIN", "s_max", "=", "DEFAULT_S_MAX", "# NOTE: We avoid computing the convex hull and just compute where", "# all segments connecting two control points intersect the", "# fat lines.", "for", "start_index", "in", "six", ".", "moves", ".", "xrange", "(", "num_nodes2", "-", "1", ")", ":", "for", "end_index", "in", "six", ".", "moves", ".", "xrange", "(", "start_index", "+", "1", ",", "num_nodes2", ")", ":", "s_min", ",", "s_max", "=", "_update_parameters", "(", "s_min", ",", "s_max", ",", "start_bottom", ",", "end_bottom", ",", "polynomial", "[", ":", ",", "start_index", "]", ",", "polynomial", "[", ":", ",", "end_index", "]", ",", ")", "s_min", ",", "s_max", "=", "_update_parameters", "(", "s_min", ",", "s_max", ",", "start_top", ",", "end_top", ",", "polynomial", "[", ":", ",", "start_index", "]", ",", "polynomial", "[", ":", ",", "end_index", "]", ",", ")", "return", "_check_parameter_range", "(", "s_min", ",", "s_max", ")" ]
r"""Reduce the parameter range where two curves can intersect. Does so by using the "fat line" for ``nodes1`` and computing the distance polynomial against ``nodes2``. .. note:: This assumes, but does not check that the curves being considered will only have one intersection in the parameter ranges :math:`s \in \left[0, 1\right]`, :math:`t \in \left[0, 1\right]`. This assumption is based on the fact that B |eacute| zier clipping is meant to be used to find tangent intersections for already subdivided (i.e. sufficiently zoomed in) curve segments. Args: nodes1 (numpy.ndarray): ``2 x N1`` array of nodes in a curve which will define the clipping region. nodes2 (numpy.ndarray): ``2 x N2`` array of nodes in a curve which will be clipped. Returns: Tuple[float, float]: The pair of * The start parameter of the clipped range. * The end parameter of the clipped range.
[ "r", "Reduce", "the", "parameter", "range", "where", "two", "curves", "can", "intersect", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_clipping.py#L220-L289
dhermes/bezier
scripts/post_process_journal.py
post_process_travis_macos
def post_process_travis_macos(journal_filename): """Post-process a generated journal file on Travis macOS. Args: journal_filename (str): The name of the journal file. """ travis_build_dir = os.environ.get("TRAVIS_BUILD_DIR", "") with open(journal_filename, "r") as file_obj: content = file_obj.read() processed = content.replace(travis_build_dir, "${TRAVIS_BUILD_DIR}") with open(journal_filename, "w") as file_obj: file_obj.write(processed)
python
def post_process_travis_macos(journal_filename): """Post-process a generated journal file on Travis macOS. Args: journal_filename (str): The name of the journal file. """ travis_build_dir = os.environ.get("TRAVIS_BUILD_DIR", "") with open(journal_filename, "r") as file_obj: content = file_obj.read() processed = content.replace(travis_build_dir, "${TRAVIS_BUILD_DIR}") with open(journal_filename, "w") as file_obj: file_obj.write(processed)
[ "def", "post_process_travis_macos", "(", "journal_filename", ")", ":", "travis_build_dir", "=", "os", ".", "environ", ".", "get", "(", "\"TRAVIS_BUILD_DIR\"", ",", "\"\"", ")", "with", "open", "(", "journal_filename", ",", "\"r\"", ")", "as", "file_obj", ":", "content", "=", "file_obj", ".", "read", "(", ")", "processed", "=", "content", ".", "replace", "(", "travis_build_dir", ",", "\"${TRAVIS_BUILD_DIR}\"", ")", "with", "open", "(", "journal_filename", ",", "\"w\"", ")", "as", "file_obj", ":", "file_obj", ".", "write", "(", "processed", ")" ]
Post-process a generated journal file on Travis macOS. Args: journal_filename (str): The name of the journal file.
[ "Post", "-", "process", "a", "generated", "journal", "file", "on", "Travis", "macOS", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/scripts/post_process_journal.py#L23-L34
dhermes/bezier
scripts/check_doc_templates.py
mod_replace
def mod_replace(match, sphinx_modules): """Convert Sphinx ``:mod:`` to plain reST link. Args: match (_sre.SRE_Match): A match (from ``re``) to be used in substitution. sphinx_modules (list): List to be track the modules that have been encountered. Returns: str: The ``match`` converted to a link. """ sphinx_modules.append(match.group("module")) return "`{}`_".format(match.group("value"))
python
def mod_replace(match, sphinx_modules): """Convert Sphinx ``:mod:`` to plain reST link. Args: match (_sre.SRE_Match): A match (from ``re``) to be used in substitution. sphinx_modules (list): List to be track the modules that have been encountered. Returns: str: The ``match`` converted to a link. """ sphinx_modules.append(match.group("module")) return "`{}`_".format(match.group("value"))
[ "def", "mod_replace", "(", "match", ",", "sphinx_modules", ")", ":", "sphinx_modules", ".", "append", "(", "match", ".", "group", "(", "\"module\"", ")", ")", "return", "\"`{}`_\"", ".", "format", "(", "match", ".", "group", "(", "\"value\"", ")", ")" ]
Convert Sphinx ``:mod:`` to plain reST link. Args: match (_sre.SRE_Match): A match (from ``re``) to be used in substitution. sphinx_modules (list): List to be track the modules that have been encountered. Returns: str: The ``match`` converted to a link.
[ "Convert", "Sphinx", ":", "mod", ":", "to", "plain", "reST", "link", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/scripts/check_doc_templates.py#L213-L226
dhermes/bezier
scripts/check_doc_templates.py
doc_replace
def doc_replace(match, sphinx_docs): """Convert Sphinx ``:doc:`` to plain reST link. Args: match (_sre.SRE_Match): A match (from ``re``) to be used in substitution. sphinx_docs (list): List to be track the documents that have been encountered. Returns: str: The ``match`` converted to a link. """ sphinx_docs.append(match.group("path")) return "`{}`_".format(match.group("value"))
python
def doc_replace(match, sphinx_docs): """Convert Sphinx ``:doc:`` to plain reST link. Args: match (_sre.SRE_Match): A match (from ``re``) to be used in substitution. sphinx_docs (list): List to be track the documents that have been encountered. Returns: str: The ``match`` converted to a link. """ sphinx_docs.append(match.group("path")) return "`{}`_".format(match.group("value"))
[ "def", "doc_replace", "(", "match", ",", "sphinx_docs", ")", ":", "sphinx_docs", ".", "append", "(", "match", ".", "group", "(", "\"path\"", ")", ")", "return", "\"`{}`_\"", ".", "format", "(", "match", ".", "group", "(", "\"value\"", ")", ")" ]
Convert Sphinx ``:doc:`` to plain reST link. Args: match (_sre.SRE_Match): A match (from ``re``) to be used in substitution. sphinx_docs (list): List to be track the documents that have been encountered. Returns: str: The ``match`` converted to a link.
[ "Convert", "Sphinx", ":", "doc", ":", "to", "plain", "reST", "link", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/scripts/check_doc_templates.py#L229-L242
dhermes/bezier
scripts/check_doc_templates.py
get_diff
def get_diff(value1, value2, name1, name2): """Get a diff between two strings. Args: value1 (str): First string to be compared. value2 (str): Second string to be compared. name1 (str): Name of the first string. name2 (str): Name of the second string. Returns: str: The full diff. """ lines1 = [line + "\n" for line in value1.splitlines()] lines2 = [line + "\n" for line in value2.splitlines()] diff_lines = difflib.context_diff( lines1, lines2, fromfile=name1, tofile=name2 ) return "".join(diff_lines)
python
def get_diff(value1, value2, name1, name2): """Get a diff between two strings. Args: value1 (str): First string to be compared. value2 (str): Second string to be compared. name1 (str): Name of the first string. name2 (str): Name of the second string. Returns: str: The full diff. """ lines1 = [line + "\n" for line in value1.splitlines()] lines2 = [line + "\n" for line in value2.splitlines()] diff_lines = difflib.context_diff( lines1, lines2, fromfile=name1, tofile=name2 ) return "".join(diff_lines)
[ "def", "get_diff", "(", "value1", ",", "value2", ",", "name1", ",", "name2", ")", ":", "lines1", "=", "[", "line", "+", "\"\\n\"", "for", "line", "in", "value1", ".", "splitlines", "(", ")", "]", "lines2", "=", "[", "line", "+", "\"\\n\"", "for", "line", "in", "value2", ".", "splitlines", "(", ")", "]", "diff_lines", "=", "difflib", ".", "context_diff", "(", "lines1", ",", "lines2", ",", "fromfile", "=", "name1", ",", "tofile", "=", "name2", ")", "return", "\"\"", ".", "join", "(", "diff_lines", ")" ]
Get a diff between two strings. Args: value1 (str): First string to be compared. value2 (str): Second string to be compared. name1 (str): Name of the first string. name2 (str): Name of the second string. Returns: str: The full diff.
[ "Get", "a", "diff", "between", "two", "strings", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/scripts/check_doc_templates.py#L245-L262
dhermes/bezier
scripts/check_doc_templates.py
populate_readme
def populate_readme(revision, rtd_version, **extra_kwargs): """Populate README template with values. Args: revision (str): The branch, commit, etc. being referred to (e.g. ``master``). rtd_version (str): The version to use for RTD (Read the Docs) links (e.g. ``latest``). extra_kwargs (Dict[str, str]): Over-ride for template arguments. Returns: str: The populated README contents. Raises: ValueError: If the ``sphinx_modules`` encountered are not as expected. ValueError: If the ``sphinx_docs`` encountered are not as expected. """ with open(TEMPLATE_FILE, "r") as file_obj: template = file_obj.read() img_prefix = IMG_PREFIX.format(revision=revision) extra_links = EXTRA_LINKS.format( rtd_version=rtd_version, revision=revision ) docs_img = DOCS_IMG.format(rtd_version=rtd_version) bernstein_basis = BERNSTEIN_BASIS_PLAIN.format(img_prefix=img_prefix) bezier_defn = BEZIER_DEFN_PLAIN.format(img_prefix=img_prefix) sum_to_unity = SUM_TO_UNITY_PLAIN.format(img_prefix=img_prefix) template_kwargs = { "code_block1": PLAIN_CODE_BLOCK, "code_block2": PLAIN_CODE_BLOCK, "code_block3": PLAIN_CODE_BLOCK, "testcleanup": "", "toctree": "", "bernstein_basis": bernstein_basis, "bezier_defn": bezier_defn, "sum_to_unity": sum_to_unity, "img_prefix": img_prefix, "extra_links": extra_links, "docs": "|docs| ", "docs_img": docs_img, "pypi": "\n\n|pypi| ", "pypi_img": PYPI_IMG, "versions": "|versions|\n\n", "versions_img": VERSIONS_IMG, "rtd_version": rtd_version, "revision": revision, "circleci_badge": CIRCLECI_BADGE, "circleci_path": "", "travis_badge": TRAVIS_BADGE, "travis_path": "", "appveyor_badge": APPVEYOR_BADGE, "appveyor_path": "", "coveralls_badge": COVERALLS_BADGE, "coveralls_path": COVERALLS_PATH, "zenodo": "|zenodo|", "zenodo_img": ZENODO_IMG, "joss": " |JOSS|", "joss_img": JOSS_IMG, } template_kwargs.update(**extra_kwargs) readme_contents = template.format(**template_kwargs) # Apply regular expressions to convert Sphinx "roles" to plain reST. readme_contents = INLINE_MATH_EXPR.sub(inline_math, readme_contents) sphinx_modules = [] to_replace = functools.partial(mod_replace, sphinx_modules=sphinx_modules) readme_contents = MOD_EXPR.sub(to_replace, readme_contents) if sphinx_modules != ["bezier.curve", "bezier.surface"]: raise ValueError("Unexpected sphinx_modules", sphinx_modules) sphinx_docs = [] to_replace = functools.partial(doc_replace, sphinx_docs=sphinx_docs) readme_contents = DOC_EXPR.sub(to_replace, readme_contents) if sphinx_docs != ["python/reference/bezier", "development"]: raise ValueError("Unexpected sphinx_docs", sphinx_docs) return readme_contents
python
def populate_readme(revision, rtd_version, **extra_kwargs): """Populate README template with values. Args: revision (str): The branch, commit, etc. being referred to (e.g. ``master``). rtd_version (str): The version to use for RTD (Read the Docs) links (e.g. ``latest``). extra_kwargs (Dict[str, str]): Over-ride for template arguments. Returns: str: The populated README contents. Raises: ValueError: If the ``sphinx_modules`` encountered are not as expected. ValueError: If the ``sphinx_docs`` encountered are not as expected. """ with open(TEMPLATE_FILE, "r") as file_obj: template = file_obj.read() img_prefix = IMG_PREFIX.format(revision=revision) extra_links = EXTRA_LINKS.format( rtd_version=rtd_version, revision=revision ) docs_img = DOCS_IMG.format(rtd_version=rtd_version) bernstein_basis = BERNSTEIN_BASIS_PLAIN.format(img_prefix=img_prefix) bezier_defn = BEZIER_DEFN_PLAIN.format(img_prefix=img_prefix) sum_to_unity = SUM_TO_UNITY_PLAIN.format(img_prefix=img_prefix) template_kwargs = { "code_block1": PLAIN_CODE_BLOCK, "code_block2": PLAIN_CODE_BLOCK, "code_block3": PLAIN_CODE_BLOCK, "testcleanup": "", "toctree": "", "bernstein_basis": bernstein_basis, "bezier_defn": bezier_defn, "sum_to_unity": sum_to_unity, "img_prefix": img_prefix, "extra_links": extra_links, "docs": "|docs| ", "docs_img": docs_img, "pypi": "\n\n|pypi| ", "pypi_img": PYPI_IMG, "versions": "|versions|\n\n", "versions_img": VERSIONS_IMG, "rtd_version": rtd_version, "revision": revision, "circleci_badge": CIRCLECI_BADGE, "circleci_path": "", "travis_badge": TRAVIS_BADGE, "travis_path": "", "appveyor_badge": APPVEYOR_BADGE, "appveyor_path": "", "coveralls_badge": COVERALLS_BADGE, "coveralls_path": COVERALLS_PATH, "zenodo": "|zenodo|", "zenodo_img": ZENODO_IMG, "joss": " |JOSS|", "joss_img": JOSS_IMG, } template_kwargs.update(**extra_kwargs) readme_contents = template.format(**template_kwargs) # Apply regular expressions to convert Sphinx "roles" to plain reST. readme_contents = INLINE_MATH_EXPR.sub(inline_math, readme_contents) sphinx_modules = [] to_replace = functools.partial(mod_replace, sphinx_modules=sphinx_modules) readme_contents = MOD_EXPR.sub(to_replace, readme_contents) if sphinx_modules != ["bezier.curve", "bezier.surface"]: raise ValueError("Unexpected sphinx_modules", sphinx_modules) sphinx_docs = [] to_replace = functools.partial(doc_replace, sphinx_docs=sphinx_docs) readme_contents = DOC_EXPR.sub(to_replace, readme_contents) if sphinx_docs != ["python/reference/bezier", "development"]: raise ValueError("Unexpected sphinx_docs", sphinx_docs) return readme_contents
[ "def", "populate_readme", "(", "revision", ",", "rtd_version", ",", "*", "*", "extra_kwargs", ")", ":", "with", "open", "(", "TEMPLATE_FILE", ",", "\"r\"", ")", "as", "file_obj", ":", "template", "=", "file_obj", ".", "read", "(", ")", "img_prefix", "=", "IMG_PREFIX", ".", "format", "(", "revision", "=", "revision", ")", "extra_links", "=", "EXTRA_LINKS", ".", "format", "(", "rtd_version", "=", "rtd_version", ",", "revision", "=", "revision", ")", "docs_img", "=", "DOCS_IMG", ".", "format", "(", "rtd_version", "=", "rtd_version", ")", "bernstein_basis", "=", "BERNSTEIN_BASIS_PLAIN", ".", "format", "(", "img_prefix", "=", "img_prefix", ")", "bezier_defn", "=", "BEZIER_DEFN_PLAIN", ".", "format", "(", "img_prefix", "=", "img_prefix", ")", "sum_to_unity", "=", "SUM_TO_UNITY_PLAIN", ".", "format", "(", "img_prefix", "=", "img_prefix", ")", "template_kwargs", "=", "{", "\"code_block1\"", ":", "PLAIN_CODE_BLOCK", ",", "\"code_block2\"", ":", "PLAIN_CODE_BLOCK", ",", "\"code_block3\"", ":", "PLAIN_CODE_BLOCK", ",", "\"testcleanup\"", ":", "\"\"", ",", "\"toctree\"", ":", "\"\"", ",", "\"bernstein_basis\"", ":", "bernstein_basis", ",", "\"bezier_defn\"", ":", "bezier_defn", ",", "\"sum_to_unity\"", ":", "sum_to_unity", ",", "\"img_prefix\"", ":", "img_prefix", ",", "\"extra_links\"", ":", "extra_links", ",", "\"docs\"", ":", "\"|docs| \"", ",", "\"docs_img\"", ":", "docs_img", ",", "\"pypi\"", ":", "\"\\n\\n|pypi| \"", ",", "\"pypi_img\"", ":", "PYPI_IMG", ",", "\"versions\"", ":", "\"|versions|\\n\\n\"", ",", "\"versions_img\"", ":", "VERSIONS_IMG", ",", "\"rtd_version\"", ":", "rtd_version", ",", "\"revision\"", ":", "revision", ",", "\"circleci_badge\"", ":", "CIRCLECI_BADGE", ",", "\"circleci_path\"", ":", "\"\"", ",", "\"travis_badge\"", ":", "TRAVIS_BADGE", ",", "\"travis_path\"", ":", "\"\"", ",", "\"appveyor_badge\"", ":", "APPVEYOR_BADGE", ",", "\"appveyor_path\"", ":", "\"\"", ",", "\"coveralls_badge\"", ":", "COVERALLS_BADGE", ",", "\"coveralls_path\"", ":", "COVERALLS_PATH", ",", "\"zenodo\"", ":", "\"|zenodo|\"", ",", "\"zenodo_img\"", ":", "ZENODO_IMG", ",", "\"joss\"", ":", "\" |JOSS|\"", ",", "\"joss_img\"", ":", "JOSS_IMG", ",", "}", "template_kwargs", ".", "update", "(", "*", "*", "extra_kwargs", ")", "readme_contents", "=", "template", ".", "format", "(", "*", "*", "template_kwargs", ")", "# Apply regular expressions to convert Sphinx \"roles\" to plain reST.", "readme_contents", "=", "INLINE_MATH_EXPR", ".", "sub", "(", "inline_math", ",", "readme_contents", ")", "sphinx_modules", "=", "[", "]", "to_replace", "=", "functools", ".", "partial", "(", "mod_replace", ",", "sphinx_modules", "=", "sphinx_modules", ")", "readme_contents", "=", "MOD_EXPR", ".", "sub", "(", "to_replace", ",", "readme_contents", ")", "if", "sphinx_modules", "!=", "[", "\"bezier.curve\"", ",", "\"bezier.surface\"", "]", ":", "raise", "ValueError", "(", "\"Unexpected sphinx_modules\"", ",", "sphinx_modules", ")", "sphinx_docs", "=", "[", "]", "to_replace", "=", "functools", ".", "partial", "(", "doc_replace", ",", "sphinx_docs", "=", "sphinx_docs", ")", "readme_contents", "=", "DOC_EXPR", ".", "sub", "(", "to_replace", ",", "readme_contents", ")", "if", "sphinx_docs", "!=", "[", "\"python/reference/bezier\"", ",", "\"development\"", "]", ":", "raise", "ValueError", "(", "\"Unexpected sphinx_docs\"", ",", "sphinx_docs", ")", "return", "readme_contents" ]
Populate README template with values. Args: revision (str): The branch, commit, etc. being referred to (e.g. ``master``). rtd_version (str): The version to use for RTD (Read the Docs) links (e.g. ``latest``). extra_kwargs (Dict[str, str]): Over-ride for template arguments. Returns: str: The populated README contents. Raises: ValueError: If the ``sphinx_modules`` encountered are not as expected. ValueError: If the ``sphinx_docs`` encountered are not as expected.
[ "Populate", "README", "template", "with", "values", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/scripts/check_doc_templates.py#L265-L340
dhermes/bezier
scripts/check_doc_templates.py
readme_verify
def readme_verify(): """Populate the template and compare to ``README``. Raises: ValueError: If the current README doesn't agree with the expected value computed from the template. """ expected = populate_readme(REVISION, RTD_VERSION) # Actually get the stored contents. with open(README_FILE, "r") as file_obj: contents = file_obj.read() if contents != expected: err_msg = "\n" + get_diff( contents, expected, "README.rst.actual", "README.rst.expected" ) raise ValueError(err_msg) else: print("README contents are as expected.")
python
def readme_verify(): """Populate the template and compare to ``README``. Raises: ValueError: If the current README doesn't agree with the expected value computed from the template. """ expected = populate_readme(REVISION, RTD_VERSION) # Actually get the stored contents. with open(README_FILE, "r") as file_obj: contents = file_obj.read() if contents != expected: err_msg = "\n" + get_diff( contents, expected, "README.rst.actual", "README.rst.expected" ) raise ValueError(err_msg) else: print("README contents are as expected.")
[ "def", "readme_verify", "(", ")", ":", "expected", "=", "populate_readme", "(", "REVISION", ",", "RTD_VERSION", ")", "# Actually get the stored contents.", "with", "open", "(", "README_FILE", ",", "\"r\"", ")", "as", "file_obj", ":", "contents", "=", "file_obj", ".", "read", "(", ")", "if", "contents", "!=", "expected", ":", "err_msg", "=", "\"\\n\"", "+", "get_diff", "(", "contents", ",", "expected", ",", "\"README.rst.actual\"", ",", "\"README.rst.expected\"", ")", "raise", "ValueError", "(", "err_msg", ")", "else", ":", "print", "(", "\"README contents are as expected.\"", ")" ]
Populate the template and compare to ``README``. Raises: ValueError: If the current README doesn't agree with the expected value computed from the template.
[ "Populate", "the", "template", "and", "compare", "to", "README", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/scripts/check_doc_templates.py#L343-L361
dhermes/bezier
scripts/check_doc_templates.py
release_readme_verify
def release_readme_verify(): """Specialize the template to a PyPI release template. Once populated, compare to ``README.rst.release.template``. Raises: ValueError: If the current template doesn't agree with the expected value specialized from the template. """ version = "{version}" expected = populate_readme( version, version, pypi="", pypi_img="", versions="\n\n", versions_img="", circleci_badge=CIRCLECI_BADGE_RELEASE, circleci_path="/{circleci_build}", travis_badge=TRAVIS_BADGE_RELEASE, travis_path="/builds/{travis_build}", appveyor_badge=APPVEYOR_BADGE_RELEASE, appveyor_path="/build/{appveyor_build}", coveralls_badge=COVERALLS_BADGE_RELEASE, coveralls_path="builds/{coveralls_build}", ) with open(RELEASE_README_FILE, "r") as file_obj: contents = file_obj.read() if contents != expected: err_msg = "\n" + get_diff( contents, expected, "README.rst.release.actual", "README.rst.release.expected", ) raise ValueError(err_msg) else: print("README.rst.release.template contents are as expected.")
python
def release_readme_verify(): """Specialize the template to a PyPI release template. Once populated, compare to ``README.rst.release.template``. Raises: ValueError: If the current template doesn't agree with the expected value specialized from the template. """ version = "{version}" expected = populate_readme( version, version, pypi="", pypi_img="", versions="\n\n", versions_img="", circleci_badge=CIRCLECI_BADGE_RELEASE, circleci_path="/{circleci_build}", travis_badge=TRAVIS_BADGE_RELEASE, travis_path="/builds/{travis_build}", appveyor_badge=APPVEYOR_BADGE_RELEASE, appveyor_path="/build/{appveyor_build}", coveralls_badge=COVERALLS_BADGE_RELEASE, coveralls_path="builds/{coveralls_build}", ) with open(RELEASE_README_FILE, "r") as file_obj: contents = file_obj.read() if contents != expected: err_msg = "\n" + get_diff( contents, expected, "README.rst.release.actual", "README.rst.release.expected", ) raise ValueError(err_msg) else: print("README.rst.release.template contents are as expected.")
[ "def", "release_readme_verify", "(", ")", ":", "version", "=", "\"{version}\"", "expected", "=", "populate_readme", "(", "version", ",", "version", ",", "pypi", "=", "\"\"", ",", "pypi_img", "=", "\"\"", ",", "versions", "=", "\"\\n\\n\"", ",", "versions_img", "=", "\"\"", ",", "circleci_badge", "=", "CIRCLECI_BADGE_RELEASE", ",", "circleci_path", "=", "\"/{circleci_build}\"", ",", "travis_badge", "=", "TRAVIS_BADGE_RELEASE", ",", "travis_path", "=", "\"/builds/{travis_build}\"", ",", "appveyor_badge", "=", "APPVEYOR_BADGE_RELEASE", ",", "appveyor_path", "=", "\"/build/{appveyor_build}\"", ",", "coveralls_badge", "=", "COVERALLS_BADGE_RELEASE", ",", "coveralls_path", "=", "\"builds/{coveralls_build}\"", ",", ")", "with", "open", "(", "RELEASE_README_FILE", ",", "\"r\"", ")", "as", "file_obj", ":", "contents", "=", "file_obj", ".", "read", "(", ")", "if", "contents", "!=", "expected", ":", "err_msg", "=", "\"\\n\"", "+", "get_diff", "(", "contents", ",", "expected", ",", "\"README.rst.release.actual\"", ",", "\"README.rst.release.expected\"", ",", ")", "raise", "ValueError", "(", "err_msg", ")", "else", ":", "print", "(", "\"README.rst.release.template contents are as expected.\"", ")" ]
Specialize the template to a PyPI release template. Once populated, compare to ``README.rst.release.template``. Raises: ValueError: If the current template doesn't agree with the expected value specialized from the template.
[ "Specialize", "the", "template", "to", "a", "PyPI", "release", "template", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/scripts/check_doc_templates.py#L364-L402
dhermes/bezier
scripts/check_doc_templates.py
_index_verify
def _index_verify(index_file, **extra_kwargs): """Populate the template and compare to documentation index file. Used for both ``docs/index.rst`` and ``docs/index.rst.release.template``. Args: index_file (str): Filename to compare against. extra_kwargs (Dict[str, str]): Over-ride for template arguments. One **special** keyword is ``side_effect``, which can be used to update the template output after the fact. Raises: ValueError: If the current ``index.rst`` doesn't agree with the expected value computed from the template. """ side_effect = extra_kwargs.pop("side_effect", None) with open(TEMPLATE_FILE, "r") as file_obj: template = file_obj.read() template_kwargs = { "code_block1": SPHINX_CODE_BLOCK1, "code_block2": SPHINX_CODE_BLOCK2, "code_block3": SPHINX_CODE_BLOCK3, "testcleanup": TEST_CLEANUP, "toctree": TOCTREE, "bernstein_basis": BERNSTEIN_BASIS_SPHINX, "bezier_defn": BEZIER_DEFN_SPHINX, "sum_to_unity": SUM_TO_UNITY_SPHINX, "img_prefix": "", "extra_links": "", "docs": "", "docs_img": "", "pypi": "\n\n|pypi| ", "pypi_img": PYPI_IMG, "versions": "|versions|\n\n", "versions_img": VERSIONS_IMG, "rtd_version": RTD_VERSION, "revision": REVISION, "circleci_badge": CIRCLECI_BADGE, "circleci_path": "", "travis_badge": TRAVIS_BADGE, "travis_path": "", "appveyor_badge": APPVEYOR_BADGE, "appveyor_path": "", "coveralls_badge": COVERALLS_BADGE, "coveralls_path": COVERALLS_PATH, "zenodo": "|zenodo|", "zenodo_img": ZENODO_IMG, "joss": " |JOSS|", "joss_img": JOSS_IMG, } template_kwargs.update(**extra_kwargs) expected = template.format(**template_kwargs) if side_effect is not None: expected = side_effect(expected) with open(index_file, "r") as file_obj: contents = file_obj.read() if contents != expected: err_msg = "\n" + get_diff( contents, expected, index_file + ".actual", index_file + ".expected", ) raise ValueError(err_msg) else: rel_name = os.path.relpath(index_file, _ROOT_DIR) msg = "{} contents are as expected.".format(rel_name) print(msg)
python
def _index_verify(index_file, **extra_kwargs): """Populate the template and compare to documentation index file. Used for both ``docs/index.rst`` and ``docs/index.rst.release.template``. Args: index_file (str): Filename to compare against. extra_kwargs (Dict[str, str]): Over-ride for template arguments. One **special** keyword is ``side_effect``, which can be used to update the template output after the fact. Raises: ValueError: If the current ``index.rst`` doesn't agree with the expected value computed from the template. """ side_effect = extra_kwargs.pop("side_effect", None) with open(TEMPLATE_FILE, "r") as file_obj: template = file_obj.read() template_kwargs = { "code_block1": SPHINX_CODE_BLOCK1, "code_block2": SPHINX_CODE_BLOCK2, "code_block3": SPHINX_CODE_BLOCK3, "testcleanup": TEST_CLEANUP, "toctree": TOCTREE, "bernstein_basis": BERNSTEIN_BASIS_SPHINX, "bezier_defn": BEZIER_DEFN_SPHINX, "sum_to_unity": SUM_TO_UNITY_SPHINX, "img_prefix": "", "extra_links": "", "docs": "", "docs_img": "", "pypi": "\n\n|pypi| ", "pypi_img": PYPI_IMG, "versions": "|versions|\n\n", "versions_img": VERSIONS_IMG, "rtd_version": RTD_VERSION, "revision": REVISION, "circleci_badge": CIRCLECI_BADGE, "circleci_path": "", "travis_badge": TRAVIS_BADGE, "travis_path": "", "appveyor_badge": APPVEYOR_BADGE, "appveyor_path": "", "coveralls_badge": COVERALLS_BADGE, "coveralls_path": COVERALLS_PATH, "zenodo": "|zenodo|", "zenodo_img": ZENODO_IMG, "joss": " |JOSS|", "joss_img": JOSS_IMG, } template_kwargs.update(**extra_kwargs) expected = template.format(**template_kwargs) if side_effect is not None: expected = side_effect(expected) with open(index_file, "r") as file_obj: contents = file_obj.read() if contents != expected: err_msg = "\n" + get_diff( contents, expected, index_file + ".actual", index_file + ".expected", ) raise ValueError(err_msg) else: rel_name = os.path.relpath(index_file, _ROOT_DIR) msg = "{} contents are as expected.".format(rel_name) print(msg)
[ "def", "_index_verify", "(", "index_file", ",", "*", "*", "extra_kwargs", ")", ":", "side_effect", "=", "extra_kwargs", ".", "pop", "(", "\"side_effect\"", ",", "None", ")", "with", "open", "(", "TEMPLATE_FILE", ",", "\"r\"", ")", "as", "file_obj", ":", "template", "=", "file_obj", ".", "read", "(", ")", "template_kwargs", "=", "{", "\"code_block1\"", ":", "SPHINX_CODE_BLOCK1", ",", "\"code_block2\"", ":", "SPHINX_CODE_BLOCK2", ",", "\"code_block3\"", ":", "SPHINX_CODE_BLOCK3", ",", "\"testcleanup\"", ":", "TEST_CLEANUP", ",", "\"toctree\"", ":", "TOCTREE", ",", "\"bernstein_basis\"", ":", "BERNSTEIN_BASIS_SPHINX", ",", "\"bezier_defn\"", ":", "BEZIER_DEFN_SPHINX", ",", "\"sum_to_unity\"", ":", "SUM_TO_UNITY_SPHINX", ",", "\"img_prefix\"", ":", "\"\"", ",", "\"extra_links\"", ":", "\"\"", ",", "\"docs\"", ":", "\"\"", ",", "\"docs_img\"", ":", "\"\"", ",", "\"pypi\"", ":", "\"\\n\\n|pypi| \"", ",", "\"pypi_img\"", ":", "PYPI_IMG", ",", "\"versions\"", ":", "\"|versions|\\n\\n\"", ",", "\"versions_img\"", ":", "VERSIONS_IMG", ",", "\"rtd_version\"", ":", "RTD_VERSION", ",", "\"revision\"", ":", "REVISION", ",", "\"circleci_badge\"", ":", "CIRCLECI_BADGE", ",", "\"circleci_path\"", ":", "\"\"", ",", "\"travis_badge\"", ":", "TRAVIS_BADGE", ",", "\"travis_path\"", ":", "\"\"", ",", "\"appveyor_badge\"", ":", "APPVEYOR_BADGE", ",", "\"appveyor_path\"", ":", "\"\"", ",", "\"coveralls_badge\"", ":", "COVERALLS_BADGE", ",", "\"coveralls_path\"", ":", "COVERALLS_PATH", ",", "\"zenodo\"", ":", "\"|zenodo|\"", ",", "\"zenodo_img\"", ":", "ZENODO_IMG", ",", "\"joss\"", ":", "\" |JOSS|\"", ",", "\"joss_img\"", ":", "JOSS_IMG", ",", "}", "template_kwargs", ".", "update", "(", "*", "*", "extra_kwargs", ")", "expected", "=", "template", ".", "format", "(", "*", "*", "template_kwargs", ")", "if", "side_effect", "is", "not", "None", ":", "expected", "=", "side_effect", "(", "expected", ")", "with", "open", "(", "index_file", ",", "\"r\"", ")", "as", "file_obj", ":", "contents", "=", "file_obj", ".", "read", "(", ")", "if", "contents", "!=", "expected", ":", "err_msg", "=", "\"\\n\"", "+", "get_diff", "(", "contents", ",", "expected", ",", "index_file", "+", "\".actual\"", ",", "index_file", "+", "\".expected\"", ",", ")", "raise", "ValueError", "(", "err_msg", ")", "else", ":", "rel_name", "=", "os", ".", "path", ".", "relpath", "(", "index_file", ",", "_ROOT_DIR", ")", "msg", "=", "\"{} contents are as expected.\"", ".", "format", "(", "rel_name", ")", "print", "(", "msg", ")" ]
Populate the template and compare to documentation index file. Used for both ``docs/index.rst`` and ``docs/index.rst.release.template``. Args: index_file (str): Filename to compare against. extra_kwargs (Dict[str, str]): Over-ride for template arguments. One **special** keyword is ``side_effect``, which can be used to update the template output after the fact. Raises: ValueError: If the current ``index.rst`` doesn't agree with the expected value computed from the template.
[ "Populate", "the", "template", "and", "compare", "to", "documentation", "index", "file", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/scripts/check_doc_templates.py#L405-L473
dhermes/bezier
scripts/check_doc_templates.py
release_docs_side_effect
def release_docs_side_effect(content): """Updates the template so that curly braces are escaped correctly. Args: content (str): The template for ``docs/index.rst.release.template``. Returns: str: The updated template with properly escaped curly braces. """ # First replace **all** curly braces. result = content.replace("{", "{{").replace("}", "}}") # Then reset the actual template arguments. result = result.replace("{{version}}", "{version}") result = result.replace("{{circleci_build}}", "{circleci_build}") result = result.replace("{{travis_build}}", "{travis_build}") result = result.replace("{{appveyor_build}}", "{appveyor_build}") result = result.replace("{{coveralls_build}}", "{coveralls_build}") return result
python
def release_docs_side_effect(content): """Updates the template so that curly braces are escaped correctly. Args: content (str): The template for ``docs/index.rst.release.template``. Returns: str: The updated template with properly escaped curly braces. """ # First replace **all** curly braces. result = content.replace("{", "{{").replace("}", "}}") # Then reset the actual template arguments. result = result.replace("{{version}}", "{version}") result = result.replace("{{circleci_build}}", "{circleci_build}") result = result.replace("{{travis_build}}", "{travis_build}") result = result.replace("{{appveyor_build}}", "{appveyor_build}") result = result.replace("{{coveralls_build}}", "{coveralls_build}") return result
[ "def", "release_docs_side_effect", "(", "content", ")", ":", "# First replace **all** curly braces.", "result", "=", "content", ".", "replace", "(", "\"{\"", ",", "\"{{\"", ")", ".", "replace", "(", "\"}\"", ",", "\"}}\"", ")", "# Then reset the actual template arguments.", "result", "=", "result", ".", "replace", "(", "\"{{version}}\"", ",", "\"{version}\"", ")", "result", "=", "result", ".", "replace", "(", "\"{{circleci_build}}\"", ",", "\"{circleci_build}\"", ")", "result", "=", "result", ".", "replace", "(", "\"{{travis_build}}\"", ",", "\"{travis_build}\"", ")", "result", "=", "result", ".", "replace", "(", "\"{{appveyor_build}}\"", ",", "\"{appveyor_build}\"", ")", "result", "=", "result", ".", "replace", "(", "\"{{coveralls_build}}\"", ",", "\"{coveralls_build}\"", ")", "return", "result" ]
Updates the template so that curly braces are escaped correctly. Args: content (str): The template for ``docs/index.rst.release.template``. Returns: str: The updated template with properly escaped curly braces.
[ "Updates", "the", "template", "so", "that", "curly", "braces", "are", "escaped", "correctly", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/scripts/check_doc_templates.py#L486-L503
dhermes/bezier
scripts/check_doc_templates.py
release_docs_index_verify
def release_docs_index_verify(): """Populate template and compare to ``docs/index.rst.release.template``. Raises: ValueError: If the current ``index.rst.release.template`` doesn't agree with the expected value computed from the template. """ version = "{version}" _index_verify( RELEASE_INDEX_FILE, side_effect=release_docs_side_effect, pypi="", pypi_img="", versions="\n\n", versions_img="", rtd_version=version, revision=version, circleci_badge=CIRCLECI_BADGE_RELEASE, circleci_path="/{circleci_build}", travis_badge=TRAVIS_BADGE_RELEASE, travis_path="/builds/{travis_build}", appveyor_badge=APPVEYOR_BADGE_RELEASE, appveyor_path="/build/{appveyor_build}", coveralls_badge=COVERALLS_BADGE_RELEASE, coveralls_path="builds/{coveralls_build}", )
python
def release_docs_index_verify(): """Populate template and compare to ``docs/index.rst.release.template``. Raises: ValueError: If the current ``index.rst.release.template`` doesn't agree with the expected value computed from the template. """ version = "{version}" _index_verify( RELEASE_INDEX_FILE, side_effect=release_docs_side_effect, pypi="", pypi_img="", versions="\n\n", versions_img="", rtd_version=version, revision=version, circleci_badge=CIRCLECI_BADGE_RELEASE, circleci_path="/{circleci_build}", travis_badge=TRAVIS_BADGE_RELEASE, travis_path="/builds/{travis_build}", appveyor_badge=APPVEYOR_BADGE_RELEASE, appveyor_path="/build/{appveyor_build}", coveralls_badge=COVERALLS_BADGE_RELEASE, coveralls_path="builds/{coveralls_build}", )
[ "def", "release_docs_index_verify", "(", ")", ":", "version", "=", "\"{version}\"", "_index_verify", "(", "RELEASE_INDEX_FILE", ",", "side_effect", "=", "release_docs_side_effect", ",", "pypi", "=", "\"\"", ",", "pypi_img", "=", "\"\"", ",", "versions", "=", "\"\\n\\n\"", ",", "versions_img", "=", "\"\"", ",", "rtd_version", "=", "version", ",", "revision", "=", "version", ",", "circleci_badge", "=", "CIRCLECI_BADGE_RELEASE", ",", "circleci_path", "=", "\"/{circleci_build}\"", ",", "travis_badge", "=", "TRAVIS_BADGE_RELEASE", ",", "travis_path", "=", "\"/builds/{travis_build}\"", ",", "appveyor_badge", "=", "APPVEYOR_BADGE_RELEASE", ",", "appveyor_path", "=", "\"/build/{appveyor_build}\"", ",", "coveralls_badge", "=", "COVERALLS_BADGE_RELEASE", ",", "coveralls_path", "=", "\"builds/{coveralls_build}\"", ",", ")" ]
Populate template and compare to ``docs/index.rst.release.template``. Raises: ValueError: If the current ``index.rst.release.template`` doesn't agree with the expected value computed from the template.
[ "Populate", "template", "and", "compare", "to", "docs", "/", "index", ".", "rst", ".", "release", ".", "template", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/scripts/check_doc_templates.py#L506-L531
dhermes/bezier
scripts/check_doc_templates.py
development_verify
def development_verify(): """Populate template and compare to ``DEVELOPMENT.rst`` Raises: ValueError: If the current ``DEVELOPMENT.rst`` doesn't agree with the expected value computed from the template. """ with open(DEVELOPMENT_TEMPLATE, "r") as file_obj: template = file_obj.read() expected = template.format(revision=REVISION, rtd_version=RTD_VERSION) with open(DEVELOPMENT_FILE, "r") as file_obj: contents = file_obj.read() if contents != expected: err_msg = "\n" + get_diff( contents, expected, "DEVELOPMENT.rst.actual", "DEVELOPMENT.rst.expected", ) raise ValueError(err_msg) else: print("DEVELOPMENT.rst contents are as expected.")
python
def development_verify(): """Populate template and compare to ``DEVELOPMENT.rst`` Raises: ValueError: If the current ``DEVELOPMENT.rst`` doesn't agree with the expected value computed from the template. """ with open(DEVELOPMENT_TEMPLATE, "r") as file_obj: template = file_obj.read() expected = template.format(revision=REVISION, rtd_version=RTD_VERSION) with open(DEVELOPMENT_FILE, "r") as file_obj: contents = file_obj.read() if contents != expected: err_msg = "\n" + get_diff( contents, expected, "DEVELOPMENT.rst.actual", "DEVELOPMENT.rst.expected", ) raise ValueError(err_msg) else: print("DEVELOPMENT.rst contents are as expected.")
[ "def", "development_verify", "(", ")", ":", "with", "open", "(", "DEVELOPMENT_TEMPLATE", ",", "\"r\"", ")", "as", "file_obj", ":", "template", "=", "file_obj", ".", "read", "(", ")", "expected", "=", "template", ".", "format", "(", "revision", "=", "REVISION", ",", "rtd_version", "=", "RTD_VERSION", ")", "with", "open", "(", "DEVELOPMENT_FILE", ",", "\"r\"", ")", "as", "file_obj", ":", "contents", "=", "file_obj", ".", "read", "(", ")", "if", "contents", "!=", "expected", ":", "err_msg", "=", "\"\\n\"", "+", "get_diff", "(", "contents", ",", "expected", ",", "\"DEVELOPMENT.rst.actual\"", ",", "\"DEVELOPMENT.rst.expected\"", ",", ")", "raise", "ValueError", "(", "err_msg", ")", "else", ":", "print", "(", "\"DEVELOPMENT.rst contents are as expected.\"", ")" ]
Populate template and compare to ``DEVELOPMENT.rst`` Raises: ValueError: If the current ``DEVELOPMENT.rst`` doesn't agree with the expected value computed from the template.
[ "Populate", "template", "and", "compare", "to", "DEVELOPMENT", ".", "rst" ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/scripts/check_doc_templates.py#L534-L556
dhermes/bezier
scripts/check_doc_templates.py
native_libraries_verify
def native_libraries_verify(): """Populate the template and compare to ``binary-extension.rst``. Raises: ValueError: If the current ``docs/python/binary-extension.rst`` doesn't agree with the expected value computed from the template. """ with open(BINARY_EXT_TEMPLATE, "r") as file_obj: template = file_obj.read() expected = template.format(revision=REVISION) with open(BINARY_EXT_FILE, "r") as file_obj: contents = file_obj.read() if contents != expected: err_msg = "\n" + get_diff( contents, expected, "docs/python/binary-extension.rst.actual", "docs/python/binary-extension.rst.expected", ) raise ValueError(err_msg) else: print("docs/python/binary-extension.rst contents are as expected.")
python
def native_libraries_verify(): """Populate the template and compare to ``binary-extension.rst``. Raises: ValueError: If the current ``docs/python/binary-extension.rst`` doesn't agree with the expected value computed from the template. """ with open(BINARY_EXT_TEMPLATE, "r") as file_obj: template = file_obj.read() expected = template.format(revision=REVISION) with open(BINARY_EXT_FILE, "r") as file_obj: contents = file_obj.read() if contents != expected: err_msg = "\n" + get_diff( contents, expected, "docs/python/binary-extension.rst.actual", "docs/python/binary-extension.rst.expected", ) raise ValueError(err_msg) else: print("docs/python/binary-extension.rst contents are as expected.")
[ "def", "native_libraries_verify", "(", ")", ":", "with", "open", "(", "BINARY_EXT_TEMPLATE", ",", "\"r\"", ")", "as", "file_obj", ":", "template", "=", "file_obj", ".", "read", "(", ")", "expected", "=", "template", ".", "format", "(", "revision", "=", "REVISION", ")", "with", "open", "(", "BINARY_EXT_FILE", ",", "\"r\"", ")", "as", "file_obj", ":", "contents", "=", "file_obj", ".", "read", "(", ")", "if", "contents", "!=", "expected", ":", "err_msg", "=", "\"\\n\"", "+", "get_diff", "(", "contents", ",", "expected", ",", "\"docs/python/binary-extension.rst.actual\"", ",", "\"docs/python/binary-extension.rst.expected\"", ",", ")", "raise", "ValueError", "(", "err_msg", ")", "else", ":", "print", "(", "\"docs/python/binary-extension.rst contents are as expected.\"", ")" ]
Populate the template and compare to ``binary-extension.rst``. Raises: ValueError: If the current ``docs/python/binary-extension.rst`` doesn't agree with the expected value computed from the template.
[ "Populate", "the", "template", "and", "compare", "to", "binary", "-", "extension", ".", "rst", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/scripts/check_doc_templates.py#L559-L581
dhermes/bezier
src/bezier/_algebraic_intersection.py
_evaluate3
def _evaluate3(nodes, x_val, y_val): """Helper for :func:`evaluate` when ``nodes`` is degree 3. Args: nodes (numpy.ndarray): ``2 x 4`` array of nodes in a curve. x_val (float): ``x``-coordinate for evaluation. y_val (float): ``y``-coordinate for evaluation. Returns: float: The computed value of :math:`f(x, y)`. """ # NOTE: This may be (a) slower and (b) less precise than # hard-coding the determinant. sylvester_mat = np.zeros((6, 6), order="F") delta = nodes - np.asfortranarray([[x_val], [y_val]]) delta[:, 1:3] *= 3.0 # Swap rows/columns so that x-y are right next to each other. # This will only change the determinant up to a sign. sylvester_mat[:2, :4] = delta sylvester_mat[2:4, 1:5] = delta sylvester_mat[4:, 2:] = delta return np.linalg.det(sylvester_mat)
python
def _evaluate3(nodes, x_val, y_val): """Helper for :func:`evaluate` when ``nodes`` is degree 3. Args: nodes (numpy.ndarray): ``2 x 4`` array of nodes in a curve. x_val (float): ``x``-coordinate for evaluation. y_val (float): ``y``-coordinate for evaluation. Returns: float: The computed value of :math:`f(x, y)`. """ # NOTE: This may be (a) slower and (b) less precise than # hard-coding the determinant. sylvester_mat = np.zeros((6, 6), order="F") delta = nodes - np.asfortranarray([[x_val], [y_val]]) delta[:, 1:3] *= 3.0 # Swap rows/columns so that x-y are right next to each other. # This will only change the determinant up to a sign. sylvester_mat[:2, :4] = delta sylvester_mat[2:4, 1:5] = delta sylvester_mat[4:, 2:] = delta return np.linalg.det(sylvester_mat)
[ "def", "_evaluate3", "(", "nodes", ",", "x_val", ",", "y_val", ")", ":", "# NOTE: This may be (a) slower and (b) less precise than", "# hard-coding the determinant.", "sylvester_mat", "=", "np", ".", "zeros", "(", "(", "6", ",", "6", ")", ",", "order", "=", "\"F\"", ")", "delta", "=", "nodes", "-", "np", ".", "asfortranarray", "(", "[", "[", "x_val", "]", ",", "[", "y_val", "]", "]", ")", "delta", "[", ":", ",", "1", ":", "3", "]", "*=", "3.0", "# Swap rows/columns so that x-y are right next to each other.", "# This will only change the determinant up to a sign.", "sylvester_mat", "[", ":", "2", ",", ":", "4", "]", "=", "delta", "sylvester_mat", "[", "2", ":", "4", ",", "1", ":", "5", "]", "=", "delta", "sylvester_mat", "[", "4", ":", ",", "2", ":", "]", "=", "delta", "return", "np", ".", "linalg", ".", "det", "(", "sylvester_mat", ")" ]
Helper for :func:`evaluate` when ``nodes`` is degree 3. Args: nodes (numpy.ndarray): ``2 x 4`` array of nodes in a curve. x_val (float): ``x``-coordinate for evaluation. y_val (float): ``y``-coordinate for evaluation. Returns: float: The computed value of :math:`f(x, y)`.
[ "Helper", "for", ":", "func", ":", "evaluate", "when", "nodes", "is", "degree", "3", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_algebraic_intersection.py#L120-L141
dhermes/bezier
src/bezier/_algebraic_intersection.py
evaluate
def evaluate(nodes, x_val, y_val): r"""Evaluate the implicitized bivariate polynomial containing the curve. Assumes `algebraic curve`_ containing :math:`B(s, t)` is given by :math:`f(x, y) = 0`. This function evaluates :math:`f(x, y)`. .. note:: This assumes, but doesn't check, that ``nodes`` has 2 rows. .. note:: This assumes, but doesn't check, that ``nodes`` is not degree-elevated. If it were degree-elevated, then the Sylvester matrix will always have zero determinant. Args: nodes (numpy.ndarray): ``2 x N`` array of nodes in a curve. x_val (float): ``x``-coordinate for evaluation. y_val (float): ``y``-coordinate for evaluation. Returns: float: The computed value of :math:`f(x, y)`. Raises: ValueError: If the curve is a point. .UnsupportedDegree: If the degree is not 1, 2 or 3. """ _, num_nodes = nodes.shape if num_nodes == 1: raise ValueError("A point cannot be implicitized") elif num_nodes == 2: # x(s) - x = (x0 - x) (1 - s) + (x1 - x) s # y(s) - y = (y0 - y) (1 - s) + (y1 - y) s # Modified Sylvester: [x0 - x, x1 - x] # [y0 - y, y1 - y] return (nodes[0, 0] - x_val) * (nodes[1, 1] - y_val) - ( nodes[0, 1] - x_val ) * (nodes[1, 0] - y_val) elif num_nodes == 3: # x(s) - x = (x0 - x) (1 - s)^2 + 2 (x1 - x) s(1 - s) + (x2 - x) s^2 # y(s) - y = (y0 - y) (1 - s)^2 + 2 (y1 - y) s(1 - s) + (y2 - y) s^2 # Modified Sylvester: [x0 - x, 2(x1 - x), x2 - x, 0] = A|B|C|0 # [ 0, x0 - x, 2(x1 - x), x2 - x] 0|A|B|C # [y0 - y, 2(y1 - y), y2 - y, 0] D|E|F|0 # [ 0, y0 - y, 2(y1 - y), y2 - y] 0|D|E|F val_a, val_b, val_c = nodes[0, :] - x_val val_b *= 2 val_d, val_e, val_f = nodes[1, :] - y_val val_e *= 2 # [A, B, C] [E, F, 0] # det [E, F, 0] = - det [A, B, C] = -E (BF - CE) + F(AF - CD) # [D, E, F] [D, E, F] sub1 = val_b * val_f - val_c * val_e sub2 = val_a * val_f - val_c * val_d sub_det_a = -val_e * sub1 + val_f * sub2 # [B, C, 0] # det [A, B, C] = B (BF - CE) - C (AF - CD) # [D, E, F] sub_det_d = val_b * sub1 - val_c * sub2 return val_a * sub_det_a + val_d * sub_det_d elif num_nodes == 4: return _evaluate3(nodes, x_val, y_val) else: raise _helpers.UnsupportedDegree(num_nodes - 1, supported=(1, 2, 3))
python
def evaluate(nodes, x_val, y_val): r"""Evaluate the implicitized bivariate polynomial containing the curve. Assumes `algebraic curve`_ containing :math:`B(s, t)` is given by :math:`f(x, y) = 0`. This function evaluates :math:`f(x, y)`. .. note:: This assumes, but doesn't check, that ``nodes`` has 2 rows. .. note:: This assumes, but doesn't check, that ``nodes`` is not degree-elevated. If it were degree-elevated, then the Sylvester matrix will always have zero determinant. Args: nodes (numpy.ndarray): ``2 x N`` array of nodes in a curve. x_val (float): ``x``-coordinate for evaluation. y_val (float): ``y``-coordinate for evaluation. Returns: float: The computed value of :math:`f(x, y)`. Raises: ValueError: If the curve is a point. .UnsupportedDegree: If the degree is not 1, 2 or 3. """ _, num_nodes = nodes.shape if num_nodes == 1: raise ValueError("A point cannot be implicitized") elif num_nodes == 2: # x(s) - x = (x0 - x) (1 - s) + (x1 - x) s # y(s) - y = (y0 - y) (1 - s) + (y1 - y) s # Modified Sylvester: [x0 - x, x1 - x] # [y0 - y, y1 - y] return (nodes[0, 0] - x_val) * (nodes[1, 1] - y_val) - ( nodes[0, 1] - x_val ) * (nodes[1, 0] - y_val) elif num_nodes == 3: # x(s) - x = (x0 - x) (1 - s)^2 + 2 (x1 - x) s(1 - s) + (x2 - x) s^2 # y(s) - y = (y0 - y) (1 - s)^2 + 2 (y1 - y) s(1 - s) + (y2 - y) s^2 # Modified Sylvester: [x0 - x, 2(x1 - x), x2 - x, 0] = A|B|C|0 # [ 0, x0 - x, 2(x1 - x), x2 - x] 0|A|B|C # [y0 - y, 2(y1 - y), y2 - y, 0] D|E|F|0 # [ 0, y0 - y, 2(y1 - y), y2 - y] 0|D|E|F val_a, val_b, val_c = nodes[0, :] - x_val val_b *= 2 val_d, val_e, val_f = nodes[1, :] - y_val val_e *= 2 # [A, B, C] [E, F, 0] # det [E, F, 0] = - det [A, B, C] = -E (BF - CE) + F(AF - CD) # [D, E, F] [D, E, F] sub1 = val_b * val_f - val_c * val_e sub2 = val_a * val_f - val_c * val_d sub_det_a = -val_e * sub1 + val_f * sub2 # [B, C, 0] # det [A, B, C] = B (BF - CE) - C (AF - CD) # [D, E, F] sub_det_d = val_b * sub1 - val_c * sub2 return val_a * sub_det_a + val_d * sub_det_d elif num_nodes == 4: return _evaluate3(nodes, x_val, y_val) else: raise _helpers.UnsupportedDegree(num_nodes - 1, supported=(1, 2, 3))
[ "def", "evaluate", "(", "nodes", ",", "x_val", ",", "y_val", ")", ":", "_", ",", "num_nodes", "=", "nodes", ".", "shape", "if", "num_nodes", "==", "1", ":", "raise", "ValueError", "(", "\"A point cannot be implicitized\"", ")", "elif", "num_nodes", "==", "2", ":", "# x(s) - x = (x0 - x) (1 - s) + (x1 - x) s", "# y(s) - y = (y0 - y) (1 - s) + (y1 - y) s", "# Modified Sylvester: [x0 - x, x1 - x]", "# [y0 - y, y1 - y]", "return", "(", "nodes", "[", "0", ",", "0", "]", "-", "x_val", ")", "*", "(", "nodes", "[", "1", ",", "1", "]", "-", "y_val", ")", "-", "(", "nodes", "[", "0", ",", "1", "]", "-", "x_val", ")", "*", "(", "nodes", "[", "1", ",", "0", "]", "-", "y_val", ")", "elif", "num_nodes", "==", "3", ":", "# x(s) - x = (x0 - x) (1 - s)^2 + 2 (x1 - x) s(1 - s) + (x2 - x) s^2", "# y(s) - y = (y0 - y) (1 - s)^2 + 2 (y1 - y) s(1 - s) + (y2 - y) s^2", "# Modified Sylvester: [x0 - x, 2(x1 - x), x2 - x, 0] = A|B|C|0", "# [ 0, x0 - x, 2(x1 - x), x2 - x] 0|A|B|C", "# [y0 - y, 2(y1 - y), y2 - y, 0] D|E|F|0", "# [ 0, y0 - y, 2(y1 - y), y2 - y] 0|D|E|F", "val_a", ",", "val_b", ",", "val_c", "=", "nodes", "[", "0", ",", ":", "]", "-", "x_val", "val_b", "*=", "2", "val_d", ",", "val_e", ",", "val_f", "=", "nodes", "[", "1", ",", ":", "]", "-", "y_val", "val_e", "*=", "2", "# [A, B, C] [E, F, 0]", "# det [E, F, 0] = - det [A, B, C] = -E (BF - CE) + F(AF - CD)", "# [D, E, F] [D, E, F]", "sub1", "=", "val_b", "*", "val_f", "-", "val_c", "*", "val_e", "sub2", "=", "val_a", "*", "val_f", "-", "val_c", "*", "val_d", "sub_det_a", "=", "-", "val_e", "*", "sub1", "+", "val_f", "*", "sub2", "# [B, C, 0]", "# det [A, B, C] = B (BF - CE) - C (AF - CD)", "# [D, E, F]", "sub_det_d", "=", "val_b", "*", "sub1", "-", "val_c", "*", "sub2", "return", "val_a", "*", "sub_det_a", "+", "val_d", "*", "sub_det_d", "elif", "num_nodes", "==", "4", ":", "return", "_evaluate3", "(", "nodes", ",", "x_val", ",", "y_val", ")", "else", ":", "raise", "_helpers", ".", "UnsupportedDegree", "(", "num_nodes", "-", "1", ",", "supported", "=", "(", "1", ",", "2", ",", "3", ")", ")" ]
r"""Evaluate the implicitized bivariate polynomial containing the curve. Assumes `algebraic curve`_ containing :math:`B(s, t)` is given by :math:`f(x, y) = 0`. This function evaluates :math:`f(x, y)`. .. note:: This assumes, but doesn't check, that ``nodes`` has 2 rows. .. note:: This assumes, but doesn't check, that ``nodes`` is not degree-elevated. If it were degree-elevated, then the Sylvester matrix will always have zero determinant. Args: nodes (numpy.ndarray): ``2 x N`` array of nodes in a curve. x_val (float): ``x``-coordinate for evaluation. y_val (float): ``y``-coordinate for evaluation. Returns: float: The computed value of :math:`f(x, y)`. Raises: ValueError: If the curve is a point. .UnsupportedDegree: If the degree is not 1, 2 or 3.
[ "r", "Evaluate", "the", "implicitized", "bivariate", "polynomial", "containing", "the", "curve", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_algebraic_intersection.py#L144-L212
dhermes/bezier
src/bezier/_algebraic_intersection.py
eval_intersection_polynomial
def eval_intersection_polynomial(nodes1, nodes2, t): r"""Evaluates a parametric curve **on** an implicitized algebraic curve. Uses :func:`evaluate` to evaluate :math:`f_1(x, y)`, the implicitization of ``nodes1``. Then plugs ``t`` into the second parametric curve to get an ``x``- and ``y``-coordinate and evaluate the **intersection polynomial**: .. math:: g(t) = f_1\left(x_2(t), y_2(t)right) Args: nodes1 (numpy.ndarray): The nodes in the first curve. nodes2 (numpy.ndarray): The nodes in the second curve. t (float): The parameter along ``nodes2`` where we evaluate the function. Returns: float: The computed value of :math:`f_1(x_2(t), y_2(t))`. """ (x_val,), (y_val,) = _curve_helpers.evaluate_multi( nodes2, np.asfortranarray([t]) ) return evaluate(nodes1, x_val, y_val)
python
def eval_intersection_polynomial(nodes1, nodes2, t): r"""Evaluates a parametric curve **on** an implicitized algebraic curve. Uses :func:`evaluate` to evaluate :math:`f_1(x, y)`, the implicitization of ``nodes1``. Then plugs ``t`` into the second parametric curve to get an ``x``- and ``y``-coordinate and evaluate the **intersection polynomial**: .. math:: g(t) = f_1\left(x_2(t), y_2(t)right) Args: nodes1 (numpy.ndarray): The nodes in the first curve. nodes2 (numpy.ndarray): The nodes in the second curve. t (float): The parameter along ``nodes2`` where we evaluate the function. Returns: float: The computed value of :math:`f_1(x_2(t), y_2(t))`. """ (x_val,), (y_val,) = _curve_helpers.evaluate_multi( nodes2, np.asfortranarray([t]) ) return evaluate(nodes1, x_val, y_val)
[ "def", "eval_intersection_polynomial", "(", "nodes1", ",", "nodes2", ",", "t", ")", ":", "(", "x_val", ",", ")", ",", "(", "y_val", ",", ")", "=", "_curve_helpers", ".", "evaluate_multi", "(", "nodes2", ",", "np", ".", "asfortranarray", "(", "[", "t", "]", ")", ")", "return", "evaluate", "(", "nodes1", ",", "x_val", ",", "y_val", ")" ]
r"""Evaluates a parametric curve **on** an implicitized algebraic curve. Uses :func:`evaluate` to evaluate :math:`f_1(x, y)`, the implicitization of ``nodes1``. Then plugs ``t`` into the second parametric curve to get an ``x``- and ``y``-coordinate and evaluate the **intersection polynomial**: .. math:: g(t) = f_1\left(x_2(t), y_2(t)right) Args: nodes1 (numpy.ndarray): The nodes in the first curve. nodes2 (numpy.ndarray): The nodes in the second curve. t (float): The parameter along ``nodes2`` where we evaluate the function. Returns: float: The computed value of :math:`f_1(x_2(t), y_2(t))`.
[ "r", "Evaluates", "a", "parametric", "curve", "**", "on", "**", "an", "implicitized", "algebraic", "curve", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_algebraic_intersection.py#L215-L239
dhermes/bezier
src/bezier/_algebraic_intersection.py
_to_power_basis11
def _to_power_basis11(nodes1, nodes2): r"""Compute the coefficients of an **intersection polynomial**. Helper for :func:`to_power_basis` in the case that each curve is degree one. In this case, B |eacute| zout's `theorem`_ tells us that the **intersection polynomial** is degree :math:`1 \cdot 1` hence we return two coefficients. Args: nodes1 (numpy.ndarray): The nodes in the first curve. nodes2 (numpy.ndarray): The nodes in the second curve. Returns: numpy.ndarray: ``2``-array of coefficients. """ # We manually invert the Vandermonde matrix: # [1 0][c0] = [n0] # [1 1][c1] [n1] val0 = eval_intersection_polynomial(nodes1, nodes2, 0.0) val1 = eval_intersection_polynomial(nodes1, nodes2, 1.0) # [c0] = [ 1 0][n0] # [c1] = [-1 1][n1] return np.asfortranarray([val0, -val0 + val1])
python
def _to_power_basis11(nodes1, nodes2): r"""Compute the coefficients of an **intersection polynomial**. Helper for :func:`to_power_basis` in the case that each curve is degree one. In this case, B |eacute| zout's `theorem`_ tells us that the **intersection polynomial** is degree :math:`1 \cdot 1` hence we return two coefficients. Args: nodes1 (numpy.ndarray): The nodes in the first curve. nodes2 (numpy.ndarray): The nodes in the second curve. Returns: numpy.ndarray: ``2``-array of coefficients. """ # We manually invert the Vandermonde matrix: # [1 0][c0] = [n0] # [1 1][c1] [n1] val0 = eval_intersection_polynomial(nodes1, nodes2, 0.0) val1 = eval_intersection_polynomial(nodes1, nodes2, 1.0) # [c0] = [ 1 0][n0] # [c1] = [-1 1][n1] return np.asfortranarray([val0, -val0 + val1])
[ "def", "_to_power_basis11", "(", "nodes1", ",", "nodes2", ")", ":", "# We manually invert the Vandermonde matrix:", "# [1 0][c0] = [n0]", "# [1 1][c1] [n1]", "val0", "=", "eval_intersection_polynomial", "(", "nodes1", ",", "nodes2", ",", "0.0", ")", "val1", "=", "eval_intersection_polynomial", "(", "nodes1", ",", "nodes2", ",", "1.0", ")", "# [c0] = [ 1 0][n0]", "# [c1] = [-1 1][n1]", "return", "np", ".", "asfortranarray", "(", "[", "val0", ",", "-", "val0", "+", "val1", "]", ")" ]
r"""Compute the coefficients of an **intersection polynomial**. Helper for :func:`to_power_basis` in the case that each curve is degree one. In this case, B |eacute| zout's `theorem`_ tells us that the **intersection polynomial** is degree :math:`1 \cdot 1` hence we return two coefficients. Args: nodes1 (numpy.ndarray): The nodes in the first curve. nodes2 (numpy.ndarray): The nodes in the second curve. Returns: numpy.ndarray: ``2``-array of coefficients.
[ "r", "Compute", "the", "coefficients", "of", "an", "**", "intersection", "polynomial", "**", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_algebraic_intersection.py#L242-L264
dhermes/bezier
src/bezier/_algebraic_intersection.py
_to_power_basis12
def _to_power_basis12(nodes1, nodes2): r"""Compute the coefficients of an **intersection polynomial**. Helper for :func:`to_power_basis` in the case that the first curve is degree one and the second is degree two. In this case, B |eacute| zout's `theorem`_ tells us that the **intersection polynomial** is degree :math:`1 \cdot 2` hence we return three coefficients. Args: nodes1 (numpy.ndarray): The nodes in the first curve. nodes2 (numpy.ndarray): The nodes in the second curve. Returns: numpy.ndarray: ``3``-array of coefficients. """ # We manually invert the Vandermonde matrix: # [1 0 0 ][c0] = [n0] # [1 1/2 1/4][c1] [n1] # [1 1 1 ][c2] [n2] val0 = eval_intersection_polynomial(nodes1, nodes2, 0.0) val1 = eval_intersection_polynomial(nodes1, nodes2, 0.5) val2 = eval_intersection_polynomial(nodes1, nodes2, 1.0) # [c0] = [ 1 0 0][n0] # [c1] = [-3 4 -1][n1] # [c2] = [ 2 -4 2][n2] return np.asfortranarray( [ val0, -3.0 * val0 + 4.0 * val1 - val2, 2.0 * val0 - 4.0 * val1 + 2.0 * val2, ] )
python
def _to_power_basis12(nodes1, nodes2): r"""Compute the coefficients of an **intersection polynomial**. Helper for :func:`to_power_basis` in the case that the first curve is degree one and the second is degree two. In this case, B |eacute| zout's `theorem`_ tells us that the **intersection polynomial** is degree :math:`1 \cdot 2` hence we return three coefficients. Args: nodes1 (numpy.ndarray): The nodes in the first curve. nodes2 (numpy.ndarray): The nodes in the second curve. Returns: numpy.ndarray: ``3``-array of coefficients. """ # We manually invert the Vandermonde matrix: # [1 0 0 ][c0] = [n0] # [1 1/2 1/4][c1] [n1] # [1 1 1 ][c2] [n2] val0 = eval_intersection_polynomial(nodes1, nodes2, 0.0) val1 = eval_intersection_polynomial(nodes1, nodes2, 0.5) val2 = eval_intersection_polynomial(nodes1, nodes2, 1.0) # [c0] = [ 1 0 0][n0] # [c1] = [-3 4 -1][n1] # [c2] = [ 2 -4 2][n2] return np.asfortranarray( [ val0, -3.0 * val0 + 4.0 * val1 - val2, 2.0 * val0 - 4.0 * val1 + 2.0 * val2, ] )
[ "def", "_to_power_basis12", "(", "nodes1", ",", "nodes2", ")", ":", "# We manually invert the Vandermonde matrix:", "# [1 0 0 ][c0] = [n0]", "# [1 1/2 1/4][c1] [n1]", "# [1 1 1 ][c2] [n2]", "val0", "=", "eval_intersection_polynomial", "(", "nodes1", ",", "nodes2", ",", "0.0", ")", "val1", "=", "eval_intersection_polynomial", "(", "nodes1", ",", "nodes2", ",", "0.5", ")", "val2", "=", "eval_intersection_polynomial", "(", "nodes1", ",", "nodes2", ",", "1.0", ")", "# [c0] = [ 1 0 0][n0]", "# [c1] = [-3 4 -1][n1]", "# [c2] = [ 2 -4 2][n2]", "return", "np", ".", "asfortranarray", "(", "[", "val0", ",", "-", "3.0", "*", "val0", "+", "4.0", "*", "val1", "-", "val2", ",", "2.0", "*", "val0", "-", "4.0", "*", "val1", "+", "2.0", "*", "val2", ",", "]", ")" ]
r"""Compute the coefficients of an **intersection polynomial**. Helper for :func:`to_power_basis` in the case that the first curve is degree one and the second is degree two. In this case, B |eacute| zout's `theorem`_ tells us that the **intersection polynomial** is degree :math:`1 \cdot 2` hence we return three coefficients. Args: nodes1 (numpy.ndarray): The nodes in the first curve. nodes2 (numpy.ndarray): The nodes in the second curve. Returns: numpy.ndarray: ``3``-array of coefficients.
[ "r", "Compute", "the", "coefficients", "of", "an", "**", "intersection", "polynomial", "**", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_algebraic_intersection.py#L267-L298
dhermes/bezier
src/bezier/_algebraic_intersection.py
_to_power_basis13
def _to_power_basis13(nodes1, nodes2): r"""Compute the coefficients of an **intersection polynomial**. Helper for :func:`to_power_basis` in the case that the first curve is degree one and the second is degree three. In this case, B |eacute| zout's `theorem`_ tells us that the **intersection polynomial** is degree :math:`1 \cdot 3` hence we return four coefficients. Args: nodes1 (numpy.ndarray): The nodes in the first curve. nodes2 (numpy.ndarray): The nodes in the second curve. Returns: numpy.ndarray: ``4``-array of coefficients. """ # We manually invert the Vandermonde matrix: # Use exact f.p. numbers to avoid round-off wherever possible. # [1 0 0 0 ][c0] = [n0] # [1 1/4 1/16 1/64 ][c1] [n1] # [1 3/4 9/16 27/64][c2] [n2] # [1 1 1 1 ][c3] [n3] val0 = eval_intersection_polynomial(nodes1, nodes2, 0.0) val1 = eval_intersection_polynomial(nodes1, nodes2, 0.25) val2 = eval_intersection_polynomial(nodes1, nodes2, 0.75) val3 = eval_intersection_polynomial(nodes1, nodes2, 1.0) # [c0] = [ 3 0 0 0][n0] # [c1] = 1 / 3 [-19 24 -8 3][n1] # [c2] = [ 32 -56 40 -16][n2] # [c3] = [-16 32 -32 16][n3] # Since polynomial coefficients, we don't need to divide by 3 # to get the same polynomial. Avoid the division to avoid round-off. return np.asfortranarray( [ 3.0 * val0, -19.0 * val0 + 24.0 * val1 - 8.0 * val2 + 3.0 * val3, 32.0 * val0 - 56.0 * val1 + 40.0 * val2 - 16.0 * val3, -16.0 * val0 + 32.0 * val1 - 32.0 * val2 + 16.0 * val3, ] )
python
def _to_power_basis13(nodes1, nodes2): r"""Compute the coefficients of an **intersection polynomial**. Helper for :func:`to_power_basis` in the case that the first curve is degree one and the second is degree three. In this case, B |eacute| zout's `theorem`_ tells us that the **intersection polynomial** is degree :math:`1 \cdot 3` hence we return four coefficients. Args: nodes1 (numpy.ndarray): The nodes in the first curve. nodes2 (numpy.ndarray): The nodes in the second curve. Returns: numpy.ndarray: ``4``-array of coefficients. """ # We manually invert the Vandermonde matrix: # Use exact f.p. numbers to avoid round-off wherever possible. # [1 0 0 0 ][c0] = [n0] # [1 1/4 1/16 1/64 ][c1] [n1] # [1 3/4 9/16 27/64][c2] [n2] # [1 1 1 1 ][c3] [n3] val0 = eval_intersection_polynomial(nodes1, nodes2, 0.0) val1 = eval_intersection_polynomial(nodes1, nodes2, 0.25) val2 = eval_intersection_polynomial(nodes1, nodes2, 0.75) val3 = eval_intersection_polynomial(nodes1, nodes2, 1.0) # [c0] = [ 3 0 0 0][n0] # [c1] = 1 / 3 [-19 24 -8 3][n1] # [c2] = [ 32 -56 40 -16][n2] # [c3] = [-16 32 -32 16][n3] # Since polynomial coefficients, we don't need to divide by 3 # to get the same polynomial. Avoid the division to avoid round-off. return np.asfortranarray( [ 3.0 * val0, -19.0 * val0 + 24.0 * val1 - 8.0 * val2 + 3.0 * val3, 32.0 * val0 - 56.0 * val1 + 40.0 * val2 - 16.0 * val3, -16.0 * val0 + 32.0 * val1 - 32.0 * val2 + 16.0 * val3, ] )
[ "def", "_to_power_basis13", "(", "nodes1", ",", "nodes2", ")", ":", "# We manually invert the Vandermonde matrix:", "# Use exact f.p. numbers to avoid round-off wherever possible.", "# [1 0 0 0 ][c0] = [n0]", "# [1 1/4 1/16 1/64 ][c1] [n1]", "# [1 3/4 9/16 27/64][c2] [n2]", "# [1 1 1 1 ][c3] [n3]", "val0", "=", "eval_intersection_polynomial", "(", "nodes1", ",", "nodes2", ",", "0.0", ")", "val1", "=", "eval_intersection_polynomial", "(", "nodes1", ",", "nodes2", ",", "0.25", ")", "val2", "=", "eval_intersection_polynomial", "(", "nodes1", ",", "nodes2", ",", "0.75", ")", "val3", "=", "eval_intersection_polynomial", "(", "nodes1", ",", "nodes2", ",", "1.0", ")", "# [c0] = [ 3 0 0 0][n0]", "# [c1] = 1 / 3 [-19 24 -8 3][n1]", "# [c2] = [ 32 -56 40 -16][n2]", "# [c3] = [-16 32 -32 16][n3]", "# Since polynomial coefficients, we don't need to divide by 3", "# to get the same polynomial. Avoid the division to avoid round-off.", "return", "np", ".", "asfortranarray", "(", "[", "3.0", "*", "val0", ",", "-", "19.0", "*", "val0", "+", "24.0", "*", "val1", "-", "8.0", "*", "val2", "+", "3.0", "*", "val3", ",", "32.0", "*", "val0", "-", "56.0", "*", "val1", "+", "40.0", "*", "val2", "-", "16.0", "*", "val3", ",", "-", "16.0", "*", "val0", "+", "32.0", "*", "val1", "-", "32.0", "*", "val2", "+", "16.0", "*", "val3", ",", "]", ")" ]
r"""Compute the coefficients of an **intersection polynomial**. Helper for :func:`to_power_basis` in the case that the first curve is degree one and the second is degree three. In this case, B |eacute| zout's `theorem`_ tells us that the **intersection polynomial** is degree :math:`1 \cdot 3` hence we return four coefficients. Args: nodes1 (numpy.ndarray): The nodes in the first curve. nodes2 (numpy.ndarray): The nodes in the second curve. Returns: numpy.ndarray: ``4``-array of coefficients.
[ "r", "Compute", "the", "coefficients", "of", "an", "**", "intersection", "polynomial", "**", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_algebraic_intersection.py#L301-L339
dhermes/bezier
src/bezier/_algebraic_intersection.py
_to_power_basis_degree4
def _to_power_basis_degree4(nodes1, nodes2): r"""Compute the coefficients of an **intersection polynomial**. Helper for :func:`to_power_basis` in the case that B |eacute| zout's `theorem`_ tells us the **intersection polynomial** is degree :math:`4`. This happens if the two curves have degrees two and two or have degrees one and four. Args: nodes1 (numpy.ndarray): The nodes in the first curve. nodes2 (numpy.ndarray): The nodes in the second curve. Returns: numpy.ndarray: ``5``-array of coefficients. """ # We manually invert the Vandermonde matrix: # [1 0 0 0 0 ][c0] = [n0] # [1 1/4 1/16 1/64 1/256 ][c1] [n1] # [1 1/2 1/4 1/8 1/16 ][c2] [n2] # [1 3/4 9/16 27/64 81/256][c3] [n3] # [1 1 1 1 1 ][c4] [n4] val0 = eval_intersection_polynomial(nodes1, nodes2, 0.0) val1 = eval_intersection_polynomial(nodes1, nodes2, 0.25) val2 = eval_intersection_polynomial(nodes1, nodes2, 0.5) val3 = eval_intersection_polynomial(nodes1, nodes2, 0.75) val4 = eval_intersection_polynomial(nodes1, nodes2, 1.0) # [c0] = [ 3 0 0 0 0 ][n0] # [c1] = 1 / 3 [-25 48 -36 16 -3 ][n1] # [c2] = [ 70 -208 228 -112 22][n2] # [c3] = [-80 288 -384 224 -48][n3] # [c4] = [ 32 -128 192 -128 32][n4] # Since polynomial coefficients, we don't need to divide by 3 # to get the same polynomial. Avoid the division to avoid round-off. return np.asfortranarray( [ 3.0 * val0, -25.0 * val0 + 48.0 * val1 - 36.0 * val2 + 16.0 * val3 - 3.0 * val4, 70.0 * val0 - 208.0 * val1 + 228.0 * val2 - 112.0 * val3 + 22.0 * val4, ( -80.0 * val0 + 288.0 * val1 - 384.0 * val2 + 224.0 * val3 - 48.0 * val4 ), 32.0 * val0 - 128.0 * val1 + 192.0 * val2 - 128.0 * val3 + 32.0 * val4, ] )
python
def _to_power_basis_degree4(nodes1, nodes2): r"""Compute the coefficients of an **intersection polynomial**. Helper for :func:`to_power_basis` in the case that B |eacute| zout's `theorem`_ tells us the **intersection polynomial** is degree :math:`4`. This happens if the two curves have degrees two and two or have degrees one and four. Args: nodes1 (numpy.ndarray): The nodes in the first curve. nodes2 (numpy.ndarray): The nodes in the second curve. Returns: numpy.ndarray: ``5``-array of coefficients. """ # We manually invert the Vandermonde matrix: # [1 0 0 0 0 ][c0] = [n0] # [1 1/4 1/16 1/64 1/256 ][c1] [n1] # [1 1/2 1/4 1/8 1/16 ][c2] [n2] # [1 3/4 9/16 27/64 81/256][c3] [n3] # [1 1 1 1 1 ][c4] [n4] val0 = eval_intersection_polynomial(nodes1, nodes2, 0.0) val1 = eval_intersection_polynomial(nodes1, nodes2, 0.25) val2 = eval_intersection_polynomial(nodes1, nodes2, 0.5) val3 = eval_intersection_polynomial(nodes1, nodes2, 0.75) val4 = eval_intersection_polynomial(nodes1, nodes2, 1.0) # [c0] = [ 3 0 0 0 0 ][n0] # [c1] = 1 / 3 [-25 48 -36 16 -3 ][n1] # [c2] = [ 70 -208 228 -112 22][n2] # [c3] = [-80 288 -384 224 -48][n3] # [c4] = [ 32 -128 192 -128 32][n4] # Since polynomial coefficients, we don't need to divide by 3 # to get the same polynomial. Avoid the division to avoid round-off. return np.asfortranarray( [ 3.0 * val0, -25.0 * val0 + 48.0 * val1 - 36.0 * val2 + 16.0 * val3 - 3.0 * val4, 70.0 * val0 - 208.0 * val1 + 228.0 * val2 - 112.0 * val3 + 22.0 * val4, ( -80.0 * val0 + 288.0 * val1 - 384.0 * val2 + 224.0 * val3 - 48.0 * val4 ), 32.0 * val0 - 128.0 * val1 + 192.0 * val2 - 128.0 * val3 + 32.0 * val4, ] )
[ "def", "_to_power_basis_degree4", "(", "nodes1", ",", "nodes2", ")", ":", "# We manually invert the Vandermonde matrix:", "# [1 0 0 0 0 ][c0] = [n0]", "# [1 1/4 1/16 1/64 1/256 ][c1] [n1]", "# [1 1/2 1/4 1/8 1/16 ][c2] [n2]", "# [1 3/4 9/16 27/64 81/256][c3] [n3]", "# [1 1 1 1 1 ][c4] [n4]", "val0", "=", "eval_intersection_polynomial", "(", "nodes1", ",", "nodes2", ",", "0.0", ")", "val1", "=", "eval_intersection_polynomial", "(", "nodes1", ",", "nodes2", ",", "0.25", ")", "val2", "=", "eval_intersection_polynomial", "(", "nodes1", ",", "nodes2", ",", "0.5", ")", "val3", "=", "eval_intersection_polynomial", "(", "nodes1", ",", "nodes2", ",", "0.75", ")", "val4", "=", "eval_intersection_polynomial", "(", "nodes1", ",", "nodes2", ",", "1.0", ")", "# [c0] = [ 3 0 0 0 0 ][n0]", "# [c1] = 1 / 3 [-25 48 -36 16 -3 ][n1]", "# [c2] = [ 70 -208 228 -112 22][n2]", "# [c3] = [-80 288 -384 224 -48][n3]", "# [c4] = [ 32 -128 192 -128 32][n4]", "# Since polynomial coefficients, we don't need to divide by 3", "# to get the same polynomial. Avoid the division to avoid round-off.", "return", "np", ".", "asfortranarray", "(", "[", "3.0", "*", "val0", ",", "-", "25.0", "*", "val0", "+", "48.0", "*", "val1", "-", "36.0", "*", "val2", "+", "16.0", "*", "val3", "-", "3.0", "*", "val4", ",", "70.0", "*", "val0", "-", "208.0", "*", "val1", "+", "228.0", "*", "val2", "-", "112.0", "*", "val3", "+", "22.0", "*", "val4", ",", "(", "-", "80.0", "*", "val0", "+", "288.0", "*", "val1", "-", "384.0", "*", "val2", "+", "224.0", "*", "val3", "-", "48.0", "*", "val4", ")", ",", "32.0", "*", "val0", "-", "128.0", "*", "val1", "+", "192.0", "*", "val2", "-", "128.0", "*", "val3", "+", "32.0", "*", "val4", ",", "]", ")" ]
r"""Compute the coefficients of an **intersection polynomial**. Helper for :func:`to_power_basis` in the case that B |eacute| zout's `theorem`_ tells us the **intersection polynomial** is degree :math:`4`. This happens if the two curves have degrees two and two or have degrees one and four. Args: nodes1 (numpy.ndarray): The nodes in the first curve. nodes2 (numpy.ndarray): The nodes in the second curve. Returns: numpy.ndarray: ``5``-array of coefficients.
[ "r", "Compute", "the", "coefficients", "of", "an", "**", "intersection", "polynomial", "**", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_algebraic_intersection.py#L342-L401
dhermes/bezier
src/bezier/_algebraic_intersection.py
_to_power_basis23
def _to_power_basis23(nodes1, nodes2): r"""Compute the coefficients of an **intersection polynomial**. Helper for :func:`to_power_basis` in the case that the first curve is degree two and the second is degree three. In this case, B |eacute| zout's `theorem`_ tells us that the **intersection polynomial** is degree :math:`2 \cdot 3` hence we return seven coefficients. .. note:: This uses a least-squares fit to the function evaluated at the Chebyshev nodes (scaled and shifted onto ``[0, 1]``). Hence, the coefficients may be less stable than those produced for smaller degrees. Args: nodes1 (numpy.ndarray): The nodes in the first curve. nodes2 (numpy.ndarray): The nodes in the second curve. Returns: numpy.ndarray: ``7``-array of coefficients. """ evaluated = [ eval_intersection_polynomial(nodes1, nodes2, t_val) for t_val in _CHEB7 ] return polynomial.polyfit(_CHEB7, evaluated, 6)
python
def _to_power_basis23(nodes1, nodes2): r"""Compute the coefficients of an **intersection polynomial**. Helper for :func:`to_power_basis` in the case that the first curve is degree two and the second is degree three. In this case, B |eacute| zout's `theorem`_ tells us that the **intersection polynomial** is degree :math:`2 \cdot 3` hence we return seven coefficients. .. note:: This uses a least-squares fit to the function evaluated at the Chebyshev nodes (scaled and shifted onto ``[0, 1]``). Hence, the coefficients may be less stable than those produced for smaller degrees. Args: nodes1 (numpy.ndarray): The nodes in the first curve. nodes2 (numpy.ndarray): The nodes in the second curve. Returns: numpy.ndarray: ``7``-array of coefficients. """ evaluated = [ eval_intersection_polynomial(nodes1, nodes2, t_val) for t_val in _CHEB7 ] return polynomial.polyfit(_CHEB7, evaluated, 6)
[ "def", "_to_power_basis23", "(", "nodes1", ",", "nodes2", ")", ":", "evaluated", "=", "[", "eval_intersection_polynomial", "(", "nodes1", ",", "nodes2", ",", "t_val", ")", "for", "t_val", "in", "_CHEB7", "]", "return", "polynomial", ".", "polyfit", "(", "_CHEB7", ",", "evaluated", ",", "6", ")" ]
r"""Compute the coefficients of an **intersection polynomial**. Helper for :func:`to_power_basis` in the case that the first curve is degree two and the second is degree three. In this case, B |eacute| zout's `theorem`_ tells us that the **intersection polynomial** is degree :math:`2 \cdot 3` hence we return seven coefficients. .. note:: This uses a least-squares fit to the function evaluated at the Chebyshev nodes (scaled and shifted onto ``[0, 1]``). Hence, the coefficients may be less stable than those produced for smaller degrees. Args: nodes1 (numpy.ndarray): The nodes in the first curve. nodes2 (numpy.ndarray): The nodes in the second curve. Returns: numpy.ndarray: ``7``-array of coefficients.
[ "r", "Compute", "the", "coefficients", "of", "an", "**", "intersection", "polynomial", "**", "." ]
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_algebraic_intersection.py#L404-L429