bugged
stringlengths
4
228k
fixed
stringlengths
0
96.3M
__index_level_0__
int64
0
481k
def integral(f, *args, **kwds): r""" The integral of `f`. EXAMPLES:: sage: integral(sin(x), x) -cos(x) sage: integral(sin(x)^2, x, pi, 123*pi/2) 121/4*pi sage: integral( sin(x), x, 0, pi) 2 We integrate a symbolic function:: sage: f(x,y,z) = x*y/z + sin(z) sage: integral(f, z) (x, y, z) |--> x*y*log(z) - cos(z) :: sage: var('a,b') (a, b) sage: assume(b-a>0) sage: integral( sin(x), x, a, b) cos(a) - cos(b) sage: forget() :: sage: integral(x/(x^3-1), x) 1/3*sqrt(3)*arctan(1/3*(2*x + 1)*sqrt(3)) + 1/3*log(x - 1) - 1/6*log(x^2 + x + 1) :: sage: integral( exp(-x^2), x ) 1/2*sqrt(pi)*erf(x) We define the Gaussian, plot and integrate it numerically and symbolically:: sage: f(x) = 1/(sqrt(2*pi)) * e^(-x^2/2) sage: P = plot(f, -4, 4, hue=0.8, thickness=2) sage: P.show(ymin=0, ymax=0.4) sage: numerical_integral(f, -4, 4) # random output (0.99993665751633376, 1.1101527003413533e-14) sage: integrate(f, x) x |--> 1/2*erf(1/2*sqrt(2)*x) You can have Sage calculate multiple integrals. For example, consider the function `exp(y^2)` on the region between the lines `x=y`, `x=1`, and `y=0`. We find the value of the integral on this region using the command:: sage: area = integral(integral(exp(y^2),x,0,y),y,0,1); area 1/2*e - 1/2 sage: float(area) 0.85914091422952255 We compute the line integral of `\sin(x)` along the arc of the curve `x=y^4` from `(1,-1)` to `(1,1)`:: sage: t = var('t') sage: (x,y) = (t^4,t) sage: (dx,dy) = (diff(x,t), diff(y,t)) sage: integral(sin(x)*dx, t,-1, 1) 0 sage: restore('x,y') # restore the symbolic variables x and y Sage is unable to do anything with the following integral:: sage: integral( exp(-x^2)*log(x), x ) integrate(e^(-x^2)*log(x), x) Note, however, that:: sage: integral( exp(-x^2)*ln(x), x, 0, oo) -1/4*(euler_gamma + 2*log(2))*sqrt(pi) This definite integral is easy:: sage: integral( ln(x)/x, x, 1, 2) 1/2*log(2)^2 Sage can't do this elliptic integral (yet):: sage: integral(1/sqrt(2*t^4 - 3*t^2 - 2), t, 2, 3) integrate(1/sqrt(2*t^4 - 3*t^2 - 2), t, 2, 3) A double integral:: sage: y = var('y') sage: integral(integral(x*y^2, x, 0, y), y, -2, 2) 32/5 This illustrates using assumptions:: sage: integral(abs(x), x, 0, 5) 25/2 sage: integral(abs(x), x, 0, a) integrate(abs(x), x, 0, a) sage: assume(a>0) sage: integral(abs(x), x, 0, a) 1/2*a^2 sage: forget() # forget the assumptions. We integrate and differentiate a huge mess:: sage: f = (x^2-1+3*(1+x^2)^(1/3))/(1+x^2)^(2/3)*x/(x^2+2)^2 sage: g = integral(f, x) sage: h = f - diff(g, x) :: sage: [float(h(i)) for i in range(5)] #random [0.0, -1.1102230246251565e-16, -5.5511151231257827e-17, -5.5511151231257827e-17, -6.9388939039072284e-17] sage: h.factor() 0 sage: bool(h == 0) True """ try: return f.integral(*args, **kwds) except AttributeError: pass if not isinstance(f, Expression): f = SR(f) return f.integral(*args, **kwds)
def integral(f, *args, **kwds): r""" The integral of `f`. EXAMPLES:: sage: integral(sin(x), x) -cos(x) sage: integral(sin(x)^2, x, pi, 123*pi/2) 121/4*pi sage: integral( sin(x), x, 0, pi) 2 We integrate a symbolic function:: sage: f(x,y,z) = x*y/z + sin(z) sage: integral(f, z) (x, y, z) |--> x*y*log(z) - cos(z) :: sage: var('a,b') (a, b) sage: assume(b-a>0) sage: integral( sin(x), x, a, b) cos(a) - cos(b) sage: forget() :: sage: integral(x/(x^3-1), x) 1/3*sqrt(3)*arctan(1/3*(2*x + 1)*sqrt(3)) + 1/3*log(x - 1) - 1/6*log(x^2 + x + 1) :: sage: integral( exp(-x^2), x ) 1/2*sqrt(pi)*erf(x) We define the Gaussian, plot and integrate it numerically and symbolically:: sage: f(x) = 1/(sqrt(2*pi)) * e^(-x^2/2) sage: P = plot(f, -4, 4, hue=0.8, thickness=2) sage: P.show(ymin=0, ymax=0.4) sage: numerical_integral(f, -4, 4) # random output (0.99993665751633376, 1.1101527003413533e-14) sage: integrate(f, x) x |--> 1/2*erf(1/2*sqrt(2)*x) You can have Sage calculate multiple integrals. For example, consider the function `exp(y^2)` on the region between the lines `x=y`, `x=1`, and `y=0`. We find the value of the integral on this region using the command:: sage: area = integral(integral(exp(y^2),x,0,y),y,0,1); area 1/2*e - 1/2 sage: float(area) 0.859140914229522... We compute the line integral of `\sin(x)` along the arc of the curve `x=y^4` from `(1,-1)` to `(1,1)`:: sage: t = var('t') sage: (x,y) = (t^4,t) sage: (dx,dy) = (diff(x,t), diff(y,t)) sage: integral(sin(x)*dx, t,-1, 1) 0 sage: restore('x,y') # restore the symbolic variables x and y Sage is unable to do anything with the following integral:: sage: integral( exp(-x^2)*log(x), x ) integrate(e^(-x^2)*log(x), x) Note, however, that:: sage: integral( exp(-x^2)*ln(x), x, 0, oo) -1/4*(euler_gamma + 2*log(2))*sqrt(pi) This definite integral is easy:: sage: integral( ln(x)/x, x, 1, 2) 1/2*log(2)^2 Sage can't do this elliptic integral (yet):: sage: integral(1/sqrt(2*t^4 - 3*t^2 - 2), t, 2, 3) integrate(1/sqrt(2*t^4 - 3*t^2 - 2), t, 2, 3) A double integral:: sage: y = var('y') sage: integral(integral(x*y^2, x, 0, y), y, -2, 2) 32/5 This illustrates using assumptions:: sage: integral(abs(x), x, 0, 5) 25/2 sage: integral(abs(x), x, 0, a) integrate(abs(x), x, 0, a) sage: assume(a>0) sage: integral(abs(x), x, 0, a) 1/2*a^2 sage: forget() # forget the assumptions. We integrate and differentiate a huge mess:: sage: f = (x^2-1+3*(1+x^2)^(1/3))/(1+x^2)^(2/3)*x/(x^2+2)^2 sage: g = integral(f, x) sage: h = f - diff(g, x) :: sage: [float(h(i)) for i in range(5)] #random [0.0, -1.1102230246251565e-16, -5.5511151231257827e-17, -5.5511151231257827e-17, -6.9388939039072284e-17] sage: h.factor() 0 sage: bool(h == 0) True """ try: return f.integral(*args, **kwds) except AttributeError: pass if not isinstance(f, Expression): f = SR(f) return f.integral(*args, **kwds)
472,400
def from_polynomial_exp(self, p): r""" Conversion from polynomial in exponential notation
def from_polynomial_exp(self, p): r""" Conversion from polynomial in exponential notation
472,401
def reduced_rauzy_graph(self, n): r""" Returns the reduced Rauzy graph of order `n` of self.
def reduced_rauzy_graph(self, n): r""" Returns the reduced Rauzy graph of order `n` of self.
472,402
def reduced_rauzy_graph(self, n): r""" Returns the reduced Rauzy graph of order `n` of self.
def reduced_rauzy_graph(self, n): r""" Returns the reduced Rauzy graph of order `n` of self.
472,403
def reduced_rauzy_graph(self, n): r""" Returns the reduced Rauzy graph of order `n` of self.
def reduced_rauzy_graph(self, n): r""" Returns the reduced Rauzy graph of order `n` of self.
472,404
def reduced_rauzy_graph(self, n): r""" Returns the reduced Rauzy graph of order `n` of self.
def reduced_rauzy_graph(self, n): r""" Returns the reduced Rauzy graph of order `n` of self.
472,405
def reduced_rauzy_graph(self, n): r""" Returns the reduced Rauzy graph of order `n` of self.
def reduced_rauzy_graph(self, n): r""" Returns the reduced Rauzy graph of order `n` of self.
472,406
def reduced_rauzy_graph(self, n): r""" Returns the reduced Rauzy graph of order `n` of self.
def reduced_rauzy_graph(self, n): r""" Returns the reduced Rauzy graph of order `n` of self.
472,407
def reduced_rauzy_graph(self, n): r""" Returns the reduced Rauzy graph of order `n` of self.
def reduced_rauzy_graph(self, n): r""" Returns the reduced Rauzy graph of order `n` of self.
472,408
def reduced_rauzy_graph(self, n): r""" Returns the reduced Rauzy graph of order `n` of self.
def reduced_rauzy_graph(self, n): r""" Returns the reduced Rauzy graph of order `n` of self.
472,409
def __call__(self, P): r""" Returns a rational point P in the abstract Homset J(K), given:
def __call__(self, P): r""" Returns a rational point P in the abstract Homset J(K), given:
472,410
def coerce_field(self, other): """ Return the number type that contains both `self.field()` and `other`.
def coerce_field(self, other): """ Return the number type that contains both `self.field()` and `other`.
472,411
def coerce_field(self, other): """ Return the number type that contains both `self.field()` and `other`.
def coerce_field(self, other): """ Return the number type that contains both `self.field()` and `other`.
472,412
def coerce_field(self, other): """ Return the number type that contains both `self.field()` and `other`.
def coerce_field(self, other): """ Return the number type that contains both `self.field()` and `other`.
472,413
def coerce_field(self, other): """ Return the number type that contains both `self.field()` and `other`.
def coerce_field(self, other): """ Return the number type that contains both `self.field()` and `other`.
472,414
def coerce_field(self, other): """ Return the number type that contains both `self.field()` and `other`.
def coerce_field(self, other): """ Return the number type that contains both `self.field()` and `other`.
472,415
def sturm_bound(self, M=None): r""" For a space M of modular forms, this function returns an integer B such that two modular forms in either self or M are equal if and only if their q-expansions are equal to precision B (note that this is 1+ the usual Sturm bound, since `O(q^\mathrm{prec})` has precision prec). If M is none, then M is set equal to self.
def sturm_bound(self, M=None): r""" For a space M of modular forms, this function returns an integer B such that two modular forms in either self or M are equal if and only if their q-expansions are equal to precision B (note that this is 1+ the usual Sturm bound, since `O(q^\mathrm{prec})` has precision prec). If M is none, then M is set equal to self.
472,416
def __classcall_private__(cls, fam, facade=True, keepkey=False): # was *args, **options): """ Normalization of arguments; see :cls:`UniqueRepresentation`.
def __classcall_private__(cls, fam, facade=True, keepkey=False): # was *args, **options): """ Normalization of arguments; see :cls:`UniqueRepresentation`.
472,417
def is_divisible_by(self, m): """ Return True if there exists a point `Q` defined over the same field as self such that `mQ` == self.
def is_divisible_by(self, m): """ Return True if there exists a point `Q` defined over the same field as self such that `mQ` == self.
472,418
def deprecation(message, version=None): r""" Issue a deprecation warning. INPUT: - ``message`` - an explanation why things are deprecated and by what it should be replaced. - ``version`` - (optional) on which version and when the deprecation occured. Please put there the version of sageq at the time of deprecation. EXAMPLES:: sage: def foo(): ... sage.misc.misc.deprecation("The function foo is replaced by bar.") sage: foo() doctest:...: DeprecationWarning: The function foo is replaced by bar. sage: def bar(): ... sage.misc.misc.deprecation("The function bar is removed.", ... 'Sage Version 4.2') sage: bar() doctest:...: DeprecationWarning: (Since Sage Version 4.2) The function bar is removed. """ # Stack level 3 to get the line number of the code which called # the deprecated function which called this function. if version is not None: message = "(Since " + version + ") " + message warn(message, DeprecationWarning, stacklevel=3)
def deprecation(message, version=None): r""" Issue a deprecation warning. INPUT: - ``message`` - an explanation why things are deprecated and by what it should be replaced. - ``version`` - (optional) on which version and when the deprecation occurred. Please put there the version of sage at the time of deprecation. EXAMPLES:: sage: def foo(): ... sage.misc.misc.deprecation("The function foo is replaced by bar.") sage: foo() doctest:...: DeprecationWarning: The function foo is replaced by bar. sage: def bar(): ... sage.misc.misc.deprecation("The function bar is removed.", ... 'Sage Version 4.2') sage: bar() doctest:...: DeprecationWarning: (Since Sage Version 4.2) The function bar is removed. """ # Stack level 3 to get the line number of the code which called # the deprecated function which called this function. if version is not None: message = "(Since " + version + ") " + message warn(message, DeprecationWarning, stacklevel=3)
472,419
sage: def bar():
sage: def bar():
472,420
def _render_on_subplot(self, subplot): """ TESTS:
def _render_on_subplot(self, subplot): """ TESTS:
472,421
def _render_on_subplot(self, subplot): """ TESTS:
def _render_on_subplot(self, subplot): """ TESTS:
472,422
def region_plot(f, xrange, yrange, plot_points, incol, outcol, bordercol, borderstyle, borderwidth,**options): r""" ``region_plot`` takes a boolean function of two variables, `f(x,y)` and plots the region where f is True over the specified ``xrange`` and ``yrange`` as demonstrated below. ``region_plot(f, (xmin, xmax), (ymin, ymax), ...)`` INPUT: - ``f`` -- a boolean function of two variables - ``(xmin, xmax)`` -- 2-tuple, the range of ``x`` values OR 3-tuple ``(x,xmin,xmax)`` - ``(ymin, ymax)`` -- 2-tuple, the range of ``y`` values OR 3-tuple ``(y,ymin,ymax)`` - ``plot_points`` -- integer (default: 100); number of points to plot in each direction of the grid - ``incol`` -- a color (default: ``'blue'``), the color inside the region - ``outcol`` -- a color (default: ``'white'``), the color of the outside of the region If any of these options are specified, the border will be shown as indicated, otherwise it is only implicit (with color ``incol``) as the border of the inside of the region. - ``bordercol`` -- a color (default: ``None``), the color of the border (``'black'`` if ``borderwidth`` or ``borderstyle`` is specified but not ``bordercol``) - ``borderstyle`` -- string (default: 'solid'), one of 'solid', 'dashed', 'dotted', 'dashdot' - ``borderwidth`` -- integer (default: None), the width of the border in pixels EXAMPLES: Here we plot a simple function of two variables:: sage: x,y = var('x,y') sage: region_plot(cos(x^2+y^2) <= 0, (x, -3, 3), (y, -3, 3)) Here we play with the colors:: sage: region_plot(x^2+y^3 < 2, (x, -2, 2), (y, -2, 2), incol='lightblue', bordercol='gray') An even more complicated plot, with dashed borders:: sage: region_plot(sin(x)*sin(y) >= 1/4, (x,-10,10), (y,-10,10), incol='yellow', bordercol='black', borderstyle='dashed', plot_points=250) A disk centered at the origin:: sage: region_plot(x^2+y^2<1, (x,-1,1), (y,-1,1), aspect_ratio=1) A plot with more than one condition (all conditions must be true for the statement to be true):: sage: region_plot([x^2+y^2<1, x<y], (x,-2,2), (y,-2,2), aspect_ratio=1) Since it doesn't look very good, let's increase plot_points:: sage: region_plot([x^2+y^2<1, x<y], (x,-2,2), (y,-2,2), plot_points=400, aspect_ratio=1) To get plots where only one condition needs to be true, use a function:: sage: region_plot(lambda x,y: x^2+y^2<1 or x<y, (x,-2,2), (y,-2,2), aspect_ratio=1) The first quadrant of the unit circle:: sage: region_plot([y>0, x>0, x^2+y^2<1], (x,-1.1, 1.1), (y,-1.1, 1.1), plot_points = 400, aspect_ratio=1) Here is another plot, with a huge border:: sage: region_plot(x*(x-1)*(x+1)+y^2<0, (x, -3, 2), (y, -3, 3), incol='lightblue', bordercol='gray', borderwidth=10, plot_points=50) If we want to keep only the region where x is positive:: sage: region_plot([x*(x-1)*(x+1)+y^2<0, x>-1], (x, -3, 2), (y, -3, 3), incol='lightblue', plot_points=50) Here we have a cut circle:: sage: region_plot([x^2+y^2<4, x>-1], (x, -2, 2), (y, -2, 2), incol='lightblue', bordercol='gray', plot_points=200, aspect_ratio=1) The first variable range corresponds to the horizontal axis and the second variable range corresponds to the vertical axis:: sage: s,t=var('s,t') sage: region_plot(s>0,(t,-2,2),(s,-2,2)) sage: region_plot(s>0,(s,-2,2),(t,-2,2)) """ from sage.plot.plot import Graphics from sage.plot.misc import setup_for_eval_on_grid import numpy if not isinstance(f, (list, tuple)): f = [f] f = [equify(g) for g in f] g, ranges = setup_for_eval_on_grid(f, [xrange, yrange], plot_points) xrange,yrange=[r[:2] for r in ranges] xy_data_arrays = numpy.asarray([[[func(x, y) for x in xsrange(*ranges[0], include_endpoint=True)] for y in xsrange(*ranges[1], include_endpoint=True)] for func in g],dtype=float) xy_data_array=numpy.abs(xy_data_arrays.prod(axis=0)) # Now we need to set entries to negative iff all # functions were negative at that point. neg_indices = (xy_data_arrays<0).all(axis=0) xy_data_array[neg_indices]=-xy_data_array[neg_indices] from matplotlib.colors import ListedColormap incol = rgbcolor(incol) outcol = rgbcolor(outcol) cmap = ListedColormap([incol, outcol]) cmap.set_over(outcol) cmap.set_under(incol) g = Graphics() g._set_extra_kwds(Graphics._extract_kwds_for_show(options, ignore=['xmin', 'xmax'])) g.add_primitive(ContourPlot(xy_data_array, xrange,yrange, dict(contours=[-1e307, 0, 1e307], cmap=cmap, fill=True, labels=False, **options))) if bordercol or borderstyle or borderwidth: cmap = [rgbcolor(bordercol)] if bordercol else ['black'] linestyles = [borderstyle] if borderstyle else None linewidths = [borderwidth] if borderwidth else None g.add_primitive(ContourPlot(xy_data_array, xrange, yrange, dict(linestyles=linestyles, linewidths=linewidths, contours=[0], cmap=[bordercol], fill=False, labels=False, **options))) return g
def region_plot(f, xrange, yrange, plot_points, incol, outcol, bordercol, borderstyle, borderwidth,**options): r""" ``region_plot`` takes a boolean function of two variables, `f(x,y)` and plots the region where f is True over the specified ``xrange`` and ``yrange`` as demonstrated below. ``region_plot(f, (xmin, xmax), (ymin, ymax), ...)`` INPUT: - ``f`` -- a boolean function of two variables - ``(xmin, xmax)`` -- 2-tuple, the range of ``x`` values OR 3-tuple ``(x,xmin,xmax)`` - ``(ymin, ymax)`` -- 2-tuple, the range of ``y`` values OR 3-tuple ``(y,ymin,ymax)`` - ``plot_points`` -- integer (default: 100); number of points to plot in each direction of the grid - ``incol`` -- a color (default: ``'blue'``), the color inside the region - ``outcol`` -- a color (default: ``'white'``), the color of the outside of the region If any of these options are specified, the border will be shown as indicated, otherwise it is only implicit (with color ``incol``) as the border of the inside of the region. - ``bordercol`` -- a color (default: ``None``), the color of the border (``'black'`` if ``borderwidth`` or ``borderstyle`` is specified but not ``bordercol``) - ``borderstyle`` -- string (default: 'solid'), one of 'solid', 'dashed', 'dotted', 'dashdot' - ``borderwidth`` -- integer (default: None), the width of the border in pixels EXAMPLES: Here we plot a simple function of two variables:: sage: x,y = var('x,y') sage: region_plot(cos(x^2+y^2) <= 0, (x, -3, 3), (y, -3, 3)) Here we play with the colors:: sage: region_plot(x^2+y^3 < 2, (x, -2, 2), (y, -2, 2), incol='lightblue', bordercol='gray') An even more complicated plot, with dashed borders:: sage: region_plot(sin(x)*sin(y) >= 1/4, (x,-10,10), (y,-10,10), incol='yellow', bordercol='black', borderstyle='dashed', plot_points=250) A disk centered at the origin:: sage: region_plot(x^2+y^2<1, (x,-1,1), (y,-1,1), aspect_ratio=1) A plot with more than one condition (all conditions must be true for the statement to be true):: sage: region_plot([x^2+y^2<1, x<y], (x,-2,2), (y,-2,2), aspect_ratio=1) Since it doesn't look very good, let's increase plot_points:: sage: region_plot([x^2+y^2<1, x<y], (x,-2,2), (y,-2,2), plot_points=400, aspect_ratio=1) To get plots where only one condition needs to be true, use a function:: sage: region_plot(lambda x,y: x^2+y^2<1 or x<y, (x,-2,2), (y,-2,2), aspect_ratio=1) The first quadrant of the unit circle:: sage: region_plot([y>0, x>0, x^2+y^2<1], (x,-1.1, 1.1), (y,-1.1, 1.1), plot_points = 400, aspect_ratio=1) Here is another plot, with a huge border:: sage: region_plot(x*(x-1)*(x+1)+y^2<0, (x, -3, 2), (y, -3, 3), incol='lightblue', bordercol='gray', borderwidth=10, plot_points=50) If we want to keep only the region where x is positive:: sage: region_plot([x*(x-1)*(x+1)+y^2<0, x>-1], (x, -3, 2), (y, -3, 3), incol='lightblue', plot_points=50) Here we have a cut circle:: sage: region_plot([x^2+y^2<4, x>-1], (x, -2, 2), (y, -2, 2), incol='lightblue', bordercol='gray', plot_points=200, aspect_ratio=1) The first variable range corresponds to the horizontal axis and the second variable range corresponds to the vertical axis:: sage: s,t=var('s,t') sage: region_plot(s>0,(t,-2,2),(s,-2,2)) sage: region_plot(s>0,(s,-2,2),(t,-2,2)) """ from sage.plot.plot import Graphics from sage.plot.misc import setup_for_eval_on_grid import numpy if not isinstance(f, (list, tuple)): f = [f] f = [equify(g) for g in f] g, ranges = setup_for_eval_on_grid(f, [xrange, yrange], plot_points) xrange,yrange=[r[:2] for r in ranges] xy_data_arrays = numpy.asarray([[[func(x, y) for x in xsrange(*ranges[0], include_endpoint=True)] for y in xsrange(*ranges[1], include_endpoint=True)] for func in g],dtype=float) xy_data_array=numpy.abs(xy_data_arrays.prod(axis=0)) # Now we need to set entries to negative iff all # functions were negative at that point. neg_indices = (xy_data_arrays<0).all(axis=0) xy_data_array[neg_indices]=-xy_data_array[neg_indices] from matplotlib.colors import ListedColormap incol = rgbcolor(incol) outcol = rgbcolor(outcol) cmap = ListedColormap([incol, outcol]) cmap.set_over(outcol) cmap.set_under(incol) g = Graphics() g._set_extra_kwds(Graphics._extract_kwds_for_show(options, ignore=['xmin', 'xmax'])) g.add_primitive(ContourPlot(xy_data_array, xrange,yrange, dict(contours=[-1e307, 0, 1e307], cmap=cmap, fill=True, **options))) if bordercol or borderstyle or borderwidth: cmap = [rgbcolor(bordercol)] if bordercol else ['black'] linestyles = [borderstyle] if borderstyle else None linewidths = [borderwidth] if borderwidth else None g.add_primitive(ContourPlot(xy_data_array, xrange, yrange, dict(linestyles=linestyles, linewidths=linewidths, contours=[0], cmap=[bordercol], fill=False, labels=False, **options))) return g
472,423
def region_plot(f, xrange, yrange, plot_points, incol, outcol, bordercol, borderstyle, borderwidth,**options): r""" ``region_plot`` takes a boolean function of two variables, `f(x,y)` and plots the region where f is True over the specified ``xrange`` and ``yrange`` as demonstrated below. ``region_plot(f, (xmin, xmax), (ymin, ymax), ...)`` INPUT: - ``f`` -- a boolean function of two variables - ``(xmin, xmax)`` -- 2-tuple, the range of ``x`` values OR 3-tuple ``(x,xmin,xmax)`` - ``(ymin, ymax)`` -- 2-tuple, the range of ``y`` values OR 3-tuple ``(y,ymin,ymax)`` - ``plot_points`` -- integer (default: 100); number of points to plot in each direction of the grid - ``incol`` -- a color (default: ``'blue'``), the color inside the region - ``outcol`` -- a color (default: ``'white'``), the color of the outside of the region If any of these options are specified, the border will be shown as indicated, otherwise it is only implicit (with color ``incol``) as the border of the inside of the region. - ``bordercol`` -- a color (default: ``None``), the color of the border (``'black'`` if ``borderwidth`` or ``borderstyle`` is specified but not ``bordercol``) - ``borderstyle`` -- string (default: 'solid'), one of 'solid', 'dashed', 'dotted', 'dashdot' - ``borderwidth`` -- integer (default: None), the width of the border in pixels EXAMPLES: Here we plot a simple function of two variables:: sage: x,y = var('x,y') sage: region_plot(cos(x^2+y^2) <= 0, (x, -3, 3), (y, -3, 3)) Here we play with the colors:: sage: region_plot(x^2+y^3 < 2, (x, -2, 2), (y, -2, 2), incol='lightblue', bordercol='gray') An even more complicated plot, with dashed borders:: sage: region_plot(sin(x)*sin(y) >= 1/4, (x,-10,10), (y,-10,10), incol='yellow', bordercol='black', borderstyle='dashed', plot_points=250) A disk centered at the origin:: sage: region_plot(x^2+y^2<1, (x,-1,1), (y,-1,1), aspect_ratio=1) A plot with more than one condition (all conditions must be true for the statement to be true):: sage: region_plot([x^2+y^2<1, x<y], (x,-2,2), (y,-2,2), aspect_ratio=1) Since it doesn't look very good, let's increase plot_points:: sage: region_plot([x^2+y^2<1, x<y], (x,-2,2), (y,-2,2), plot_points=400, aspect_ratio=1) To get plots where only one condition needs to be true, use a function:: sage: region_plot(lambda x,y: x^2+y^2<1 or x<y, (x,-2,2), (y,-2,2), aspect_ratio=1) The first quadrant of the unit circle:: sage: region_plot([y>0, x>0, x^2+y^2<1], (x,-1.1, 1.1), (y,-1.1, 1.1), plot_points = 400, aspect_ratio=1) Here is another plot, with a huge border:: sage: region_plot(x*(x-1)*(x+1)+y^2<0, (x, -3, 2), (y, -3, 3), incol='lightblue', bordercol='gray', borderwidth=10, plot_points=50) If we want to keep only the region where x is positive:: sage: region_plot([x*(x-1)*(x+1)+y^2<0, x>-1], (x, -3, 2), (y, -3, 3), incol='lightblue', plot_points=50) Here we have a cut circle:: sage: region_plot([x^2+y^2<4, x>-1], (x, -2, 2), (y, -2, 2), incol='lightblue', bordercol='gray', plot_points=200, aspect_ratio=1) The first variable range corresponds to the horizontal axis and the second variable range corresponds to the vertical axis:: sage: s,t=var('s,t') sage: region_plot(s>0,(t,-2,2),(s,-2,2)) sage: region_plot(s>0,(s,-2,2),(t,-2,2)) """ from sage.plot.plot import Graphics from sage.plot.misc import setup_for_eval_on_grid import numpy if not isinstance(f, (list, tuple)): f = [f] f = [equify(g) for g in f] g, ranges = setup_for_eval_on_grid(f, [xrange, yrange], plot_points) xrange,yrange=[r[:2] for r in ranges] xy_data_arrays = numpy.asarray([[[func(x, y) for x in xsrange(*ranges[0], include_endpoint=True)] for y in xsrange(*ranges[1], include_endpoint=True)] for func in g],dtype=float) xy_data_array=numpy.abs(xy_data_arrays.prod(axis=0)) # Now we need to set entries to negative iff all # functions were negative at that point. neg_indices = (xy_data_arrays<0).all(axis=0) xy_data_array[neg_indices]=-xy_data_array[neg_indices] from matplotlib.colors import ListedColormap incol = rgbcolor(incol) outcol = rgbcolor(outcol) cmap = ListedColormap([incol, outcol]) cmap.set_over(outcol) cmap.set_under(incol) g = Graphics() g._set_extra_kwds(Graphics._extract_kwds_for_show(options, ignore=['xmin', 'xmax'])) g.add_primitive(ContourPlot(xy_data_array, xrange,yrange, dict(contours=[-1e307, 0, 1e307], cmap=cmap, fill=True, labels=False, **options))) if bordercol or borderstyle or borderwidth: cmap = [rgbcolor(bordercol)] if bordercol else ['black'] linestyles = [borderstyle] if borderstyle else None linewidths = [borderwidth] if borderwidth else None g.add_primitive(ContourPlot(xy_data_array, xrange, yrange, dict(linestyles=linestyles, linewidths=linewidths, contours=[0], cmap=[bordercol], fill=False, labels=False, **options))) return g
def region_plot(f, xrange, yrange, plot_points, incol, outcol, bordercol, borderstyle, borderwidth,**options): r""" ``region_plot`` takes a boolean function of two variables, `f(x,y)` and plots the region where f is True over the specified ``xrange`` and ``yrange`` as demonstrated below. ``region_plot(f, (xmin, xmax), (ymin, ymax), ...)`` INPUT: - ``f`` -- a boolean function of two variables - ``(xmin, xmax)`` -- 2-tuple, the range of ``x`` values OR 3-tuple ``(x,xmin,xmax)`` - ``(ymin, ymax)`` -- 2-tuple, the range of ``y`` values OR 3-tuple ``(y,ymin,ymax)`` - ``plot_points`` -- integer (default: 100); number of points to plot in each direction of the grid - ``incol`` -- a color (default: ``'blue'``), the color inside the region - ``outcol`` -- a color (default: ``'white'``), the color of the outside of the region If any of these options are specified, the border will be shown as indicated, otherwise it is only implicit (with color ``incol``) as the border of the inside of the region. - ``bordercol`` -- a color (default: ``None``), the color of the border (``'black'`` if ``borderwidth`` or ``borderstyle`` is specified but not ``bordercol``) - ``borderstyle`` -- string (default: 'solid'), one of 'solid', 'dashed', 'dotted', 'dashdot' - ``borderwidth`` -- integer (default: None), the width of the border in pixels EXAMPLES: Here we plot a simple function of two variables:: sage: x,y = var('x,y') sage: region_plot(cos(x^2+y^2) <= 0, (x, -3, 3), (y, -3, 3)) Here we play with the colors:: sage: region_plot(x^2+y^3 < 2, (x, -2, 2), (y, -2, 2), incol='lightblue', bordercol='gray') An even more complicated plot, with dashed borders:: sage: region_plot(sin(x)*sin(y) >= 1/4, (x,-10,10), (y,-10,10), incol='yellow', bordercol='black', borderstyle='dashed', plot_points=250) A disk centered at the origin:: sage: region_plot(x^2+y^2<1, (x,-1,1), (y,-1,1), aspect_ratio=1) A plot with more than one condition (all conditions must be true for the statement to be true):: sage: region_plot([x^2+y^2<1, x<y], (x,-2,2), (y,-2,2), aspect_ratio=1) Since it doesn't look very good, let's increase plot_points:: sage: region_plot([x^2+y^2<1, x<y], (x,-2,2), (y,-2,2), plot_points=400, aspect_ratio=1) To get plots where only one condition needs to be true, use a function:: sage: region_plot(lambda x,y: x^2+y^2<1 or x<y, (x,-2,2), (y,-2,2), aspect_ratio=1) The first quadrant of the unit circle:: sage: region_plot([y>0, x>0, x^2+y^2<1], (x,-1.1, 1.1), (y,-1.1, 1.1), plot_points = 400, aspect_ratio=1) Here is another plot, with a huge border:: sage: region_plot(x*(x-1)*(x+1)+y^2<0, (x, -3, 2), (y, -3, 3), incol='lightblue', bordercol='gray', borderwidth=10, plot_points=50) If we want to keep only the region where x is positive:: sage: region_plot([x*(x-1)*(x+1)+y^2<0, x>-1], (x, -3, 2), (y, -3, 3), incol='lightblue', plot_points=50) Here we have a cut circle:: sage: region_plot([x^2+y^2<4, x>-1], (x, -2, 2), (y, -2, 2), incol='lightblue', bordercol='gray', plot_points=200, aspect_ratio=1) The first variable range corresponds to the horizontal axis and the second variable range corresponds to the vertical axis:: sage: s,t=var('s,t') sage: region_plot(s>0,(t,-2,2),(s,-2,2)) sage: region_plot(s>0,(s,-2,2),(t,-2,2)) """ from sage.plot.plot import Graphics from sage.plot.misc import setup_for_eval_on_grid import numpy if not isinstance(f, (list, tuple)): f = [f] f = [equify(g) for g in f] g, ranges = setup_for_eval_on_grid(f, [xrange, yrange], plot_points) xrange,yrange=[r[:2] for r in ranges] xy_data_arrays = numpy.asarray([[[func(x, y) for x in xsrange(*ranges[0], include_endpoint=True)] for y in xsrange(*ranges[1], include_endpoint=True)] for func in g],dtype=float) xy_data_array=numpy.abs(xy_data_arrays.prod(axis=0)) # Now we need to set entries to negative iff all # functions were negative at that point. neg_indices = (xy_data_arrays<0).all(axis=0) xy_data_array[neg_indices]=-xy_data_array[neg_indices] from matplotlib.colors import ListedColormap incol = rgbcolor(incol) outcol = rgbcolor(outcol) cmap = ListedColormap([incol, outcol]) cmap.set_over(outcol) cmap.set_under(incol) g = Graphics() g._set_extra_kwds(Graphics._extract_kwds_for_show(options, ignore=['xmin', 'xmax'])) g.add_primitive(ContourPlot(xy_data_array, xrange,yrange, dict(contours=[-1e307, 0, 1e307], cmap=cmap, fill=True, labels=False, **options))) if bordercol or borderstyle or borderwidth: cmap = [rgbcolor(bordercol)] if bordercol else ['black'] linestyles = [borderstyle] if borderstyle else None linewidths = [borderwidth] if borderwidth else None g.add_primitive(ContourPlot(xy_data_array, xrange, yrange, dict(linestyles=linestyles, linewidths=linewidths, contours=[0], cmap=[bordercol], fill=False, **options))) return g
472,424
def Set(X): r""" Create the underlying set of $X$. If $X$ is a list, tuple, Python set, or ``X.is_finite()`` is true, this returns a wrapper around Python's enumerated immutable frozenset type with extra functionality. Otherwise it returns a more formal wrapper. If you need the functionality of mutable sets, use Python's builtin set type. EXAMPLES:: sage: X = Set(GF(9,'a')) sage: X {0, 1, 2, a, a + 1, a + 2, 2*a, 2*a + 1, 2*a + 2} sage: type(X) <class 'sage.sets.set.Set_object_enumerated'> sage: Y = X.union(Set(QQ)) sage: Y Set-theoretic union of {0, 1, 2, a, a + 1, a + 2, 2*a, 2*a + 1, 2*a + 2} and Set of elements of Rational Field sage: type(Y) <class 'sage.sets.set.Set_object_union'> Usually sets can be used as dictionary keys. :: sage: d={Set([2*I,1+I]):10} sage: d # key is randomly ordered {{I + 1, 2*I}: 10} sage: d[Set([1+I,2*I])] 10 sage: d[Set((1+I,2*I))] 10 The original object is often forgotten. :: sage: v = [1,2,3] sage: X = Set(v) sage: X {1, 2, 3} sage: v.append(5) sage: X {1, 2, 3} sage: 5 in X False Set also accepts iterators, but be careful to only give *finite* sets. :: sage: list(Set(iter([1, 2, 3, 4, 5]))) [1, 2, 3, 4, 5] TESTS:: sage: Set(Primes()) Set of all prime numbers: 2, 3, 5, 7, ... sage: Set(Subsets([1,2,3])).cardinality() 8 """ if is_Set(X): return X if isinstance(X, Element): raise TypeError, "Element has no defined underlying set" elif isinstance(X, (list, tuple, set, frozenset)): return Set_object_enumerated(frozenset(X)) try: if X.is_finite(): return Set_object_enumerated(X) except AttributeError: pass if is_iterator(X): # Note we are risking an infinite loop here, # but this is the way Python behaves too: try # sage: set(an iterator which does not terminate) X = list(X) return Set_object(X)
def Set(X): r""" Create the underlying set of $X$. If $X$ is a list, tuple, Python set, or ``X.is_finite()`` is true, this returns a wrapper around Python's enumerated immutable frozenset type with extra functionality. Otherwise it returns a more formal wrapper. If you need the functionality of mutable sets, use Python's builtin set type. EXAMPLES:: sage: X = Set(GF(9,'a')) sage: X {0, 1, 2, a, a + 1, a + 2, 2*a, 2*a + 1, 2*a + 2} sage: type(X) <class 'sage.sets.set.Set_object_enumerated'> sage: Y = X.union(Set(QQ)) sage: Y Set-theoretic union of {0, 1, 2, a, a + 1, a + 2, 2*a, 2*a + 1, 2*a + 2} and Set of elements of Rational Field sage: type(Y) <class 'sage.sets.set.Set_object_union'> Usually sets can be used as dictionary keys. :: sage: d={Set([2*I,1+I]):10} sage: d # key is randomly ordered {{I + 1, 2*I}: 10} sage: d[Set([1+I,2*I])] 10 sage: d[Set((1+I,2*I))] 10 The original object is often forgotten. :: sage: v = [1,2,3] sage: X = Set(v) sage: X {1, 2, 3} sage: v.append(5) sage: X {1, 2, 3} sage: 5 in X False Set also accepts iterators, but be careful to only give *finite* sets. :: sage: list(Set(iter([1, 2, 3, 4, 5]))) [1, 2, 3, 4, 5] TESTS:: sage: Set(Primes()) Set of all prime numbers: 2, 3, 5, 7, ... sage: Set(Subsets([1,2,3])).cardinality() 8 """ if is_Set(X): return X if isinstance(X, Element): raise TypeError, "Element has no defined underlying set" elif isinstance(X, (list, tuple, set, frozenset)): return Set_object_enumerated(frozenset(X)) try: if X.is_finite(): return Set_object_enumerated(X) except AttributeError: pass if is_iterator(X): # Note we are risking an infinite loop here, # but this is the way Python behaves too: try # sage: set(an iterator which does not terminate) return Set_object_enumerated(list(X)) return Set_object(X)
472,425
def __init__(self, x, y, r1, r2, angle, options): """ Initializes base class Ellipse.
def __init__(self, x, y, r1, r2, angle, options): """ Initializes base class Ellipse.
472,426
def get_minmax_data(self): """ Returns a dictionary with the bounding box data.
def get_minmax_data(self): """ Returns a dictionary with the bounding box data.
472,427
def get_minmax_data(self): """ Returns a dictionary with the bounding box data.
def get_minmax_data(self): """ Returns a dictionary with the bounding box data.
472,428
def get_minmax_data(self): """ Returns a dictionary with the bounding box data.
def get_minmax_data(self): """ Returns a dictionary with the bounding box data.
472,429
def _allowed_options(self): """ Return the allowed options for the Ellipse class.
def _allowed_options(self): """ Return the allowed options for the Ellipse class.
472,430
def _repr_(self): """ String representation of Ellipse primitive.
def _repr_(self): """ String representation of Ellipse primitive.
472,431
def plot3d(self): r""" Plot 3d is not implemented.
def plot3d(self): r""" Plot 3d is not implemented.
472,432
def NumberField(polynomial, name=None, check=True, names=None, cache=True, embedding=None, latex_name=None): r""" Return *the* number field defined by the given irreducible polynomial and with variable with the given name. If check is True (the default), also verify that the defining polynomial is irreducible and over `\QQ`. INPUT: - ``polynomial`` - a polynomial over `\QQ` or a number field, or a list of polynomials. - ``name`` - a string (default: 'a'), the name of the generator - ``check`` - bool (default: True); do type checking and irreducibility checking. - ``embedding`` - image of the generator in an ambient field (default: None) EXAMPLES:: sage: z = QQ['z'].0 sage: K = NumberField(z^2 - 2,'s'); K Number Field in s with defining polynomial z^2 - 2 sage: s = K.0; s s sage: s*s 2 sage: s^2 2 Constructing a relative number field:: sage: K.<a> = NumberField(x^2 - 2) sage: R.<t> = K[] sage: L.<b> = K.extension(t^3+t+a); L Number Field in b with defining polynomial t^3 + t + a over its base field sage: L.absolute_field('c') Number Field in c with defining polynomial x^6 + 2*x^4 + x^2 - 2 sage: a*b a*b sage: L(a) a sage: L.lift_to_base(b^3 + b) -a Constructing another number field:: sage: k.<i> = NumberField(x^2 + 1) sage: R.<z> = k[] sage: m.<j> = NumberField(z^3 + i*z + 3) sage: m Number Field in j with defining polynomial z^3 + i*z + 3 over its base field Number fields are globally unique:: sage: K.<a>= NumberField(x^3-5) sage: a^3 5 sage: L.<a>= NumberField(x^3-5) sage: K is L True Having different defining polynomials makes the fields different:: sage: x = polygen(QQ, 'x'); y = polygen(QQ, 'y') sage: k.<a> = NumberField(x^2 + 3) sage: m.<a> = NumberField(y^2 + 3) sage: k Number Field in a with defining polynomial x^2 + 3 sage: m Number Field in a with defining polynomial y^2 + 3 One can also define number fields with specified embeddings, may be used for arithmetic and deduce relations with other number fields which would not be valid for an abstract number field:: sage: K.<a> = NumberField(x^3-2, embedding=1.2) sage: RR.coerce_map_from(K) Composite map: From: Number Field in a with defining polynomial x^3 - 2 To: Real Field with 53 bits of precision Defn: Generic morphism: From: Number Field in a with defining polynomial x^3 - 2 To: Real Lazy Field Defn: a -> 1.259921049894873? then Conversion via _mpfr_ method map: From: Real Lazy Field To: Real Field with 53 bits of precision sage: RR(a) 1.25992104989487 sage: 1.1 + a 2.35992104989487 sage: b = 1/(a+1); b 1/3*a^2 - 1/3*a + 1/3 sage: RR(b) 0.442493334024442 sage: L.<b> = NumberField(x^6-2, embedding=1.1) sage: L(a) b^2 sage: a + b b^2 + b Note that the image only needs to be specified to enough precision to distinguish roots, and is exactly computed to any needed precision:: sage: RealField(200)(a) 1.2599210498948731647672106072782283505702514647015079800820 One can embed into any other field:: sage: K.<a> = NumberField(x^3-2, embedding=CC.gen()-0.6) sage: CC(a) -0.629960524947436 + 1.09112363597172*I sage: L = Qp(5) sage: f = polygen(L)^3 - 2 sage: K.<a> = NumberField(x^3-2, embedding=f.roots()[0][0]) sage: a + L(1) 4 + 2*5^2 + 2*5^3 + 3*5^4 + 5^5 + 4*5^6 + 2*5^8 + 3*5^9 + 4*5^12 + 4*5^14 + 4*5^15 + 3*5^16 + 5^17 + 5^18 + 2*5^19 + O(5^20) sage: L.<b> = NumberField(x^6-x^2+1/10, embedding=1) sage: K.<a> = NumberField(x^3-x+1/10, embedding=b^2) sage: a+b b^2 + b sage: CC(a) == CC(b)^2 True sage: K.coerce_embedding() Generic morphism: From: Number Field in a with defining polynomial x^3 - x + 1/10 To: Number Field in b with defining polynomial x^6 - x^2 + 1/10 Defn: a -> b^2 The ``QuadraticField`` and ``CyclotomicField`` constructors create an embedding by default unless otherwise specified. :: sage: K.<zeta> = CyclotomicField(15) sage: CC(zeta) 0.913545457642601 + 0.406736643075800*I sage: L.<sqrtn3> = QuadraticField(-3) sage: K(sqrtn3) 2*zeta^5 + 1 sage: sqrtn3 + zeta 2*zeta^5 + zeta + 1 An example involving a variable name that defines a function in PARI:: sage: theta = polygen(QQ, 'theta') sage: M.<z> = NumberField([theta^3 + 4, theta^2 + 3]); M Number Field in z0 with defining polynomial theta^3 + 4 over its base field TESTS:: sage: x = QQ['x'].gen() sage: y = ZZ['y'].gen() sage: K = NumberField(x^3 + x + 3, 'a'); K Number Field in a with defining polynomial x^3 + x + 3 sage: K.defining_polynomial().parent() Univariate Polynomial Ring in x over Rational Field :: sage: L = NumberField(y^3 + y + 3, 'a'); L Number Field in a with defining polynomial y^3 + y + 3 sage: L.defining_polynomial().parent() Univariate Polynomial Ring in y over Rational Field :: sage: sage.rings.number_field.number_field._nf_cache = {} sage: K.<x> = CyclotomicField(5)[] sage: W.<a> = NumberField(x^2 + 1); W Number Field in a with defining polynomial x^2 + 1 over its base field sage: sage.rings.number_field.number_field._nf_cache = {} sage: W1 = NumberField(x^2+1,'a') sage: K.<x> = CyclotomicField(5)[] sage: W.<a> = NumberField(x^2 + 1); W Number Field in a with defining polynomial x^2 + 1 over its base field """ if name is None and names is None: raise TypeError, "You must specify the name of the generator." if not names is None: name = names if isinstance(polynomial, (list, tuple)): return NumberFieldTower(polynomial, name) name = sage.structure.parent_gens.normalize_names(1, name) if not isinstance(polynomial, polynomial_element.Polynomial): try: polynomial = polynomial.polynomial(QQ) except (AttributeError, TypeError): raise TypeError, "polynomial (=%s) must be a polynomial."%repr(polynomial) # convert ZZ to QQ R = polynomial.base_ring() Q = polynomial.parent().base_extend(R.fraction_field()) polynomial = Q(polynomial) if cache: key = (polynomial, polynomial.base_ring(), name, embedding, embedding.parent() if embedding is not None else None) if _nf_cache.has_key(key): K = _nf_cache[key]() if not K is None: return K if isinstance(R, NumberField_generic): S = R.extension(polynomial, name, check=check) if cache: _nf_cache[key] = weakref.ref(S) return S if polynomial.degree() == 2: K = NumberField_quadratic(polynomial, name, latex_name, check, embedding) else: K = NumberField_absolute(polynomial, name, latex_name, check, embedding) if cache: _nf_cache[key] = weakref.ref(K) return K
def NumberField(polynomial, name=None, check=True, names=None, cache=True, embedding=None, latex_name=None): r""" Return *the* number field defined by the given irreducible polynomial and with variable with the given name. If check is True (the default), also verify that the defining polynomial is irreducible and over `\QQ`. INPUT: - ``polynomial`` - a polynomial over `\QQ` or a number field, or a list of polynomials. - ``name`` - a string (default: 'a'), the name of the generator - ``check`` - bool (default: True); do type checking and irreducibility checking. - ``embedding`` - image of the generator in an ambient field (default: None) EXAMPLES:: sage: z = QQ['z'].0 sage: K = NumberField(z^2 - 2,'s'); K Number Field in s with defining polynomial z^2 - 2 sage: s = K.0; s s sage: s*s 2 sage: s^2 2 Constructing a relative number field:: sage: K.<a> = NumberField(x^2 - 2) sage: R.<t> = K[] sage: L.<b> = K.extension(t^3+t+a); L Number Field in b with defining polynomial t^3 + t + a over its base field sage: L.absolute_field('c') Number Field in c with defining polynomial x^6 + 2*x^4 + x^2 - 2 sage: a*b a*b sage: L(a) a sage: L.lift_to_base(b^3 + b) -a Constructing another number field:: sage: k.<i> = NumberField(x^2 + 1) sage: R.<z> = k[] sage: m.<j> = NumberField(z^3 + i*z + 3) sage: m Number Field in j with defining polynomial z^3 + i*z + 3 over its base field Number fields are globally unique:: sage: K.<a>= NumberField(x^3-5) sage: a^3 5 sage: L.<a>= NumberField(x^3-5) sage: K is L True Having different defining polynomials makes the fields different:: sage: x = polygen(QQ, 'x'); y = polygen(QQ, 'y') sage: k.<a> = NumberField(x^2 + 3) sage: m.<a> = NumberField(y^2 + 3) sage: k Number Field in a with defining polynomial x^2 + 3 sage: m Number Field in a with defining polynomial y^2 + 3 One can also define number fields with specified embeddings, may be used for arithmetic and deduce relations with other number fields which would not be valid for an abstract number field:: sage: K.<a> = NumberField(x^3-2, embedding=1.2) sage: RR.coerce_map_from(K) Composite map: From: Number Field in a with defining polynomial x^3 - 2 To: Real Field with 53 bits of precision Defn: Generic morphism: From: Number Field in a with defining polynomial x^3 - 2 To: Real Lazy Field Defn: a -> 1.259921049894873? then Conversion via _mpfr_ method map: From: Real Lazy Field To: Real Field with 53 bits of precision sage: RR(a) 1.25992104989487 sage: 1.1 + a 2.35992104989487 sage: b = 1/(a+1); b 1/3*a^2 - 1/3*a + 1/3 sage: RR(b) 0.442493334024442 sage: L.<b> = NumberField(x^6-2, embedding=1.1) sage: L(a) b^2 sage: a + b b^2 + b Note that the image only needs to be specified to enough precision to distinguish roots, and is exactly computed to any needed precision:: sage: RealField(200)(a) 1.2599210498948731647672106072782283505702514647015079800820 One can embed into any other field:: sage: K.<a> = NumberField(x^3-2, embedding=CC.gen()-0.6) sage: CC(a) -0.629960524947436 + 1.09112363597172*I sage: L = Qp(5) sage: f = polygen(L)^3 - 2 sage: K.<a> = NumberField(x^3-2, embedding=f.roots()[0][0]) sage: a + L(1) 4 + 2*5^2 + 2*5^3 + 3*5^4 + 5^5 + 4*5^6 + 2*5^8 + 3*5^9 + 4*5^12 + 4*5^14 + 4*5^15 + 3*5^16 + 5^17 + 5^18 + 2*5^19 + O(5^20) sage: L.<b> = NumberField(x^6-x^2+1/10, embedding=1) sage: K.<a> = NumberField(x^3-x+1/10, embedding=b^2) sage: a+b b^2 + b sage: CC(a) == CC(b)^2 True sage: K.coerce_embedding() Generic morphism: From: Number Field in a with defining polynomial x^3 - x + 1/10 To: Number Field in b with defining polynomial x^6 - x^2 + 1/10 Defn: a -> b^2 The ``QuadraticField`` and ``CyclotomicField`` constructors create an embedding by default unless otherwise specified. :: sage: K.<zeta> = CyclotomicField(15) sage: CC(zeta) 0.913545457642601 + 0.406736643075800*I sage: L.<sqrtn3> = QuadraticField(-3) sage: K(sqrtn3) 2*zeta^5 + 1 sage: sqrtn3 + zeta 2*zeta^5 + zeta + 1 An example involving a variable name that defines a function in PARI:: sage: theta = polygen(QQ, 'theta') sage: M.<z> = NumberField([theta^3 + 4, theta^2 + 3]); M Number Field in z0 with defining polynomial theta^3 + 4 over its base field TESTS:: sage: x = QQ['x'].gen() sage: y = ZZ['y'].gen() sage: K = NumberField(x^3 + x + 3, 'a'); K Number Field in a with defining polynomial x^3 + x + 3 sage: K.defining_polynomial().parent() Univariate Polynomial Ring in x over Rational Field :: sage: L = NumberField(y^3 + y + 3, 'a'); L Number Field in a with defining polynomial y^3 + y + 3 sage: L.defining_polynomial().parent() Univariate Polynomial Ring in y over Rational Field :: sage: sage.rings.number_field.number_field._nf_cache = {} sage: K.<x> = CyclotomicField(5)[] sage: W.<a> = NumberField(x^2 + 1); W Number Field in a with defining polynomial x^2 + 1 over its base field sage: sage.rings.number_field.number_field._nf_cache = {} sage: W1 = NumberField(x^2+1,'a') sage: K.<x> = CyclotomicField(5)[] sage: W.<a> = NumberField(x^2 + 1); W Number Field in a with defining polynomial x^2 + 1 over its base field """ if name is None and names is None: raise TypeError, "You must specify the name of the generator." if not names is None: name = names if isinstance(polynomial, (list, tuple)): return NumberFieldTower(polynomial, name) name = sage.structure.parent_gens.normalize_names(1, name) if not isinstance(polynomial, polynomial_element.Polynomial): try: polynomial = polynomial.polynomial(QQ) except (AttributeError, TypeError): raise TypeError, "polynomial (=%s) must be a polynomial."%repr(polynomial) # convert ZZ to QQ R = polynomial.base_ring() Q = polynomial.parent().base_extend(R.fraction_field()) polynomial = Q(polynomial) if cache: key = (polynomial, polynomial.base_ring(), name, latex_name, embedding, embedding.parent() if embedding is not None else None) if _nf_cache.has_key(key): K = _nf_cache[key]() if not K is None: return K if isinstance(R, NumberField_generic): S = R.extension(polynomial, name, check=check) if cache: _nf_cache[key] = weakref.ref(S) return S if polynomial.degree() == 2: K = NumberField_quadratic(polynomial, name, latex_name, check, embedding) else: K = NumberField_absolute(polynomial, name, latex_name, check, embedding) if cache: _nf_cache[key] = weakref.ref(K) return K
472,433
def QuadraticField(D, names, check=True, embedding=True, latex_name=None): r""" Return a quadratic field obtained by adjoining a square root of `D` to the rational numbers, where `D` is not a perfect square. INPUT: - ``D`` - a rational number - ``names`` - variable name - ``check`` - bool (default: True) - ``embedding`` - bool or square root of D in an ambient field (default: True) OUTPUT: A number field defined by a quadratic polynomial. Unless otherwise specified, it has an embedding into `\RR` or `\CC` by sending the generator to the positive root. EXAMPLES:: sage: QuadraticField(3, 'a') Number Field in a with defining polynomial x^2 - 3 sage: K.<theta> = QuadraticField(3); K Number Field in theta with defining polynomial x^2 - 3 sage: RR(theta) 1.73205080756888 sage: QuadraticField(9, 'a') Traceback (most recent call last): ... ValueError: D must not be a perfect square. sage: QuadraticField(9, 'a', check=False) Number Field in a with defining polynomial x^2 - 9 Quadratic number fields derive from general number fields. :: sage: from sage.rings.number_field.number_field import is_NumberField sage: type(K) <class 'sage.rings.number_field.number_field.NumberField_quadratic_with_category'> sage: is_NumberField(K) True Quadratic number fields are cached:: sage: QuadraticField(-11, 'a') is QuadraticField(-11, 'a') True We can give the generator a special name for latex:: sage: K.<a> = QuadraticField(next_prime(10^10), latex_name=r'\sqrt{D}') sage: 1+a a + 1 sage: latex(1+a) \sqrt{D} + 1 """ D = QQ(D) if check: if D.is_square(): raise ValueError, "D must not be a perfect square." R = QQ['x'] f = R([-D, 0, 1]) if embedding is True: if D > 0: embedding = RLF(D).sqrt() else: embedding = CLF(D).sqrt() return NumberField(f, names, check=False, embedding=embedding, latex_name=latex_name)
def QuadraticField(D, names, check=True, embedding=True, latex_name='sqrt'): r""" Return a quadratic field obtained by adjoining a square root of `D` to the rational numbers, where `D` is not a perfect square. INPUT: - ``D`` - a rational number - ``names`` - variable name - ``check`` - bool (default: True) - ``embedding`` - bool or square root of D in an ambient field (default: True) OUTPUT: A number field defined by a quadratic polynomial. Unless otherwise specified, it has an embedding into `\RR` or `\CC` by sending the generator to the positive root. EXAMPLES:: sage: QuadraticField(3, 'a') Number Field in a with defining polynomial x^2 - 3 sage: K.<theta> = QuadraticField(3); K Number Field in theta with defining polynomial x^2 - 3 sage: RR(theta) 1.73205080756888 sage: QuadraticField(9, 'a') Traceback (most recent call last): ... ValueError: D must not be a perfect square. sage: QuadraticField(9, 'a', check=False) Number Field in a with defining polynomial x^2 - 9 Quadratic number fields derive from general number fields. :: sage: from sage.rings.number_field.number_field import is_NumberField sage: type(K) <class 'sage.rings.number_field.number_field.NumberField_quadratic_with_category'> sage: is_NumberField(K) True Quadratic number fields are cached:: sage: QuadraticField(-11, 'a') is QuadraticField(-11, 'a') True We can give the generator a special name for latex:: sage: K.<a> = QuadraticField(next_prime(10^10), latex_name=r'\sqrt{D}') sage: 1+a a + 1 sage: latex(1+a) \sqrt{D} + 1 """ D = QQ(D) if check: if D.is_square(): raise ValueError, "D must not be a perfect square." R = QQ['x'] f = R([-D, 0, 1]) if embedding is True: if D > 0: embedding = RLF(D).sqrt() else: embedding = CLF(D).sqrt() return NumberField(f, names, check=False, embedding=embedding, latex_name=latex_name)
472,434
def QuadraticField(D, names, check=True, embedding=True, latex_name=None): r""" Return a quadratic field obtained by adjoining a square root of `D` to the rational numbers, where `D` is not a perfect square. INPUT: - ``D`` - a rational number - ``names`` - variable name - ``check`` - bool (default: True) - ``embedding`` - bool or square root of D in an ambient field (default: True) OUTPUT: A number field defined by a quadratic polynomial. Unless otherwise specified, it has an embedding into `\RR` or `\CC` by sending the generator to the positive root. EXAMPLES:: sage: QuadraticField(3, 'a') Number Field in a with defining polynomial x^2 - 3 sage: K.<theta> = QuadraticField(3); K Number Field in theta with defining polynomial x^2 - 3 sage: RR(theta) 1.73205080756888 sage: QuadraticField(9, 'a') Traceback (most recent call last): ... ValueError: D must not be a perfect square. sage: QuadraticField(9, 'a', check=False) Number Field in a with defining polynomial x^2 - 9 Quadratic number fields derive from general number fields. :: sage: from sage.rings.number_field.number_field import is_NumberField sage: type(K) <class 'sage.rings.number_field.number_field.NumberField_quadratic_with_category'> sage: is_NumberField(K) True Quadratic number fields are cached:: sage: QuadraticField(-11, 'a') is QuadraticField(-11, 'a') True We can give the generator a special name for latex:: sage: K.<a> = QuadraticField(next_prime(10^10), latex_name=r'\sqrt{D}') sage: 1+a a + 1 sage: latex(1+a) \sqrt{D} + 1 """ D = QQ(D) if check: if D.is_square(): raise ValueError, "D must not be a perfect square." R = QQ['x'] f = R([-D, 0, 1]) if embedding is True: if D > 0: embedding = RLF(D).sqrt() else: embedding = CLF(D).sqrt() return NumberField(f, names, check=False, embedding=embedding, latex_name=latex_name)
def QuadraticField(D, names, check=True, embedding=True, latex_name=None): r""" Return a quadratic field obtained by adjoining a square root of `D` to the rational numbers, where `D` is not a perfect square. INPUT: - ``D`` - a rational number - ``names`` - variable name - ``check`` - bool (default: True) - ``embedding`` - bool or square root of D in an ambient field (default: True) OUTPUT: A number field defined by a quadratic polynomial. Unless otherwise specified, it has an embedding into `\RR` or `\CC` by sending the generator to the positive or upper half plane root. EXAMPLES:: sage: QuadraticField(3, 'a') Number Field in a with defining polynomial x^2 - 3 sage: K.<theta> = QuadraticField(3); K Number Field in theta with defining polynomial x^2 - 3 sage: RR(theta) 1.73205080756888 sage: QuadraticField(9, 'a') Traceback (most recent call last): ... ValueError: D must not be a perfect square. sage: QuadraticField(9, 'a', check=False) Number Field in a with defining polynomial x^2 - 9 Quadratic number fields derive from general number fields. :: sage: from sage.rings.number_field.number_field import is_NumberField sage: type(K) <class 'sage.rings.number_field.number_field.NumberField_quadratic_with_category'> sage: is_NumberField(K) True Quadratic number fields are cached:: sage: QuadraticField(-11, 'a') is QuadraticField(-11, 'a') True We can give the generator a special name for latex:: sage: K.<a> = QuadraticField(next_prime(10^10), latex_name=r'\sqrt{D}') sage: 1+a a + 1 sage: latex(1+a) \sqrt{D} + 1 """ D = QQ(D) if check: if D.is_square(): raise ValueError, "D must not be a perfect square." R = QQ['x'] f = R([-D, 0, 1]) if embedding is True: if D > 0: embedding = RLF(D).sqrt() else: embedding = CLF(D).sqrt() return NumberField(f, names, check=False, embedding=embedding, latex_name=latex_name)
472,435
def QuadraticField(D, names, check=True, embedding=True, latex_name=None): r""" Return a quadratic field obtained by adjoining a square root of `D` to the rational numbers, where `D` is not a perfect square. INPUT: - ``D`` - a rational number - ``names`` - variable name - ``check`` - bool (default: True) - ``embedding`` - bool or square root of D in an ambient field (default: True) OUTPUT: A number field defined by a quadratic polynomial. Unless otherwise specified, it has an embedding into `\RR` or `\CC` by sending the generator to the positive root. EXAMPLES:: sage: QuadraticField(3, 'a') Number Field in a with defining polynomial x^2 - 3 sage: K.<theta> = QuadraticField(3); K Number Field in theta with defining polynomial x^2 - 3 sage: RR(theta) 1.73205080756888 sage: QuadraticField(9, 'a') Traceback (most recent call last): ... ValueError: D must not be a perfect square. sage: QuadraticField(9, 'a', check=False) Number Field in a with defining polynomial x^2 - 9 Quadratic number fields derive from general number fields. :: sage: from sage.rings.number_field.number_field import is_NumberField sage: type(K) <class 'sage.rings.number_field.number_field.NumberField_quadratic_with_category'> sage: is_NumberField(K) True Quadratic number fields are cached:: sage: QuadraticField(-11, 'a') is QuadraticField(-11, 'a') True We can give the generator a special name for latex:: sage: K.<a> = QuadraticField(next_prime(10^10), latex_name=r'\sqrt{D}') sage: 1+a a + 1 sage: latex(1+a) \sqrt{D} + 1 """ D = QQ(D) if check: if D.is_square(): raise ValueError, "D must not be a perfect square." R = QQ['x'] f = R([-D, 0, 1]) if embedding is True: if D > 0: embedding = RLF(D).sqrt() else: embedding = CLF(D).sqrt() return NumberField(f, names, check=False, embedding=embedding, latex_name=latex_name)
def QuadraticField(D, names, check=True, embedding=True, latex_name=None): r""" Return a quadratic field obtained by adjoining a square root of `D` to the rational numbers, where `D` is not a perfect square. INPUT: - ``D`` - a rational number - ``names`` - variable name - ``check`` - bool (default: True) - ``embedding`` - bool or square root of D in an ambient field (default: True) OUTPUT: A number field defined by a quadratic polynomial. Unless otherwise specified, it has an embedding into `\RR` or `\CC` by sending the generator to the positive root. EXAMPLES:: sage: QuadraticField(3, 'a') Number Field in a with defining polynomial x^2 - 3 sage: K.<theta> = QuadraticField(3); K Number Field in theta with defining polynomial x^2 - 3 sage: RR(theta) 1.73205080756888 sage: QuadraticField(9, 'a') Traceback (most recent call last): ... ValueError: D must not be a perfect square. sage: QuadraticField(9, 'a', check=False) Number Field in a with defining polynomial x^2 - 9 Quadratic number fields derive from general number fields. :: sage: from sage.rings.number_field.number_field import is_NumberField sage: type(K) <class 'sage.rings.number_field.number_field.NumberField_quadratic_with_category'> sage: is_NumberField(K) True Quadratic number fields are cached:: sage: QuadraticField(-11, 'a') is QuadraticField(-11, 'a') True By default, quadratic fields come with a nice latex representation:: sage: K.<a> = QuadraticField(-7) sage: latex(a) \sqrt{-7} sage: latex(1/(1+a)) -\frac{1}{8} \sqrt{-7} + \frac{1}{8} sage: K.latex_variable_name() '\\sqrt{-7}' We can provide our own name as well:: sage: K.<a> = QuadraticField(next_prime(10^10), latex_name=r'\sqrt{D}') sage: 1+a a + 1 sage: latex(1+a) \sqrt{D} + 1 """ D = QQ(D) if check: if D.is_square(): raise ValueError, "D must not be a perfect square." R = QQ['x'] f = R([-D, 0, 1]) if embedding is True: if D > 0: embedding = RLF(D).sqrt() else: embedding = CLF(D).sqrt() return NumberField(f, names, check=False, embedding=embedding, latex_name=latex_name)
472,436
def tamagawa_product(self): r""" Given an elliptic curve `E` over a number field `K`, this function returns the integer `C(E/K)` that appears in the Birch and Swinnerton-Dyer conjecture accounting for the local information at finite places. If the model is a global minimal model then `C(E/K)` is simply the product of the Tamagawa numbers `c_v` where `v` runs over all prime ideals of `K`. Otherwise, if the model has to be changed at a place `v` a correction factor appears. The definition is such that `C(E/K)` times the periods at the infinite places is invariant under change of the Weierstrass model. See [Ta2] and [Do] for details.
def tamagawa_product_bsd(self): r""" Given an elliptic curve `E` over a number field `K`, this function returns the integer `C(E/K)` that appears in the Birch and Swinnerton-Dyer conjecture accounting for the local information at finite places. If the model is a global minimal model then `C(E/K)` is simply the product of the Tamagawa numbers `c_v` where `v` runs over all prime ideals of `K`. Otherwise, if the model has to be changed at a place `v` a correction factor appears. The definition is such that `C(E/K)` times the periods at the infinite places is invariant under change of the Weierstrass model. See [Ta2] and [Do] for details.
472,437
def tamagawa_product(self): r""" Given an elliptic curve `E` over a number field `K`, this function returns the integer `C(E/K)` that appears in the Birch and Swinnerton-Dyer conjecture accounting for the local information at finite places. If the model is a global minimal model then `C(E/K)` is simply the product of the Tamagawa numbers `c_v` where `v` runs over all prime ideals of `K`. Otherwise, if the model has to be changed at a place `v` a correction factor appears. The definition is such that `C(E/K)` times the periods at the infinite places is invariant under change of the Weierstrass model. See [Ta2] and [Do] for details.
def tamagawa_product(self): r""" Given an elliptic curve `E` over a number field `K`, this function returns the integer `C(E/K)` that appears in the Birch and Swinnerton-Dyer conjecture accounting for the local information at finite places. If the model is a global minimal model then `C(E/K)` is simply the product of the Tamagawa numbers `c_v` where `v` runs over all prime ideals of `K`. Otherwise, if the model has to be changed at a place `v` a correction factor appears. The definition is such that `C(E/K)` times the periods at the infinite places is invariant under change of the Weierstrass model. See [Ta2] and [Do] for details.
472,438
def tamagawa_product(self): r""" Given an elliptic curve `E` over a number field `K`, this function returns the integer `C(E/K)` that appears in the Birch and Swinnerton-Dyer conjecture accounting for the local information at finite places. If the model is a global minimal model then `C(E/K)` is simply the product of the Tamagawa numbers `c_v` where `v` runs over all prime ideals of `K`. Otherwise, if the model has to be changed at a place `v` a correction factor appears. The definition is such that `C(E/K)` times the periods at the infinite places is invariant under change of the Weierstrass model. See [Ta2] and [Do] for details.
def tamagawa_product(self): r""" Given an elliptic curve `E` over a number field `K`, this function returns the integer `C(E/K)` that appears in the Birch and Swinnerton-Dyer conjecture accounting for the local information at finite places. If the model is a global minimal model then `C(E/K)` is simply the product of the Tamagawa numbers `c_v` where `v` runs over all prime ideals of `K`. Otherwise, if the model has to be changed at a place `v` a correction factor appears. The definition is such that `C(E/K)` times the periods at the infinite places is invariant under change of the Weierstrass model. See [Ta2] and [Do] for details.
472,439
def tamagawa_product(self): r""" Given an elliptic curve `E` over a number field `K`, this function returns the integer `C(E/K)` that appears in the Birch and Swinnerton-Dyer conjecture accounting for the local information at finite places. If the model is a global minimal model then `C(E/K)` is simply the product of the Tamagawa numbers `c_v` where `v` runs over all prime ideals of `K`. Otherwise, if the model has to be changed at a place `v` a correction factor appears. The definition is such that `C(E/K)` times the periods at the infinite places is invariant under change of the Weierstrass model. See [Ta2] and [Do] for details.
def tamagawa_product(self): r""" Given an elliptic curve `E` over a number field `K`, this function returns the integer `C(E/K)` that appears in the Birch and Swinnerton-Dyer conjecture accounting for the local information at finite places. If the model is a global minimal model then `C(E/K)` is simply the product of the Tamagawa numbers `c_v` where `v` runs over all prime ideals of `K`. Otherwise, if the model has to be changed at a place `v` a correction factor appears. The definition is such that `C(E/K)` times the periods at the infinite places is invariant under change of the Weierstrass model. See [Ta2] and [Do] for details.
472,440
def global_minimal_model(self, proof = None): r""" Returns a model of self that is integral, minimal at all primes.
def global_minimal_model(self, proof = None): r""" Returns a model of self that is integral, minimal at all primes.
472,441
sage: 'divisors' in _search_src_or_doc('src', '^ *def prime', interact=False)
sage: 'divisors' in _search_src_or_doc('src', '^ *def prime', interact=False)
472,442
sage: 'divisors' in _search_src_or_doc('src', '^ *def prime', interact=False)
sage: 'divisors' in _search_src_or_doc('src', '^ *def prime', interact=False)
472,443
sage: 'divisors' in _search_src_or_doc('src', '^ *def prime', interact=False)
sage: 'divisors' in _search_src_or_doc('src', '^ *def prime', interact=False)
472,444
sage: 'divisors' in _search_src_or_doc('src', '^ *def prime', interact=False)
sage: 'divisors' in _search_src_or_doc('src', '^ *def prime', interact=False)
472,445
sage: 'divisors' in _search_src_or_doc('src', '^ *def prime', interact=False)
sage: 'divisors' in _search_src_or_doc('src', '^ *def prime', interact=False)
472,446
def region_plot(f, xrange, yrange, plot_points, incol, outcol, bordercol, borderstyle, borderwidth): r""" ``region_plot`` takes a boolean function of two variables, `f(x,y)` and plots the region where f is True over the specified ``xrange`` and ``yrange`` as demonstrated below. ``region_plot(f, (xmin, xmax), (ymin, ymax), ...)`` INPUT: - ``f`` -- a boolean function of two variables - ``(xmin, xmax)`` -- 2-tuple, the range of ``x`` values OR 3-tuple ``(x,xmin,xmax)`` - ``(ymin, ymax)`` -- 2-tuple, the range of ``y`` values OR 3-tuple ``(y,ymin,ymax)`` - ``plot_points`` -- integer (default: 100); number of points to plot in each direction of the grid - ``incol`` -- a color (default: ``'blue'``), the color inside the region - ``outcol`` -- a color (default: ``'white'``), the color of the outside of the region If any of these options are specified, the border will be shown as indicated, otherwise it is only implicit (with color ``incol``) as the border of the inside of the region. - ``bordercol`` -- a color (default: ``None``), the color of the border (``'black'`` if ``borderwidth`` or ``borderstyle`` is specified but not ``bordercol``) - ``borderstyle`` -- string (default: 'solid'), one of 'solid', 'dashed', 'dotted', 'dashdot' - ``borderwidth`` -- integer (default: None), the width of the border in pixels EXAMPLES: Here we plot a simple function of two variables:: sage: x,y = var('x,y') sage: region_plot(cos(x^2+y^2) <= 0, (x, -3, 3), (y, -3, 3)) Here we play with the colors:: sage: region_plot(x^2+y^3 < 2, (x, -2, 2), (y, -2, 2), incol='lightblue', bordercol='gray') An even more complicated plot, with dashed borders:: sage: region_plot(sin(x)*sin(y) >= 1/4, (x,-10,10), (y,-10,10), incol='yellow', bordercol='black', borderstyle='dashed', plot_points=250) A disk centered at the origin:: sage: region_plot(x^2+y^2<1, (x,-1,1), (y,-1,1)).show(aspect_ratio=1) A plot with more than one condition:: sage: region_plot([x^2+y^2<1, x<y], (x,-2,2), (y,-2,2)) Since it doesn't look very good, let's increase plot_points:: sage: region_plot([x^2+y^2<1, x<y], (x,-2,2), (y,-2,2), plot_points=400).show(aspect_ratio=1) #long time The first quadrant of the unit circle:: sage: region_plot([y>0, x>0, x^2+y^2<1], (x,-1.1, 1.1), (y,-1.1, 1.1), plot_points = 400).show(aspect_ratio=1) Here is another plot, with a huge border:: sage: region_plot(x*(x-1)*(x+1)+y^2<0, (x, -3, 2), (y, -3, 3), incol='lightblue', bordercol='gray', borderwidth=10, plot_points=50) If we want to keep only the region where x is positive:: sage: region_plot([x*(x-1)*(x+1)+y^2<0, x>-1], (x, -3, 2), (y, -3, 3), incol='lightblue', plot_points=50) Here we have a cut circle:: sage: region_plot([x^2+y^2<4, x>-1], (x, -2, 2), (y, -2, 2), incol='lightblue', bordercol='gray', plot_points=200).show(aspect_ratio=1) """ from sage.plot.plot import Graphics from sage.plot.misc import setup_for_eval_on_grid import numpy if not isinstance(f, (list, tuple)): f = [f] f = [equify(g) for g in f] g, ranges = setup_for_eval_on_grid(f, [xrange, yrange], plot_points) xrange,yrange=[r[:2] for r in ranges] xy_data_arrays = numpy.asarray([[[func(x, y) for x in xsrange(*ranges[0], include_endpoint=True)] for y in xsrange(*ranges[1], include_endpoint=True)] for func in g],dtype=float) xy_data_array=numpy.abs(xy_data_arrays.prod(axis=0)) # Now we need to set entries to negative iff all # functions were negative at that point. neg_indices = (xy_data_arrays<0).all(axis=0) xy_data_array[neg_indices]=-xy_data_array[neg_indices] from matplotlib.colors import ListedColormap incol = rgbcolor(incol) outcol = rgbcolor(outcol) cmap = ListedColormap([incol, outcol]) cmap.set_over(outcol) cmap.set_under(incol) g = Graphics() opt = contour_plot.options.copy() opt.pop('plot_points') opt.pop('fill') opt.pop('contours') opt.pop('frame') g.add_primitive(ContourPlot(xy_data_array, xrange,yrange, dict(plot_points=plot_points, contours=[-1e307, 0, 1e307], cmap=cmap, fill=True, **opt))) if bordercol or borderstyle or borderwidth: cmap = [rgbcolor(bordercol)] if bordercol else ['black'] linestyles = [borderstyle] if borderstyle else None linewidths = [borderwidth] if borderwidth else None opt.pop('linestyles') opt.pop('linewidths') g.add_primitive(ContourPlot(xy_data_array, xrange, yrange, dict(plot_points=plot_points, linestyles=linestyles, linewidths=linewidths, contours=[0], cmap=[bordercol], fill=False, **opt))) return g
def region_plot(f, xrange, yrange, plot_points, incol, outcol, bordercol, borderstyle, borderwidth): r""" ``region_plot`` takes a boolean function of two variables, `f(x,y)` and plots the region where f is True over the specified ``xrange`` and ``yrange`` as demonstrated below. ``region_plot(f, (xmin, xmax), (ymin, ymax), ...)`` INPUT: - ``f`` -- a boolean function of two variables - ``(xmin, xmax)`` -- 2-tuple, the range of ``x`` values OR 3-tuple ``(x,xmin,xmax)`` - ``(ymin, ymax)`` -- 2-tuple, the range of ``y`` values OR 3-tuple ``(y,ymin,ymax)`` - ``plot_points`` -- integer (default: 100); number of points to plot in each direction of the grid - ``incol`` -- a color (default: ``'blue'``), the color inside the region - ``outcol`` -- a color (default: ``'white'``), the color of the outside of the region If any of these options are specified, the border will be shown as indicated, otherwise it is only implicit (with color ``incol``) as the border of the inside of the region. - ``bordercol`` -- a color (default: ``None``), the color of the border (``'black'`` if ``borderwidth`` or ``borderstyle`` is specified but not ``bordercol``) - ``borderstyle`` -- string (default: 'solid'), one of 'solid', 'dashed', 'dotted', 'dashdot' - ``borderwidth`` -- integer (default: None), the width of the border in pixels EXAMPLES: Here we plot a simple function of two variables:: sage: x,y = var('x,y') sage: region_plot(cos(x^2+y^2) <= 0, (x, -3, 3), (y, -3, 3)) Here we play with the colors:: sage: region_plot(x^2+y^3 < 2, (x, -2, 2), (y, -2, 2), incol='lightblue', bordercol='gray') An even more complicated plot, with dashed borders:: sage: region_plot(sin(x)*sin(y) >= 1/4, (x,-10,10), (y,-10,10), incol='yellow', bordercol='black', borderstyle='dashed', plot_points=250) A disk centered at the origin:: sage: region_plot(x^2+y^2<1, (x,-1,1), (y,-1,1)).show(aspect_ratio=1) A plot with more than one condition:: sage: region_plot([x^2+y^2<1, x<y], (x,-2,2), (y,-2,2)) Since it doesn't look very good, let's increase plot_points:: sage: region_plot([x^2+y^2<1, x<y], (x,-2,2), (y,-2,2), plot_points=400).show(aspect_ratio=1) #long time The first quadrant of the unit circle:: sage: region_plot([y>0, x>0, x^2+y^2<1], (x,-1.1, 1.1), (y,-1.1, 1.1), plot_points = 400).show(aspect_ratio=1) Here is another plot, with a huge border:: sage: region_plot(x*(x-1)*(x+1)+y^2<0, (x, -3, 2), (y, -3, 3), incol='lightblue', bordercol='gray', borderwidth=10, plot_points=50) If we want to keep only the region where x is positive:: sage: region_plot([x*(x-1)*(x+1)+y^2<0, x>-1], (x, -3, 2), (y, -3, 3), incol='lightblue', plot_points=50) Here we have a cut circle:: sage: region_plot([x^2+y^2<4, x>-1], (x, -2, 2), (y, -2, 2), incol='lightblue', bordercol='gray', plot_points=200).show(aspect_ratio=1) """ from sage.plot.plot import Graphics from sage.plot.misc import setup_for_eval_on_grid import numpy if not isinstance(f, (list, tuple)): f = [f] f = [equify(g) for g in f] g, ranges = setup_for_eval_on_grid(f, [xrange, yrange], plot_points) xrange,yrange=[r[:2] for r in ranges] xy_data_arrays = numpy.asarray([[[func(x, y) for x in xsrange(*ranges[0], include_endpoint=True)] for y in xsrange(*ranges[1], include_endpoint=True)] for func in g],dtype=float) xy_data_array=numpy.abs(xy_data_arrays.prod(axis=0)) # Now we need to set entries to negative iff all # functions were negative at that point. neg_indices = (xy_data_arrays<0).all(axis=0) xy_data_array[neg_indices]=-xy_data_array[neg_indices] from matplotlib.colors import ListedColormap incol = rgbcolor(incol) outcol = rgbcolor(outcol) cmap = ListedColormap([incol, outcol]) cmap.set_over(outcol) cmap.set_under(incol) g = Graphics() opt = contour_plot.options.copy() opt.pop('plot_points') opt.pop('fill') opt.pop('contours') opt.pop('frame') g.add_primitive(ContourPlot(xy_data_array, xrange,yrange, dict(plot_points=plot_points, contours=[-1e307, 0, 1e307], cmap=cmap, fill=True, **opt))) if bordercol or borderstyle or borderwidth: cmap = [rgbcolor(bordercol)] if bordercol else ['black'] linestyles = [borderstyle] if borderstyle else None linewidths = [borderwidth] if borderwidth else None opt.pop('linestyles') opt.pop('linewidths') g.add_primitive(ContourPlot(xy_data_array, xrange, yrange, dict(plot_points=plot_points, linestyles=linestyles, linewidths=linewidths, contours=[0], cmap=[bordercol], fill=False, **opt))) return g
472,447
def _singular_init_(self, singular=singular_default): """ Return a newly created Singular ring matching this ring. """ if not can_convert_to_singular(self): raise TypeError, "no conversion of this ring to a Singular ring defined"
def _singular_init_(self, singular=singular_default): """ Return a newly created Singular ring matching this ring. """ if not can_convert_to_singular(self): raise TypeError, "no conversion of this ring to a Singular ring defined"
472,448
def check_tkz_graph(): r""" Checks if the proper `\mbox{\rm\LaTeX}` packages for the ``tikzpicture`` environment are installed in the user's environment. If the requisite packages are not found on the first call to this function, warnings are printed. Thereafter, the function caches its result in the variable ``_have_tkz_graph``, and any subsequent time, it just checks the value of the variable, without printing any warnings. So any doctest that illustrates the use of the tkz-graph packages should call this once as having random output to exhaust the warnings before testing output. TESTS:: sage: from sage.graphs.graph_latex import check_tkz_graph sage: check_tkz_graph() # random - depends on TeX installation sage: check_tkz_graph() # at least the second time, so no output """ global _checked_tkz_graph if not _checked_tkz_graph: import os have_tkzgraph = not bool(os.system('kpsewhich tkz-graph.sty > /dev/null')) if not have_tkzgraph: print 'Warning: tkz-graph.sty is not part' print "of this computer's TeX installation." print 'This package is required to' print 'render graphs in LaTeX. Visit' print 'http://altermundus.com/pages/graph.html' have_tkzberge = not bool(os.system('kpsewhich tkz-berge.sty > /dev/null')) if not have_tkzberge: print 'Warning: tkz-berge.sty is not part' print "of this computer's TeX installation." print 'This package is required to' print 'render graphs in LaTeX. Visit' print 'http://altermundus.com/pages/graph.html' _checked_tkz_graph = True
def check_tkz_graph(): r""" Checks if the proper `\mbox{\rm\LaTeX}` packages for the ``tikzpicture`` environment are installed in the user's environment. If the requisite packages are not found on the first call to this function, warnings are printed. Thereafter, the function caches its result in the variable ``_have_tkz_graph``, and any subsequent time, it just checks the value of the variable, without printing any warnings. So any doctest that illustrates the use of the tkz-graph packages should call this once as having random output to exhaust the warnings before testing output. TESTS:: sage: from sage.graphs.graph_latex import check_tkz_graph sage: check_tkz_graph() # random - depends on TeX installation sage: check_tkz_graph() # at least the second time, so no output """ global _checked_tkz_graph if not _checked_tkz_graph: import os have_tkzgraph = not bool(os.system('kpsewhich tkz-graph.sty &> /dev/null')) if not have_tkzgraph: print 'Warning: tkz-graph.sty is not part' print "of this computer's TeX installation." print 'This package is required to' print 'render graphs in LaTeX. Visit' print 'http://altermundus.com/pages/graph.html' have_tkzberge = not bool(os.system('kpsewhich tkz-berge.sty > /dev/null')) if not have_tkzberge: print 'Warning: tkz-berge.sty is not part' print "of this computer's TeX installation." print 'This package is required to' print 'render graphs in LaTeX. Visit' print 'http://altermundus.com/pages/graph.html' _checked_tkz_graph = True
472,449
def check_tkz_graph(): r""" Checks if the proper `\mbox{\rm\LaTeX}` packages for the ``tikzpicture`` environment are installed in the user's environment. If the requisite packages are not found on the first call to this function, warnings are printed. Thereafter, the function caches its result in the variable ``_have_tkz_graph``, and any subsequent time, it just checks the value of the variable, without printing any warnings. So any doctest that illustrates the use of the tkz-graph packages should call this once as having random output to exhaust the warnings before testing output. TESTS:: sage: from sage.graphs.graph_latex import check_tkz_graph sage: check_tkz_graph() # random - depends on TeX installation sage: check_tkz_graph() # at least the second time, so no output """ global _checked_tkz_graph if not _checked_tkz_graph: import os have_tkzgraph = not bool(os.system('kpsewhich tkz-graph.sty > /dev/null')) if not have_tkzgraph: print 'Warning: tkz-graph.sty is not part' print "of this computer's TeX installation." print 'This package is required to' print 'render graphs in LaTeX. Visit' print 'http://altermundus.com/pages/graph.html' have_tkzberge = not bool(os.system('kpsewhich tkz-berge.sty > /dev/null')) if not have_tkzberge: print 'Warning: tkz-berge.sty is not part' print "of this computer's TeX installation." print 'This package is required to' print 'render graphs in LaTeX. Visit' print 'http://altermundus.com/pages/graph.html' _checked_tkz_graph = True
def check_tkz_graph(): r""" Checks if the proper `\mbox{\rm\LaTeX}` packages for the ``tikzpicture`` environment are installed in the user's environment. If the requisite packages are not found on the first call to this function, warnings are printed. Thereafter, the function caches its result in the variable ``_have_tkz_graph``, and any subsequent time, it just checks the value of the variable, without printing any warnings. So any doctest that illustrates the use of the tkz-graph packages should call this once as having random output to exhaust the warnings before testing output. TESTS:: sage: from sage.graphs.graph_latex import check_tkz_graph sage: check_tkz_graph() # random - depends on TeX installation sage: check_tkz_graph() # at least the second time, so no output """ global _checked_tkz_graph if not _checked_tkz_graph: import os have_tkzgraph = not bool(os.system('kpsewhich tkz-graph.sty > /dev/null')) if not have_tkzgraph: print 'Warning: tkz-graph.sty is not part' print "of this computer's TeX installation." print 'This package is required to' print 'render graphs in LaTeX. Visit' print 'http://altermundus.com/pages/graph.html' have_tkzberge = not bool(os.system('kpsewhich tkz-berge.sty &> /dev/null')) if not have_tkzberge: print 'Warning: tkz-berge.sty is not part' print "of this computer's TeX installation." print 'This package is required to' print 'render graphs in LaTeX. Visit' print 'http://altermundus.com/pages/graph.html' _checked_tkz_graph = True
472,450
def have_tkz_graph(): r""" Returns ``True`` if the proper `\mbox{\rm\LaTeX}` packages for the ``tikzpicture`` environment are installed in the user's environment. The first time it is run, this function caches its result in the variable ``_have_tkz_graph``, and any subsequent time, it just checks the value of the variable. TESTS:: sage: from sage.graphs.graph_latex import have_tkz_graph, _have_tkz_graph sage: have_tkz_graph() # random - depends on TeX installation sage: _have_tkz_graph is None False sage: _have_tkz_graph == have_tkz_graph() True """ global _have_tkz_graph if _have_tkz_graph is None: import os have_tkzgraph = not bool(os.system('kpsewhich tkz-graph.sty > /dev/null')) have_tkzberge = not bool(os.system('kpsewhich tkz-berge.sty > /dev/null')) _have_tkz_graph = have_tkzgraph and have_tkzberge return _have_tkz_graph
def have_tkz_graph(): r""" Returns ``True`` if the proper `\mbox{\rm\LaTeX}` packages for the ``tikzpicture`` environment are installed in the user's environment. The first time it is run, this function caches its result in the variable ``_have_tkz_graph``, and any subsequent time, it just checks the value of the variable. TESTS:: sage: from sage.graphs.graph_latex import have_tkz_graph, _have_tkz_graph sage: have_tkz_graph() # random - depends on TeX installation sage: _have_tkz_graph is None False sage: _have_tkz_graph == have_tkz_graph() True """ global _have_tkz_graph if _have_tkz_graph is None: import os have_tkzgraph = not bool(os.system('kpsewhich tkz-graph.sty &> /dev/null')) have_tkzberge = not bool(os.system('kpsewhich tkz-berge.sty &> /dev/null')) _have_tkz_graph = have_tkzgraph and have_tkzberge return _have_tkz_graph
472,451
def hasse_diagram(self): """ Returns the Hasse_diagram of the poset as a Sage DiGraph object.
def hasse_diagram(self): """ Returns the Hasse_diagram of the poset as a Sage DiGraph object.
472,452
def polar_plot(funcs, *args, **kwds): r""" ``polar_plot`` takes a single function or a list or tuple of functions and plots them with polar coordinates in the given domain. This function is equivalent to the plot command with the options ``polar=True`` and ``aspect_ratio=1``. For more help on options, see the documentation for plot. INPUT: - ``funcs`` - a function - other options are passed to plot EXAMPLES: Here is a blue 8-leaved petal:: sage: polar_plot(sin(5*x)^2, (x, 0, 2*pi), color='blue') A red figure-8:: sage: polar_plot(abs(sqrt(1 - sin(x)^2)), (x, 0, 2*pi), color='red') A green limacon of Pascal:: sage: polar_plot(2 + 2*cos(x), (x, 0, 2*pi), color=hue(0.3)) Several polar plots:: sage: polar_plot([2*sin(x), 2*cos(x)], (x, 0, 2*pi)) A filled spiral:: sage: polar_plot(sqrt, 0, 2 * pi, fill = True) Fill the area between two functions:: sage: polar_plot(cos(4*x) + 1.5, 0, 2*pi, fill=0.5 * cos(4*x) + 2.5, fillcolor='orange').show(aspect_ratio=1) Fill the area between several spirals:: sage: polar_plot([(1.2+k*0.2)*log(x) for k in range(6)], 1, 3 * pi, fill = {0: [1], 2: [3], 4: [5]}) Exclude points at discontinuities:: sage: polar_plot(log(floor(x)), (x, 1, 4*pi), aspect_ratio = 1, exclude = [1..12]) """ kwds['polar']=True return plot(funcs, *args, **kwds)
def polar_plot(funcs, *args, **kwds): r""" ``polar_plot`` takes a single function or a list or tuple of functions and plots them with polar coordinates in the given domain. This function is equivalent to the :func:`plot` command with the options ``polar=True`` and ``aspect_ratio=1``. For more help on options, see the documentation for plot. INPUT: - ``funcs`` - a function - other options are passed to plot EXAMPLES: Here is a blue 8-leaved petal:: sage: polar_plot(sin(5*x)^2, (x, 0, 2*pi), color='blue') A red figure-8:: sage: polar_plot(abs(sqrt(1 - sin(x)^2)), (x, 0, 2*pi), color='red') A green limacon of Pascal:: sage: polar_plot(2 + 2*cos(x), (x, 0, 2*pi), color=hue(0.3)) Several polar plots:: sage: polar_plot([2*sin(x), 2*cos(x)], (x, 0, 2*pi)) A filled spiral:: sage: polar_plot(sqrt, 0, 2 * pi, fill = True) Fill the area between two functions:: sage: polar_plot(cos(4*x) + 1.5, 0, 2*pi, fill=0.5 * cos(4*x) + 2.5, fillcolor='orange').show(aspect_ratio=1) Fill the area between several spirals:: sage: polar_plot([(1.2+k*0.2)*log(x) for k in range(6)], 1, 3 * pi, fill = {0: [1], 2: [3], 4: [5]}) Exclude points at discontinuities:: sage: polar_plot(log(floor(x)), (x, 1, 4*pi), aspect_ratio = 1, exclude = [1..12]) """ kwds['polar']=True return plot(funcs, *args, **kwds)
472,453
def polar_plot(funcs, *args, **kwds): r""" ``polar_plot`` takes a single function or a list or tuple of functions and plots them with polar coordinates in the given domain. This function is equivalent to the plot command with the options ``polar=True`` and ``aspect_ratio=1``. For more help on options, see the documentation for plot. INPUT: - ``funcs`` - a function - other options are passed to plot EXAMPLES: Here is a blue 8-leaved petal:: sage: polar_plot(sin(5*x)^2, (x, 0, 2*pi), color='blue') A red figure-8:: sage: polar_plot(abs(sqrt(1 - sin(x)^2)), (x, 0, 2*pi), color='red') A green limacon of Pascal:: sage: polar_plot(2 + 2*cos(x), (x, 0, 2*pi), color=hue(0.3)) Several polar plots:: sage: polar_plot([2*sin(x), 2*cos(x)], (x, 0, 2*pi)) A filled spiral:: sage: polar_plot(sqrt, 0, 2 * pi, fill = True) Fill the area between two functions:: sage: polar_plot(cos(4*x) + 1.5, 0, 2*pi, fill=0.5 * cos(4*x) + 2.5, fillcolor='orange').show(aspect_ratio=1) Fill the area between several spirals:: sage: polar_plot([(1.2+k*0.2)*log(x) for k in range(6)], 1, 3 * pi, fill = {0: [1], 2: [3], 4: [5]}) Exclude points at discontinuities:: sage: polar_plot(log(floor(x)), (x, 1, 4*pi), aspect_ratio = 1, exclude = [1..12]) """ kwds['polar']=True return plot(funcs, *args, **kwds)
def polar_plot(funcs, *args, **kwds): r""" ``polar_plot`` takes a single function or a list or tuple of functions and plots them with polar coordinates in the given domain. This function is equivalent to the plot command with the options ``polar=True`` and ``aspect_ratio=1``. For more help on options, see the documentation for :func:`plot`. INPUT: - ``funcs`` - a function - other options are passed to plot EXAMPLES: Here is a blue 8-leaved petal:: sage: polar_plot(sin(5*x)^2, (x, 0, 2*pi), color='blue') A red figure-8:: sage: polar_plot(abs(sqrt(1 - sin(x)^2)), (x, 0, 2*pi), color='red') A green limacon of Pascal:: sage: polar_plot(2 + 2*cos(x), (x, 0, 2*pi), color=hue(0.3)) Several polar plots:: sage: polar_plot([2*sin(x), 2*cos(x)], (x, 0, 2*pi)) A filled spiral:: sage: polar_plot(sqrt, 0, 2 * pi, fill = True) Fill the area between two functions:: sage: polar_plot(cos(4*x) + 1.5, 0, 2*pi, fill=0.5 * cos(4*x) + 2.5, fillcolor='orange').show(aspect_ratio=1) Fill the area between several spirals:: sage: polar_plot([(1.2+k*0.2)*log(x) for k in range(6)], 1, 3 * pi, fill = {0: [1], 2: [3], 4: [5]}) Exclude points at discontinuities:: sage: polar_plot(log(floor(x)), (x, 1, 4*pi), aspect_ratio = 1, exclude = [1..12]) """ kwds['polar']=True return plot(funcs, *args, **kwds)
472,454
def _find_scaling_L_ratio(self): r""" This function is use to set ``_scaling``, the factor used to adjust the scalar multiple of the modular symbol. If `[0]`, the modular symbol evaluated at 0, is non-zero, we can just scale it with respect to the approximation of the L-value. It is known that the quotient is a rational number with small denominator. Otherwise we try to scale using quadratic twists.
def _find_scaling_L_ratio(self): r""" This function is use to set ``_scaling``, the factor used to adjust the scalar multiple of the modular symbol. If `[0]`, the modular symbol evaluated at 0, is non-zero, we can just scale it with respect to the approximation of the L-value. It is known that the quotient is a rational number with small denominator. Otherwise we try to scale using quadratic twists.
472,455
def _find_scaling_L_ratio(self): r""" This function is use to set ``_scaling``, the factor used to adjust the scalar multiple of the modular symbol. If `[0]`, the modular symbol evaluated at 0, is non-zero, we can just scale it with respect to the approximation of the L-value. It is known that the quotient is a rational number with small denominator. Otherwise we try to scale using quadratic twists.
def _find_scaling_L_ratio(self): r""" This function is use to set ``_scaling``, the factor used to adjust the scalar multiple of the modular symbol. If `[0]`, the modular symbol evaluated at 0, is non-zero, we can just scale it with respect to the approximation of the L-value. It is known that the quotient is a rational number with small denominator. Otherwise we try to scale using quadratic twists.
472,456
def _find_scaling_L_ratio(self): r""" This function is use to set ``_scaling``, the factor used to adjust the scalar multiple of the modular symbol. If `[0]`, the modular symbol evaluated at 0, is non-zero, we can just scale it with respect to the approximation of the L-value. It is known that the quotient is a rational number with small denominator. Otherwise we try to scale using quadratic twists.
def _find_scaling_L_ratio(self): r""" This function is use to set ``_scaling``, the factor used to adjust the scalar multiple of the modular symbol. If `[0]`, the modular symbol evaluated at 0, is non-zero, we can just scale it with respect to the approximation of the L-value. It is known that the quotient is a rational number with small denominator. Otherwise we try to scale using quadratic twists.
472,457
def _find_scaling_L_ratio(self): r""" This function is use to set ``_scaling``, the factor used to adjust the scalar multiple of the modular symbol. If `[0]`, the modular symbol evaluated at 0, is non-zero, we can just scale it with respect to the approximation of the L-value. It is known that the quotient is a rational number with small denominator. Otherwise we try to scale using quadratic twists.
def _find_scaling_L_ratio(self): r""" This function is use to set ``_scaling``, the factor used to adjust the scalar multiple of the modular symbol. If `[0]`, the modular symbol evaluated at 0, is non-zero, we can just scale it with respect to the approximation of the L-value. It is known that the quotient is a rational number with small denominator. Otherwise we try to scale using quadratic twists.
472,458
def _find_scaling_L_ratio(self): r""" This function is use to set ``_scaling``, the factor used to adjust the scalar multiple of the modular symbol. If `[0]`, the modular symbol evaluated at 0, is non-zero, we can just scale it with respect to the approximation of the L-value. It is known that the quotient is a rational number with small denominator. Otherwise we try to scale using quadratic twists.
def _find_scaling_L_ratio(self): r""" This function is use to set ``_scaling``, the factor used to adjust the scalar multiple of the modular symbol. If `[0]`, the modular symbol evaluated at 0, is non-zero, we can just scale it with respect to the approximation of the L-value. It is known that the quotient is a rational number with small denominator. Otherwise we try to scale using quadratic twists.
472,459
def _find_scaling_L_ratio(self): r""" This function is use to set ``_scaling``, the factor used to adjust the scalar multiple of the modular symbol. If `[0]`, the modular symbol evaluated at 0, is non-zero, we can just scale it with respect to the approximation of the L-value. It is known that the quotient is a rational number with small denominator. Otherwise we try to scale using quadratic twists.
def _find_scaling_L_ratio(self): r""" This function is use to set ``_scaling``, the factor used to adjust the scalar multiple of the modular symbol. If `[0]`, the modular symbol evaluated at 0, is non-zero, we can just scale it with respect to the approximation of the L-value. It is known that the quotient is a rational number with small denominator. Otherwise we try to scale using quadratic twists.
472,460
def _find_scaling_L_ratio(self): r""" This function is use to set ``_scaling``, the factor used to adjust the scalar multiple of the modular symbol. If `[0]`, the modular symbol evaluated at 0, is non-zero, we can just scale it with respect to the approximation of the L-value. It is known that the quotient is a rational number with small denominator. Otherwise we try to scale using quadratic twists.
def _find_scaling_L_ratio(self): r""" This function is use to set ``_scaling``, the factor used to adjust the scalar multiple of the modular symbol. If `[0]`, the modular symbol evaluated at 0, is non-zero, we can just scale it with respect to the approximation of the L-value. It is known that the quotient is a rational number with small denominator. Otherwise we try to scale using quadratic twists.
472,461
def _find_scaling_L_ratio(self): r""" This function is use to set ``_scaling``, the factor used to adjust the scalar multiple of the modular symbol. If `[0]`, the modular symbol evaluated at 0, is non-zero, we can just scale it with respect to the approximation of the L-value. It is known that the quotient is a rational number with small denominator. Otherwise we try to scale using quadratic twists.
def _find_scaling_L_ratio(self): r""" This function is use to set ``_scaling``, the factor used to adjust the scalar multiple of the modular symbol. If `[0]`, the modular symbol evaluated at 0, is non-zero, we can just scale it with respect to the approximation of the L-value. It is known that the quotient is a rational number with small denominator. Otherwise we try to scale using quadratic twists.
472,462
def _find_scaling_L_ratio(self): r""" This function is use to set ``_scaling``, the factor used to adjust the scalar multiple of the modular symbol. If `[0]`, the modular symbol evaluated at 0, is non-zero, we can just scale it with respect to the approximation of the L-value. It is known that the quotient is a rational number with small denominator. Otherwise we try to scale using quadratic twists.
def _find_scaling_L_ratio(self): r""" This function is use to set ``_scaling``, the factor used to adjust the scalar multiple of the modular symbol. If `[0]`, the modular symbol evaluated at 0, is non-zero, we can just scale it with respect to the approximation of the L-value. It is known that the quotient is a rational number with small denominator. Otherwise we try to scale using quadratic twists.
472,463
def _find_scaling_L_ratio(self): r""" This function is use to set ``_scaling``, the factor used to adjust the scalar multiple of the modular symbol. If `[0]`, the modular symbol evaluated at 0, is non-zero, we can just scale it with respect to the approximation of the L-value. It is known that the quotient is a rational number with small denominator. Otherwise we try to scale using quadratic twists.
def _find_scaling_L_ratio(self): r""" This function is use to set ``_scaling``, the factor used to adjust the scalar multiple of the modular symbol. If `[0]`, the modular symbol evaluated at 0, is non-zero, we can just scale it with respect to the approximation of the L-value. It is known that the quotient is a rational number with small denominator. Otherwise we try to scale using quadratic twists.
472,464
def _find_scaling_L_ratio(self): r""" This function is use to set ``_scaling``, the factor used to adjust the scalar multiple of the modular symbol. If `[0]`, the modular symbol evaluated at 0, is non-zero, we can just scale it with respect to the approximation of the L-value. It is known that the quotient is a rational number with small denominator. Otherwise we try to scale using quadratic twists.
def _find_scaling_L_ratio(self): r""" This function is use to set ``_scaling``, the factor used to adjust the scalar multiple of the modular symbol. If `[0]`, the modular symbol evaluated at 0, is non-zero, we can just scale it with respect to the approximation of the L-value. It is known that the quotient is a rational number with small denominator. Otherwise we try to scale using quadratic twists.
472,465
def sturm_bound(self, M=None): r""" For a space M of modular forms, this function returns an integer B such that two modular forms in either self or M are equal if and only if their q-expansions are equal to precision B (note that this is 1+ the usual Sturm bound, since `O(q^\mathrm{prec})` has precision prec). If M is none, then M is set equal to self.
def sturm_bound(self, M=None): r""" For a space M of modular forms, this function returns an integer B such that two modular forms in either self or M are equal if and only if their q-expansions are equal to precision B (note that this is 1+ the usual Sturm bound, since `O(q^\mathrm{prec})` has precision prec). If M is none, then M is set equal to self.
472,466
def sturm_bound(self, M=None): r""" For a space M of modular forms, this function returns an integer B such that two modular forms in either self or M are equal if and only if their q-expansions are equal to precision B (note that this is 1+ the usual Sturm bound, since `O(q^\mathrm{prec})` has precision prec). If M is none, then M is set equal to self.
def sturm_bound(self, M=None): r""" For a space M of modular forms, this function returns an integer B such that two modular forms in either self or M are equal if and only if their q-expansions are equal to precision B (note that this is 1+ the usual Sturm bound, since `O(q^\mathrm{prec})` has precision prec). If M is none, then M is set equal to self.
472,467
def sturm_bound(self, M=None): r""" For a space M of modular forms, this function returns an integer B such that two modular forms in either self or M are equal if and only if their q-expansions are equal to precision B (note that this is 1+ the usual Sturm bound, since `O(q^\mathrm{prec})` has precision prec). If M is none, then M is set equal to self.
def sturm_bound(self, M=None): r""" For a space M of modular forms, this function returns an integer B such that two modular forms in either self or M are equal if and only if their q-expansions are equal to precision B (note that this is 1+ the usual Sturm bound, since `O(q^\mathrm{prec})` has precision prec). If M is none, then M is set equal to self.
472,468
def __init__(self, *args, **kwargs): """ Construct a substitution box (S-box) for a given lookup table `S`.
def __init__(self, *args, **kwargs): """ Construct a substitution box (S-box) for a given lookup table `S`.
472,469
def valuation(m, p): """ The exact power of p that divides m. m should be an integer or rational (but maybe other types work too.) This actually just calls the m.valuation() method. If m is 0, this function returns rings.infinity. EXAMPLES:: sage: valuation(512,2) 9 sage: valuation(1,2) 0 sage: valuation(5/9, 3) -2 Valuation of 0 is defined, but valuation with respect to 0 is not:: sage: valuation(0,7) +Infinity sage: valuation(3,0) Traceback (most recent call last): ... ValueError: You can only compute the valuation with respect to a integer larger than 1. Here are some other examples:: sage: valuation(100,10) 2 sage: valuation(200,10) 2 sage: valuation(243,3) 5 sage: valuation(243*10007,3) 5 sage: valuation(243*10007,10007) 1 """ if hasattr(m, 'valuation'): return m.valuation(p) if m == 0: import sage.rings.all return sage.rings.all.infinity if is_FractionFieldElement(m): return valuation(m.numerator()) - valuation(m.denominator()) r = 0 power = p while not (m % power): # m % power == 0 r += 1 power *= p return r
def valuation(m,*args1, **args2): """ This actually just calls the m.valuation() method. If m is 0, this function returns rings.infinity. EXAMPLES:: sage: valuation(512,2) 9 sage: valuation(1,2) 0 sage: valuation(5/9, 3) -2 Valuation of 0 is defined, but valuation with respect to 0 is not:: sage: valuation(0,7) +Infinity sage: valuation(3,0) Traceback (most recent call last): ... ValueError: You can only compute the valuation with respect to a integer larger than 1. Here are some other examples:: sage: valuation(100,10) 2 sage: valuation(200,10) 2 sage: valuation(243,3) 5 sage: valuation(243*10007,3) 5 sage: valuation(243*10007,10007) 1 """ if hasattr(m, 'valuation'): return m.valuation(p) if m == 0: import sage.rings.all return sage.rings.all.infinity if is_FractionFieldElement(m): return valuation(m.numerator()) - valuation(m.denominator()) r = 0 power = p while not (m % power): # m % power == 0 r += 1 power *= p return r
472,470
def valuation(m, p): """ The exact power of p that divides m. m should be an integer or rational (but maybe other types work too.) This actually just calls the m.valuation() method. If m is 0, this function returns rings.infinity. EXAMPLES:: sage: valuation(512,2) 9 sage: valuation(1,2) 0 sage: valuation(5/9, 3) -2 Valuation of 0 is defined, but valuation with respect to 0 is not:: sage: valuation(0,7) +Infinity sage: valuation(3,0) Traceback (most recent call last): ... ValueError: You can only compute the valuation with respect to a integer larger than 1. Here are some other examples:: sage: valuation(100,10) 2 sage: valuation(200,10) 2 sage: valuation(243,3) 5 sage: valuation(243*10007,3) 5 sage: valuation(243*10007,10007) 1 """ if hasattr(m, 'valuation'): return m.valuation(p) if m == 0: import sage.rings.all return sage.rings.all.infinity if is_FractionFieldElement(m): return valuation(m.numerator()) - valuation(m.denominator()) r = 0 power = p while not (m % power): # m % power == 0 r += 1 power *= p return r
def valuation(m, p): """ The exact power of p that divides m. m should be an integer or rational (but maybe other types work too.) This actually just calls the m.valuation() method. See the documentation of m.valuation() for a more precise description. Use of this function by developers is discouraged. Use m.valuation() instead. .. NOTE:: This is not always a valuation in the mathematical sense. For more information see: sage.rings.finite_rings.integer_mod.IntegerMod_int.valuation EXAMPLES:: sage: valuation(512,2) 9 sage: valuation(1,2) 0 sage: valuation(5/9, 3) -2 Valuation of 0 is defined, but valuation with respect to 0 is not:: sage: valuation(0,7) +Infinity sage: valuation(3,0) Traceback (most recent call last): ... ValueError: You can only compute the valuation with respect to a integer larger than 1. Here are some other examples:: sage: valuation(100,10) 2 sage: valuation(200,10) 2 sage: valuation(243,3) 5 sage: valuation(243*10007,3) 5 sage: valuation(243*10007,10007) 1 """ if hasattr(m, 'valuation'): return m.valuation(p) if m == 0: import sage.rings.all return sage.rings.all.infinity if is_FractionFieldElement(m): return valuation(m.numerator()) - valuation(m.denominator()) r = 0 power = p while not (m % power): # m % power == 0 r += 1 power *= p return r
472,471
def valuation(m, p): """ The exact power of p that divides m. m should be an integer or rational (but maybe other types work too.) This actually just calls the m.valuation() method. If m is 0, this function returns rings.infinity. EXAMPLES:: sage: valuation(512,2) 9 sage: valuation(1,2) 0 sage: valuation(5/9, 3) -2 Valuation of 0 is defined, but valuation with respect to 0 is not:: sage: valuation(0,7) +Infinity sage: valuation(3,0) Traceback (most recent call last): ... ValueError: You can only compute the valuation with respect to a integer larger than 1. Here are some other examples:: sage: valuation(100,10) 2 sage: valuation(200,10) 2 sage: valuation(243,3) 5 sage: valuation(243*10007,3) 5 sage: valuation(243*10007,10007) 1 """ if hasattr(m, 'valuation'): return m.valuation(p) if m == 0: import sage.rings.all return sage.rings.all.infinity if is_FractionFieldElement(m): return valuation(m.numerator()) - valuation(m.denominator()) r = 0 power = p while not (m % power): # m % power == 0 r += 1 power *= p return r
def valuation(m, p): """ The exact power of p that divides m. m should be an integer or rational (but maybe other types work too.) This actually just calls the m.valuation() method. If m is 0, this function returns rings.infinity. EXAMPLES:: sage: valuation(512,2) 9 sage: valuation(1,2) 0 sage: valuation(5/9, 3) -2 Valuation of 0 is defined, but valuation with respect to 0 is not:: sage: valuation(0,7) +Infinity sage: valuation(3,0) Traceback (most recent call last): ... ValueError: You can only compute the valuation with respect to a integer larger than 1. Here are some other examples:: sage: valuation(100,10) 2 sage: valuation(200,10) 2 sage: valuation(243,3) 5 sage: valuation(243*10007,3) 5 sage: valuation(243*10007,10007) 1 """ if hasattr(m, 'valuation'): return m.valuation(p) if m == 0: import sage.rings.all return sage.rings.all.infinity if is_FractionFieldElement(m): return valuation(m.numerator()) - valuation(m.denominator()) r = 0 power = p while not (m % power): # m % power == 0 r += 1 power *= p return r
472,472
def canonical_label(self, partition=None, certify=False, verbosity=0, edge_labels=False): """ Returns the canonical label with respect to the partition. If no partition is given, uses the unit partition.
def canonical_label(self, partition=None, certify=False, verbosity=0, edge_labels=False): """ Returns the canonical label with respect to the partition. If no partition is given, uses the unit partition.
472,473
def canonical_label(self, partition=None, certify=False, verbosity=0, edge_labels=False): """ Returns the canonical label with respect to the partition. If no partition is given, uses the unit partition.
def canonical_label(self, partition=None, certify=False, verbosity=0, edge_labels=False): """ Returns the canonical label with respect to the partition. If no partition is given, uses the unit partition.
472,474
def canonical_label(self, partition=None, certify=False, verbosity=0, edge_labels=False): """ Returns the canonical label with respect to the partition. If no partition is given, uses the unit partition.
def canonical_label(self, partition=None, certify=False, verbosity=0, edge_labels=False): """ Returns the canonical label with respect to the partition. If no partition is given, uses the unit partition.
472,475
def canonical_label(self, partition=None, certify=False, verbosity=0, edge_labels=False): """ Returns the canonical label with respect to the partition. If no partition is given, uses the unit partition.
def canonical_label(self, partition=None, certify=False, verbosity=0, edge_labels=False): """ Returns the canonical label with respect to the partition. If no partition is given, uses the unit partition.
472,476
def canonical_label(self, partition=None, certify=False, verbosity=0, edge_labels=False): """ Returns the canonical label with respect to the partition. If no partition is given, uses the unit partition.
def canonical_label(self, partition=None, certify=False, verbosity=0, edge_labels=False): """ Returns the canonical label with respect to the partition. If no partition is given, uses the unit partition.
472,477
def E2(self,prec=20): r""" Returns the value of the `p`-adic Eisenstein series of weight 2 evaluated on the elliptic curve having split multiplicative reduction.
def E2(self,prec=20): r""" Returns the value of the `p`-adic Eisenstein series of weight 2 evaluated on the elliptic curve having split multiplicative reduction.
472,478
def __call__(self, *args): """ Coerces the element into the ring. You may pass a vector in the ambient space, an element of the base_ring, or an argument list of integers (or half-integers for the spin types) which are the components of a vector in the ambient space.
def __call__(self, *args): """ Coerces the element into the ring. You may pass a vector in the ambient space, an element of the base_ring, or an argument list of integers (or half-integers for the spin types) which are the components of a vector in the ambient space.
472,479
def bezier3d(path, **options): """ Draws a 3-dimensional bezier path. Input is similar to bezier_path, but each point in the path and each control point is required to have 3 coordinates. INPUT: - ``path`` - a list of curves, which each is a list of points. See further detail below. - ``thickness`` - (default: 2) - ``color`` - a word that describes a color - ``opacity`` - (default: 1) if less than 1 then is transparent - ``aspect_ratio`` - (default:[1,1,1]) The path is a list of curves, and each curve is a list of points. Each point is a tuple (x,y,z). The first curve contains the endpoints as the first and last point in the list. All other curves assume a starting point given by the last entry in the preceding list, and take the last point in the list as their opposite endpoint. A curve can have 0, 1 or 2 control points listed between the endpoints. In the input example for path below, the first and second curves have 2 control points, the third has one, and the fourth has no control points: path = [[p1, c1, c2, p2], [c3, c4, p3], [c5, p4], [p5], ...] In the case of no control points, a straight line will be drawn between the two endpoints. If one control point is supplied, then the curve at each of the endpoints will be tangent to the line from that endpoint to the control point. Similarly, in the case of two control points, at each endpoint the curve will be tangent to the line connecting that endpoint with the control point immediately after or immediately preceding it in the list. So in our example above, the curve between p1 and p2 is tangent to the line through p1 and c1 at p1, and tangent to the line through p2 and c2 at p2. Similarly, the curve between p2 and p3 is tangent to line(p2,c3) at p2 and tangent to line(p3,c4) at p3. Curve(p3,p4) is tangent to line(p3,c5) at p3 and tangent to line(p4,c5) at p4. Curve(p4,p5) is a straight line. EXAMPLES: sage: path = [[(0,0,0),(.5,.1,.2),(.75,3,-1),(1,1,0)],[(.5,1,.2),(1,.5,0)],[(.7,.2,.5)]] sage: b = bezier3d(path, color='green') sage: b To construct a simple curve, create a list containing a single list: sage: path = [[(0,0,0),(1,0,0),(0,1,0),(0,1,1)]] sage: curve = bezier3d(path, thickness=5, color='blue') sage: curve """ import parametric_plot3d as P3D from sage.modules.free_module_element import vector from sage.calculus.calculus import var p0 = vector(path[0][-1]) t = var('t') if len(path[0]) > 2: B = (1-t)**3*vector(path[0][0])+3*t*(1-t)**2*vector(path[0][1])+3*t**2*(1-t)*vector(path[0][-2])+t**3*p0 G = P3D.parametric_plot3d(list(B), (0, 1), color=options['color'], aspect_ratio=options['aspect_ratio'], thickness=options['thickness'], opacity=options['opacity']) else: G = line3d([path[0][0], p0], color=options['color'], thickness=options['thickness'], opacity=options['opacity']) for curve in path[1:]: if len(curve) > 1: p1 = vector(curve[0]) p2 = vector(curve[-2]) p3 = vector(curve[-1]) B = (1-t)**3*p0+3*t*(1-t)**2*p1+3*t**2*(1-t)*p2+t**3*p3 G += P3D.parametric_plot3d(list(B), (0, 1), color=options['color'], aspect_ratio=options['aspect_ratio'], thickness=options['thickness'], opacity=options['opacity']) else: G += line3d([p0,curve[0]], color=options['color'], thickness=options['thickness'], opacity=options['opacity']) p0 = curve[-1] return G
def bezier3d(path, **options): """ Draws a 3-dimensional bezier path. Input is similar to bezier_path, but each point in the path and each control point is required to have 3 coordinates. INPUT: - ``path`` - a list of curves, which each is a list of points. See further detail below. - ``thickness`` - (default: 2) - ``color`` - a word that describes a color - ``opacity`` - (default: 1) if less than 1 then is transparent - ``aspect_ratio`` - (default:[1,1,1]) The path is a list of curves, and each curve is a list of points. Each point is a tuple (x,y,z). The first curve contains the endpoints as the first and last point in the list. All other curves assume a starting point given by the last entry in the preceding list, and take the last point in the list as their opposite endpoint. A curve can have 0, 1 or 2 control points listed between the endpoints. In the input example for path below, the first and second curves have 2 control points, the third has one, and the fourth has no control points:: path = [[p1, c1, c2, p2], [c3, c4, p3], [c5, p4], [p5], ...] In the case of no control points, a straight line will be drawn between the two endpoints. If one control point is supplied, then the curve at each of the endpoints will be tangent to the line from that endpoint to the control point. Similarly, in the case of two control points, at each endpoint the curve will be tangent to the line connecting that endpoint with the control point immediately after or immediately preceding it in the list. So in our example above, the curve between p1 and p2 is tangent to the line through p1 and c1 at p1, and tangent to the line through p2 and c2 at p2. Similarly, the curve between p2 and p3 is tangent to line(p2,c3) at p2 and tangent to line(p3,c4) at p3. Curve(p3,p4) is tangent to line(p3,c5) at p3 and tangent to line(p4,c5) at p4. Curve(p4,p5) is a straight line. EXAMPLES: sage: path = [[(0,0,0),(.5,.1,.2),(.75,3,-1),(1,1,0)],[(.5,1,.2),(1,.5,0)],[(.7,.2,.5)]] sage: b = bezier3d(path, color='green') sage: b To construct a simple curve, create a list containing a single list: sage: path = [[(0,0,0),(1,0,0),(0,1,0),(0,1,1)]] sage: curve = bezier3d(path, thickness=5, color='blue') sage: curve """ import parametric_plot3d as P3D from sage.modules.free_module_element import vector from sage.calculus.calculus import var p0 = vector(path[0][-1]) t = var('t') if len(path[0]) > 2: B = (1-t)**3*vector(path[0][0])+3*t*(1-t)**2*vector(path[0][1])+3*t**2*(1-t)*vector(path[0][-2])+t**3*p0 G = P3D.parametric_plot3d(list(B), (0, 1), color=options['color'], aspect_ratio=options['aspect_ratio'], thickness=options['thickness'], opacity=options['opacity']) else: G = line3d([path[0][0], p0], color=options['color'], thickness=options['thickness'], opacity=options['opacity']) for curve in path[1:]: if len(curve) > 1: p1 = vector(curve[0]) p2 = vector(curve[-2]) p3 = vector(curve[-1]) B = (1-t)**3*p0+3*t*(1-t)**2*p1+3*t**2*(1-t)*p2+t**3*p3 G += P3D.parametric_plot3d(list(B), (0, 1), color=options['color'], aspect_ratio=options['aspect_ratio'], thickness=options['thickness'], opacity=options['opacity']) else: G += line3d([p0,curve[0]], color=options['color'], thickness=options['thickness'], opacity=options['opacity']) p0 = curve[-1] return G
472,480
def bezier3d(path, **options): """ Draws a 3-dimensional bezier path. Input is similar to bezier_path, but each point in the path and each control point is required to have 3 coordinates. INPUT: - ``path`` - a list of curves, which each is a list of points. See further detail below. - ``thickness`` - (default: 2) - ``color`` - a word that describes a color - ``opacity`` - (default: 1) if less than 1 then is transparent - ``aspect_ratio`` - (default:[1,1,1]) The path is a list of curves, and each curve is a list of points. Each point is a tuple (x,y,z). The first curve contains the endpoints as the first and last point in the list. All other curves assume a starting point given by the last entry in the preceding list, and take the last point in the list as their opposite endpoint. A curve can have 0, 1 or 2 control points listed between the endpoints. In the input example for path below, the first and second curves have 2 control points, the third has one, and the fourth has no control points: path = [[p1, c1, c2, p2], [c3, c4, p3], [c5, p4], [p5], ...] In the case of no control points, a straight line will be drawn between the two endpoints. If one control point is supplied, then the curve at each of the endpoints will be tangent to the line from that endpoint to the control point. Similarly, in the case of two control points, at each endpoint the curve will be tangent to the line connecting that endpoint with the control point immediately after or immediately preceding it in the list. So in our example above, the curve between p1 and p2 is tangent to the line through p1 and c1 at p1, and tangent to the line through p2 and c2 at p2. Similarly, the curve between p2 and p3 is tangent to line(p2,c3) at p2 and tangent to line(p3,c4) at p3. Curve(p3,p4) is tangent to line(p3,c5) at p3 and tangent to line(p4,c5) at p4. Curve(p4,p5) is a straight line. EXAMPLES: sage: path = [[(0,0,0),(.5,.1,.2),(.75,3,-1),(1,1,0)],[(.5,1,.2),(1,.5,0)],[(.7,.2,.5)]] sage: b = bezier3d(path, color='green') sage: b To construct a simple curve, create a list containing a single list: sage: path = [[(0,0,0),(1,0,0),(0,1,0),(0,1,1)]] sage: curve = bezier3d(path, thickness=5, color='blue') sage: curve """ import parametric_plot3d as P3D from sage.modules.free_module_element import vector from sage.calculus.calculus import var p0 = vector(path[0][-1]) t = var('t') if len(path[0]) > 2: B = (1-t)**3*vector(path[0][0])+3*t*(1-t)**2*vector(path[0][1])+3*t**2*(1-t)*vector(path[0][-2])+t**3*p0 G = P3D.parametric_plot3d(list(B), (0, 1), color=options['color'], aspect_ratio=options['aspect_ratio'], thickness=options['thickness'], opacity=options['opacity']) else: G = line3d([path[0][0], p0], color=options['color'], thickness=options['thickness'], opacity=options['opacity']) for curve in path[1:]: if len(curve) > 1: p1 = vector(curve[0]) p2 = vector(curve[-2]) p3 = vector(curve[-1]) B = (1-t)**3*p0+3*t*(1-t)**2*p1+3*t**2*(1-t)*p2+t**3*p3 G += P3D.parametric_plot3d(list(B), (0, 1), color=options['color'], aspect_ratio=options['aspect_ratio'], thickness=options['thickness'], opacity=options['opacity']) else: G += line3d([p0,curve[0]], color=options['color'], thickness=options['thickness'], opacity=options['opacity']) p0 = curve[-1] return G
def bezier3d(path, **options): """ Draws a 3-dimensional bezier path. Input is similar to bezier_path, but each point in the path and each control point is required to have 3 coordinates. INPUT: - ``path`` - a list of curves, which each is a list of points. See further detail below. - ``thickness`` - (default: 2) - ``color`` - a word that describes a color - ``opacity`` - (default: 1) if less than 1 then is transparent - ``aspect_ratio`` - (default:[1,1,1]) The path is a list of curves, and each curve is a list of points. Each point is a tuple (x,y,z). The first curve contains the endpoints as the first and last point in the list. All other curves assume a starting point given by the last entry in the preceding list, and take the last point in the list as their opposite endpoint. A curve can have 0, 1 or 2 control points listed between the endpoints. In the input example for path below, the first and second curves have 2 control points, the third has one, and the fourth has no control points: path = [[p1, c1, c2, p2], [c3, c4, p3], [c5, p4], [p5], ...] In the case of no control points, a straight line will be drawn between the two endpoints. If one control point is supplied, then the curve at each of the endpoints will be tangent to the line from that endpoint to the control point. Similarly, in the case of two control points, at each endpoint the curve will be tangent to the line connecting that endpoint with the control point immediately after or immediately preceding it in the list. So in our example above, the curve between p1 and p2 is tangent to the line through p1 and c1 at p1, and tangent to the line through p2 and c2 at p2. Similarly, the curve between p2 and p3 is tangent to line(p2,c3) at p2 and tangent to line(p3,c4) at p3. Curve(p3,p4) is tangent to line(p3,c5) at p3 and tangent to line(p4,c5) at p4. Curve(p4,p5) is a straight line. EXAMPLES:: sage: path = [[(0,0,0),(.5,.1,.2),(.75,3,-1),(1,1,0)],[(.5,1,.2),(1,.5,0)],[(.7,.2,.5)]] sage: b = bezier3d(path, color='green') sage: b To construct a simple curve, create a list containing a single list: sage: path = [[(0,0,0),(1,0,0),(0,1,0),(0,1,1)]] sage: curve = bezier3d(path, thickness=5, color='blue') sage: curve """ import parametric_plot3d as P3D from sage.modules.free_module_element import vector from sage.calculus.calculus import var p0 = vector(path[0][-1]) t = var('t') if len(path[0]) > 2: B = (1-t)**3*vector(path[0][0])+3*t*(1-t)**2*vector(path[0][1])+3*t**2*(1-t)*vector(path[0][-2])+t**3*p0 G = P3D.parametric_plot3d(list(B), (0, 1), color=options['color'], aspect_ratio=options['aspect_ratio'], thickness=options['thickness'], opacity=options['opacity']) else: G = line3d([path[0][0], p0], color=options['color'], thickness=options['thickness'], opacity=options['opacity']) for curve in path[1:]: if len(curve) > 1: p1 = vector(curve[0]) p2 = vector(curve[-2]) p3 = vector(curve[-1]) B = (1-t)**3*p0+3*t*(1-t)**2*p1+3*t**2*(1-t)*p2+t**3*p3 G += P3D.parametric_plot3d(list(B), (0, 1), color=options['color'], aspect_ratio=options['aspect_ratio'], thickness=options['thickness'], opacity=options['opacity']) else: G += line3d([p0,curve[0]], color=options['color'], thickness=options['thickness'], opacity=options['opacity']) p0 = curve[-1] return G
472,481
def bezier3d(path, **options): """ Draws a 3-dimensional bezier path. Input is similar to bezier_path, but each point in the path and each control point is required to have 3 coordinates. INPUT: - ``path`` - a list of curves, which each is a list of points. See further detail below. - ``thickness`` - (default: 2) - ``color`` - a word that describes a color - ``opacity`` - (default: 1) if less than 1 then is transparent - ``aspect_ratio`` - (default:[1,1,1]) The path is a list of curves, and each curve is a list of points. Each point is a tuple (x,y,z). The first curve contains the endpoints as the first and last point in the list. All other curves assume a starting point given by the last entry in the preceding list, and take the last point in the list as their opposite endpoint. A curve can have 0, 1 or 2 control points listed between the endpoints. In the input example for path below, the first and second curves have 2 control points, the third has one, and the fourth has no control points: path = [[p1, c1, c2, p2], [c3, c4, p3], [c5, p4], [p5], ...] In the case of no control points, a straight line will be drawn between the two endpoints. If one control point is supplied, then the curve at each of the endpoints will be tangent to the line from that endpoint to the control point. Similarly, in the case of two control points, at each endpoint the curve will be tangent to the line connecting that endpoint with the control point immediately after or immediately preceding it in the list. So in our example above, the curve between p1 and p2 is tangent to the line through p1 and c1 at p1, and tangent to the line through p2 and c2 at p2. Similarly, the curve between p2 and p3 is tangent to line(p2,c3) at p2 and tangent to line(p3,c4) at p3. Curve(p3,p4) is tangent to line(p3,c5) at p3 and tangent to line(p4,c5) at p4. Curve(p4,p5) is a straight line. EXAMPLES: sage: path = [[(0,0,0),(.5,.1,.2),(.75,3,-1),(1,1,0)],[(.5,1,.2),(1,.5,0)],[(.7,.2,.5)]] sage: b = bezier3d(path, color='green') sage: b To construct a simple curve, create a list containing a single list: sage: path = [[(0,0,0),(1,0,0),(0,1,0),(0,1,1)]] sage: curve = bezier3d(path, thickness=5, color='blue') sage: curve """ import parametric_plot3d as P3D from sage.modules.free_module_element import vector from sage.calculus.calculus import var p0 = vector(path[0][-1]) t = var('t') if len(path[0]) > 2: B = (1-t)**3*vector(path[0][0])+3*t*(1-t)**2*vector(path[0][1])+3*t**2*(1-t)*vector(path[0][-2])+t**3*p0 G = P3D.parametric_plot3d(list(B), (0, 1), color=options['color'], aspect_ratio=options['aspect_ratio'], thickness=options['thickness'], opacity=options['opacity']) else: G = line3d([path[0][0], p0], color=options['color'], thickness=options['thickness'], opacity=options['opacity']) for curve in path[1:]: if len(curve) > 1: p1 = vector(curve[0]) p2 = vector(curve[-2]) p3 = vector(curve[-1]) B = (1-t)**3*p0+3*t*(1-t)**2*p1+3*t**2*(1-t)*p2+t**3*p3 G += P3D.parametric_plot3d(list(B), (0, 1), color=options['color'], aspect_ratio=options['aspect_ratio'], thickness=options['thickness'], opacity=options['opacity']) else: G += line3d([p0,curve[0]], color=options['color'], thickness=options['thickness'], opacity=options['opacity']) p0 = curve[-1] return G
def bezier3d(path, **options): """ Draws a 3-dimensional bezier path. Input is similar to bezier_path, but each point in the path and each control point is required to have 3 coordinates. INPUT: - ``path`` - a list of curves, which each is a list of points. See further detail below. - ``thickness`` - (default: 2) - ``color`` - a word that describes a color - ``opacity`` - (default: 1) if less than 1 then is transparent - ``aspect_ratio`` - (default:[1,1,1]) The path is a list of curves, and each curve is a list of points. Each point is a tuple (x,y,z). The first curve contains the endpoints as the first and last point in the list. All other curves assume a starting point given by the last entry in the preceding list, and take the last point in the list as their opposite endpoint. A curve can have 0, 1 or 2 control points listed between the endpoints. In the input example for path below, the first and second curves have 2 control points, the third has one, and the fourth has no control points: path = [[p1, c1, c2, p2], [c3, c4, p3], [c5, p4], [p5], ...] In the case of no control points, a straight line will be drawn between the two endpoints. If one control point is supplied, then the curve at each of the endpoints will be tangent to the line from that endpoint to the control point. Similarly, in the case of two control points, at each endpoint the curve will be tangent to the line connecting that endpoint with the control point immediately after or immediately preceding it in the list. So in our example above, the curve between p1 and p2 is tangent to the line through p1 and c1 at p1, and tangent to the line through p2 and c2 at p2. Similarly, the curve between p2 and p3 is tangent to line(p2,c3) at p2 and tangent to line(p3,c4) at p3. Curve(p3,p4) is tangent to line(p3,c5) at p3 and tangent to line(p4,c5) at p4. Curve(p4,p5) is a straight line. EXAMPLES: sage: path = [[(0,0,0),(.5,.1,.2),(.75,3,-1),(1,1,0)],[(.5,1,.2),(1,.5,0)],[(.7,.2,.5)]] sage: b = bezier3d(path, color='green') sage: b To construct a simple curve, create a list containing a single list:: sage: path = [[(0,0,0),(1,0,0),(0,1,0),(0,1,1)]] sage: curve = bezier3d(path, thickness=5, color='blue') sage: curve """ import parametric_plot3d as P3D from sage.modules.free_module_element import vector from sage.calculus.calculus import var p0 = vector(path[0][-1]) t = var('t') if len(path[0]) > 2: B = (1-t)**3*vector(path[0][0])+3*t*(1-t)**2*vector(path[0][1])+3*t**2*(1-t)*vector(path[0][-2])+t**3*p0 G = P3D.parametric_plot3d(list(B), (0, 1), color=options['color'], aspect_ratio=options['aspect_ratio'], thickness=options['thickness'], opacity=options['opacity']) else: G = line3d([path[0][0], p0], color=options['color'], thickness=options['thickness'], opacity=options['opacity']) for curve in path[1:]: if len(curve) > 1: p1 = vector(curve[0]) p2 = vector(curve[-2]) p3 = vector(curve[-1]) B = (1-t)**3*p0+3*t*(1-t)**2*p1+3*t**2*(1-t)*p2+t**3*p3 G += P3D.parametric_plot3d(list(B), (0, 1), color=options['color'], aspect_ratio=options['aspect_ratio'], thickness=options['thickness'], opacity=options['opacity']) else: G += line3d([p0,curve[0]], color=options['color'], thickness=options['thickness'], opacity=options['opacity']) p0 = curve[-1] return G
472,482
def frame3d(lower_left, upper_right, **kwds): """ Draw a frame in 3D. Primarily used as a helper function for creating frames for 3D graphics viewing. INPUT: - ``lower_left`` - the lower left corner of the frame, as a list, tuple, or vector - ``upper_right`` - the upper right corner of the frame, as a list, tuple, or vector Type ``line3d.options`` for a dictionary of the default options for lines, which are also available. EXAMPLES: A frame:: sage: from sage.plot.plot3d.shapes2 import frame3d sage: frame3d([1,3,2],vector([2,5,4]),color='red') This is usually used for making an actual plot:: sage: y = var('y') sage: plot3d(sin(x^2+y^2),(x,0,pi),(y,0,pi)) """ x0,y0,z0 = lower_left x1,y1,z1 = upper_right L1 = line3d([(x0,y0,z0), (x0,y1,z0), (x1,y1,z0), (x1,y0,z0), (x0,y0,z0), # top square (x0,y0,z1), (x0,y1,z1), (x1,y1,z1), (x1,y0,z1), (x0,y0,z1)], # bottom square **kwds) # 3 additional lines joining top to bottom v2 = line3d([(x0,y1,z0), (x0,y1,z1)], **kwds) v3 = line3d([(x1,y0,z0), (x1,y0,z1)], **kwds) v4 = line3d([(x1,y1,z0), (x1,y1,z1)], **kwds) F = L1 + v2 + v3 + v4 F._set_extra_kwds(kwds) return F
def frame3d(lower_left, upper_right, **kwds): """ Draw a frame in 3-D. Primarily used as a helper function for creating frames for 3-D graphics viewing. INPUT: - ``lower_left`` - the lower left corner of the frame, as a list, tuple, or vector - ``upper_right`` - the upper right corner of the frame, as a list, tuple, or vector Type ``line3d.options`` for a dictionary of the default options for lines, which are also available. EXAMPLES: A frame:: sage: from sage.plot.plot3d.shapes2 import frame3d sage: frame3d([1,3,2],vector([2,5,4]),color='red') This is usually used for making an actual plot:: sage: y = var('y') sage: plot3d(sin(x^2+y^2),(x,0,pi),(y,0,pi)) """ x0,y0,z0 = lower_left x1,y1,z1 = upper_right L1 = line3d([(x0,y0,z0), (x0,y1,z0), (x1,y1,z0), (x1,y0,z0), (x0,y0,z0), # top square (x0,y0,z1), (x0,y1,z1), (x1,y1,z1), (x1,y0,z1), (x0,y0,z1)], # bottom square **kwds) # 3 additional lines joining top to bottom v2 = line3d([(x0,y1,z0), (x0,y1,z1)], **kwds) v3 = line3d([(x1,y0,z0), (x1,y0,z1)], **kwds) v4 = line3d([(x1,y1,z0), (x1,y1,z1)], **kwds) F = L1 + v2 + v3 + v4 F._set_extra_kwds(kwds) return F
472,483
def frame3d(lower_left, upper_right, **kwds): """ Draw a frame in 3D. Primarily used as a helper function for creating frames for 3D graphics viewing. INPUT: - ``lower_left`` - the lower left corner of the frame, as a list, tuple, or vector - ``upper_right`` - the upper right corner of the frame, as a list, tuple, or vector Type ``line3d.options`` for a dictionary of the default options for lines, which are also available. EXAMPLES: A frame:: sage: from sage.plot.plot3d.shapes2 import frame3d sage: frame3d([1,3,2],vector([2,5,4]),color='red') This is usually used for making an actual plot:: sage: y = var('y') sage: plot3d(sin(x^2+y^2),(x,0,pi),(y,0,pi)) """ x0,y0,z0 = lower_left x1,y1,z1 = upper_right L1 = line3d([(x0,y0,z0), (x0,y1,z0), (x1,y1,z0), (x1,y0,z0), (x0,y0,z0), # top square (x0,y0,z1), (x0,y1,z1), (x1,y1,z1), (x1,y0,z1), (x0,y0,z1)], # bottom square **kwds) # 3 additional lines joining top to bottom v2 = line3d([(x0,y1,z0), (x0,y1,z1)], **kwds) v3 = line3d([(x1,y0,z0), (x1,y0,z1)], **kwds) v4 = line3d([(x1,y1,z0), (x1,y1,z1)], **kwds) F = L1 + v2 + v3 + v4 F._set_extra_kwds(kwds) return F
def frame3d(lower_left, upper_right, **kwds): """ Draw a frame in 3D. Primarily used as a helper function for creating frames for 3D graphics viewing. INPUT: - ``lower_left`` - the lower left corner of the frame, as a list, tuple, or vector. - ``upper_right`` - the upper right corner of the frame, as a list, tuple, or vector. Type ``line3d.options`` for a dictionary of the default options for lines, which are also available. EXAMPLES: A frame:: sage: from sage.plot.plot3d.shapes2 import frame3d sage: frame3d([1,3,2],vector([2,5,4]),color='red') This is usually used for making an actual plot:: sage: y = var('y') sage: plot3d(sin(x^2+y^2),(x,0,pi),(y,0,pi)) """ x0,y0,z0 = lower_left x1,y1,z1 = upper_right L1 = line3d([(x0,y0,z0), (x0,y1,z0), (x1,y1,z0), (x1,y0,z0), (x0,y0,z0), # top square (x0,y0,z1), (x0,y1,z1), (x1,y1,z1), (x1,y0,z1), (x0,y0,z1)], # bottom square **kwds) # 3 additional lines joining top to bottom v2 = line3d([(x0,y1,z0), (x0,y1,z1)], **kwds) v3 = line3d([(x1,y0,z0), (x1,y0,z1)], **kwds) v4 = line3d([(x1,y1,z0), (x1,y1,z1)], **kwds) F = L1 + v2 + v3 + v4 F._set_extra_kwds(kwds) return F
472,484
def frame3d(lower_left, upper_right, **kwds): """ Draw a frame in 3D. Primarily used as a helper function for creating frames for 3D graphics viewing. INPUT: - ``lower_left`` - the lower left corner of the frame, as a list, tuple, or vector - ``upper_right`` - the upper right corner of the frame, as a list, tuple, or vector Type ``line3d.options`` for a dictionary of the default options for lines, which are also available. EXAMPLES: A frame:: sage: from sage.plot.plot3d.shapes2 import frame3d sage: frame3d([1,3,2],vector([2,5,4]),color='red') This is usually used for making an actual plot:: sage: y = var('y') sage: plot3d(sin(x^2+y^2),(x,0,pi),(y,0,pi)) """ x0,y0,z0 = lower_left x1,y1,z1 = upper_right L1 = line3d([(x0,y0,z0), (x0,y1,z0), (x1,y1,z0), (x1,y0,z0), (x0,y0,z0), # top square (x0,y0,z1), (x0,y1,z1), (x1,y1,z1), (x1,y0,z1), (x0,y0,z1)], # bottom square **kwds) # 3 additional lines joining top to bottom v2 = line3d([(x0,y1,z0), (x0,y1,z1)], **kwds) v3 = line3d([(x1,y0,z0), (x1,y0,z1)], **kwds) v4 = line3d([(x1,y1,z0), (x1,y1,z1)], **kwds) F = L1 + v2 + v3 + v4 F._set_extra_kwds(kwds) return F
def frame3d(lower_left, upper_right, **kwds): """ Draw a frame in 3D. Primarily used as a helper function for creating frames for 3D graphics viewing. INPUT: - ``lower_left`` - the lower left corner of the frame, as a list, tuple, or vector. - ``upper_right`` - the upper right corner of the frame, as a list, tuple, or vector. Type ``line3d.options`` for a dictionary of the default options for lines, which are also available. EXAMPLES: A frame:: sage: from sage.plot.plot3d.shapes2 import frame3d sage: frame3d([1,3,2],vector([2,5,4]),color='red') This is usually used for making an actual plot:: sage: y = var('y') sage: plot3d(sin(x^2+y^2),(x,0,pi),(y,0,pi)) """ x0,y0,z0 = lower_left x1,y1,z1 = upper_right L1 = line3d([(x0,y0,z0), (x0,y1,z0), (x1,y1,z0), (x1,y0,z0), (x0,y0,z0), # top square (x0,y0,z1), (x0,y1,z1), (x1,y1,z1), (x1,y0,z1), (x0,y0,z1)], # bottom square **kwds) # 3 additional lines joining top to bottom v2 = line3d([(x0,y1,z0), (x0,y1,z1)], **kwds) v3 = line3d([(x1,y0,z0), (x1,y0,z1)], **kwds) v4 = line3d([(x1,y1,z0), (x1,y1,z1)], **kwds) F = L1 + v2 + v3 + v4 F._set_extra_kwds(kwds) return F
472,485
def frame_labels(lower_left, upper_right, label_lower_left, label_upper_right, eps = 1, **kwds): """ Draw correct labels for a given frame in 3D. Primarily used as a helper function for creating frames for 3D graphics viewing - do not use directly unless you know what you are doing! INPUT: - ``lower_left`` - the lower left corner of the frame, as a list, tuple, or vector - ``upper_right`` - the upper right corner of the frame, as a list, tuple, or vector - ``label_lower_left`` - the label for the lower left corner of the frame, as a list, tuple, or vector. This label must actually have all coordinates less than the coordinates of the other label. - ``label_upper_right`` - the label for the upper right corner of the frame, as a list, tuple, or vector. This label must actually have all coordinates greater than the coordinates of the other label. - ``eps`` - (default: 1) a parameter for how far away from the frame to put the labels. Type ``line3d.options`` for a dictionary of the default options for lines, which are also available. EXAMPLES: We can use it directly:: sage: from sage.plot.plot3d.shapes2 import frame_labels sage: frame_labels([1,2,3],[4,5,6],[1,2,3],[4,5,6]) This is usually used for making an actual plot:: sage: y = var('y') sage: P = plot3d(sin(x^2+y^2),(x,0,pi),(y,0,pi)) sage: a,b = P._rescale_for_frame_aspect_ratio_and_zoom(1.0,[1,1,1],1) sage: F = frame_labels(a,b,*P._box_for_aspect_ratio("automatic",a,b)) sage: F.jmol_repr(F.default_render_params())[0] [['select atomno = 1', 'color atom [76,76,76]', 'label "0.0"']] TESTS:: sage: frame_labels([1,2,3],[4,5,6],[1,2,3],[1,3,4]) Traceback (most recent call last): ... ValueError: Ensure the upper right labels are above and to the right of the lower left labels. """ x0,y0,z0 = lower_left x1,y1,z1 = upper_right lx0,ly0,lz0 = label_lower_left lx1,ly1,lz1 = label_upper_right if (lx1 - lx0) <= 0 or (ly1 - ly0) <= 0 or (lz1 - lz0) <= 0: raise ValueError, "Ensure the upper right labels are above and to the right of the lower left labels." # Helper function for formatting the frame labels from math import log log10 = log(10) nd = lambda a: int(log(a)/log10) def fmt_string(a): b = a/2.0 if b >= 1: return "%.1f" n = max(0, 2 - nd(a/2.0)) return "%%.%sf"%n # Slightly faster than mean for this situation def avg(a,b): return (a+b)/2.0 color = (0.3,0.3,0.3) fmt = fmt_string(lx1 - lx0) T = Text(fmt%lx0, color=color).translate((x0,y0-eps,z0)) T += Text(fmt%avg(lx0,lx1), color=color).translate((avg(x0,x1),y0-eps,z0)) T += Text(fmt%lx1, color=color).translate((x1,y0-eps,z0)) fmt = fmt_string(ly1 - ly0) T += Text(fmt%ly0, color=color).translate((x1+eps,y0,z0)) T += Text(fmt%avg(ly0,ly1), color=color).translate((x1+eps,avg(y0,y1),z0)) T += Text(fmt%ly1, color=color).translate((x1+eps,y1,z0)) fmt = fmt_string(lz1 - lz0) T += Text(fmt%lz0, color=color).translate((x0-eps,y0,z0)) T += Text(fmt%avg(lz0,lz1), color=color).translate((x0-eps,y0,avg(z0,z1))) T += Text(fmt%lz1, color=color).translate((x0-eps,y0,z1)) return T
def frame_labels(lower_left, upper_right, label_lower_left, label_upper_right, eps = 1, **kwds): """ Draw correct labels for a given frame in 3-D. Primarily used as a helper function for creating frames for 3-D graphics viewing - do not use directly unless you know what you are doing! INPUT: - ``lower_left`` - the lower left corner of the frame, as a list, tuple, or vector - ``upper_right`` - the upper right corner of the frame, as a list, tuple, or vector - ``label_lower_left`` - the label for the lower left corner of the frame, as a list, tuple, or vector. This label must actually have all coordinates less than the coordinates of the other label. - ``label_upper_right`` - the label for the upper right corner of the frame, as a list, tuple, or vector. This label must actually have all coordinates greater than the coordinates of the other label. - ``eps`` - (default: 1) a parameter for how far away from the frame to put the labels. Type ``line3d.options`` for a dictionary of the default options for lines, which are also available. EXAMPLES: We can use it directly:: sage: from sage.plot.plot3d.shapes2 import frame_labels sage: frame_labels([1,2,3],[4,5,6],[1,2,3],[4,5,6]) This is usually used for making an actual plot:: sage: y = var('y') sage: P = plot3d(sin(x^2+y^2),(x,0,pi),(y,0,pi)) sage: a,b = P._rescale_for_frame_aspect_ratio_and_zoom(1.0,[1,1,1],1) sage: F = frame_labels(a,b,*P._box_for_aspect_ratio("automatic",a,b)) sage: F.jmol_repr(F.default_render_params())[0] [['select atomno = 1', 'color atom [76,76,76]', 'label "0.0"']] TESTS:: sage: frame_labels([1,2,3],[4,5,6],[1,2,3],[1,3,4]) Traceback (most recent call last): ... ValueError: Ensure the upper right labels are above and to the right of the lower left labels. """ x0,y0,z0 = lower_left x1,y1,z1 = upper_right lx0,ly0,lz0 = label_lower_left lx1,ly1,lz1 = label_upper_right if (lx1 - lx0) <= 0 or (ly1 - ly0) <= 0 or (lz1 - lz0) <= 0: raise ValueError, "Ensure the upper right labels are above and to the right of the lower left labels." # Helper function for formatting the frame labels from math import log log10 = log(10) nd = lambda a: int(log(a)/log10) def fmt_string(a): b = a/2.0 if b >= 1: return "%.1f" n = max(0, 2 - nd(a/2.0)) return "%%.%sf"%n # Slightly faster than mean for this situation def avg(a,b): return (a+b)/2.0 color = (0.3,0.3,0.3) fmt = fmt_string(lx1 - lx0) T = Text(fmt%lx0, color=color).translate((x0,y0-eps,z0)) T += Text(fmt%avg(lx0,lx1), color=color).translate((avg(x0,x1),y0-eps,z0)) T += Text(fmt%lx1, color=color).translate((x1,y0-eps,z0)) fmt = fmt_string(ly1 - ly0) T += Text(fmt%ly0, color=color).translate((x1+eps,y0,z0)) T += Text(fmt%avg(ly0,ly1), color=color).translate((x1+eps,avg(y0,y1),z0)) T += Text(fmt%ly1, color=color).translate((x1+eps,y1,z0)) fmt = fmt_string(lz1 - lz0) T += Text(fmt%lz0, color=color).translate((x0-eps,y0,z0)) T += Text(fmt%avg(lz0,lz1), color=color).translate((x0-eps,y0,avg(z0,z1))) T += Text(fmt%lz1, color=color).translate((x0-eps,y0,z1)) return T
472,486
def frame_labels(lower_left, upper_right, label_lower_left, label_upper_right, eps = 1, **kwds): """ Draw correct labels for a given frame in 3D. Primarily used as a helper function for creating frames for 3D graphics viewing - do not use directly unless you know what you are doing! INPUT: - ``lower_left`` - the lower left corner of the frame, as a list, tuple, or vector - ``upper_right`` - the upper right corner of the frame, as a list, tuple, or vector - ``label_lower_left`` - the label for the lower left corner of the frame, as a list, tuple, or vector. This label must actually have all coordinates less than the coordinates of the other label. - ``label_upper_right`` - the label for the upper right corner of the frame, as a list, tuple, or vector. This label must actually have all coordinates greater than the coordinates of the other label. - ``eps`` - (default: 1) a parameter for how far away from the frame to put the labels. Type ``line3d.options`` for a dictionary of the default options for lines, which are also available. EXAMPLES: We can use it directly:: sage: from sage.plot.plot3d.shapes2 import frame_labels sage: frame_labels([1,2,3],[4,5,6],[1,2,3],[4,5,6]) This is usually used for making an actual plot:: sage: y = var('y') sage: P = plot3d(sin(x^2+y^2),(x,0,pi),(y,0,pi)) sage: a,b = P._rescale_for_frame_aspect_ratio_and_zoom(1.0,[1,1,1],1) sage: F = frame_labels(a,b,*P._box_for_aspect_ratio("automatic",a,b)) sage: F.jmol_repr(F.default_render_params())[0] [['select atomno = 1', 'color atom [76,76,76]', 'label "0.0"']] TESTS:: sage: frame_labels([1,2,3],[4,5,6],[1,2,3],[1,3,4]) Traceback (most recent call last): ... ValueError: Ensure the upper right labels are above and to the right of the lower left labels. """ x0,y0,z0 = lower_left x1,y1,z1 = upper_right lx0,ly0,lz0 = label_lower_left lx1,ly1,lz1 = label_upper_right if (lx1 - lx0) <= 0 or (ly1 - ly0) <= 0 or (lz1 - lz0) <= 0: raise ValueError, "Ensure the upper right labels are above and to the right of the lower left labels." # Helper function for formatting the frame labels from math import log log10 = log(10) nd = lambda a: int(log(a)/log10) def fmt_string(a): b = a/2.0 if b >= 1: return "%.1f" n = max(0, 2 - nd(a/2.0)) return "%%.%sf"%n # Slightly faster than mean for this situation def avg(a,b): return (a+b)/2.0 color = (0.3,0.3,0.3) fmt = fmt_string(lx1 - lx0) T = Text(fmt%lx0, color=color).translate((x0,y0-eps,z0)) T += Text(fmt%avg(lx0,lx1), color=color).translate((avg(x0,x1),y0-eps,z0)) T += Text(fmt%lx1, color=color).translate((x1,y0-eps,z0)) fmt = fmt_string(ly1 - ly0) T += Text(fmt%ly0, color=color).translate((x1+eps,y0,z0)) T += Text(fmt%avg(ly0,ly1), color=color).translate((x1+eps,avg(y0,y1),z0)) T += Text(fmt%ly1, color=color).translate((x1+eps,y1,z0)) fmt = fmt_string(lz1 - lz0) T += Text(fmt%lz0, color=color).translate((x0-eps,y0,z0)) T += Text(fmt%avg(lz0,lz1), color=color).translate((x0-eps,y0,avg(z0,z1))) T += Text(fmt%lz1, color=color).translate((x0-eps,y0,z1)) return T
def frame_labels(lower_left, upper_right, label_lower_left, label_upper_right, eps = 1, **kwds): """ Draw correct labels for a given frame in 3D. Primarily used as a helper function for creating frames for 3D graphics viewing - do not use directly unless you know what you are doing! INPUT: - ``lower_left`` - the lower left corner of the frame, as a list, tuple, or vector. - ``upper_right`` - the upper right corner of the frame, as a list, tuple, or vector. - ``label_lower_left`` - the label for the lower left corner of the frame, as a list, tuple, or vector. This label must actually have all coordinates less than the coordinates of the other label. - ``label_upper_right`` - the label for the upper right corner of the frame, as a list, tuple, or vector. This label must actually have all coordinates greater than the coordinates of the other label. - ``eps`` - (default: 1) a parameter for how far away from the frame to put the labels. Type ``line3d.options`` for a dictionary of the default options for lines, which are also available. EXAMPLES: We can use it directly:: sage: from sage.plot.plot3d.shapes2 import frame_labels sage: frame_labels([1,2,3],[4,5,6],[1,2,3],[4,5,6]) This is usually used for making an actual plot:: sage: y = var('y') sage: P = plot3d(sin(x^2+y^2),(x,0,pi),(y,0,pi)) sage: a,b = P._rescale_for_frame_aspect_ratio_and_zoom(1.0,[1,1,1],1) sage: F = frame_labels(a,b,*P._box_for_aspect_ratio("automatic",a,b)) sage: F.jmol_repr(F.default_render_params())[0] [['select atomno = 1', 'color atom [76,76,76]', 'label "0.0"']] TESTS:: sage: frame_labels([1,2,3],[4,5,6],[1,2,3],[1,3,4]) Traceback (most recent call last): ... ValueError: Ensure the upper right labels are above and to the right of the lower left labels. """ x0,y0,z0 = lower_left x1,y1,z1 = upper_right lx0,ly0,lz0 = label_lower_left lx1,ly1,lz1 = label_upper_right if (lx1 - lx0) <= 0 or (ly1 - ly0) <= 0 or (lz1 - lz0) <= 0: raise ValueError, "Ensure the upper right labels are above and to the right of the lower left labels." # Helper function for formatting the frame labels from math import log log10 = log(10) nd = lambda a: int(log(a)/log10) def fmt_string(a): b = a/2.0 if b >= 1: return "%.1f" n = max(0, 2 - nd(a/2.0)) return "%%.%sf"%n # Slightly faster than mean for this situation def avg(a,b): return (a+b)/2.0 color = (0.3,0.3,0.3) fmt = fmt_string(lx1 - lx0) T = Text(fmt%lx0, color=color).translate((x0,y0-eps,z0)) T += Text(fmt%avg(lx0,lx1), color=color).translate((avg(x0,x1),y0-eps,z0)) T += Text(fmt%lx1, color=color).translate((x1,y0-eps,z0)) fmt = fmt_string(ly1 - ly0) T += Text(fmt%ly0, color=color).translate((x1+eps,y0,z0)) T += Text(fmt%avg(ly0,ly1), color=color).translate((x1+eps,avg(y0,y1),z0)) T += Text(fmt%ly1, color=color).translate((x1+eps,y1,z0)) fmt = fmt_string(lz1 - lz0) T += Text(fmt%lz0, color=color).translate((x0-eps,y0,z0)) T += Text(fmt%avg(lz0,lz1), color=color).translate((x0-eps,y0,avg(z0,z1))) T += Text(fmt%lz1, color=color).translate((x0-eps,y0,z1)) return T
472,487
def frame_labels(lower_left, upper_right, label_lower_left, label_upper_right, eps = 1, **kwds): """ Draw correct labels for a given frame in 3D. Primarily used as a helper function for creating frames for 3D graphics viewing - do not use directly unless you know what you are doing! INPUT: - ``lower_left`` - the lower left corner of the frame, as a list, tuple, or vector - ``upper_right`` - the upper right corner of the frame, as a list, tuple, or vector - ``label_lower_left`` - the label for the lower left corner of the frame, as a list, tuple, or vector. This label must actually have all coordinates less than the coordinates of the other label. - ``label_upper_right`` - the label for the upper right corner of the frame, as a list, tuple, or vector. This label must actually have all coordinates greater than the coordinates of the other label. - ``eps`` - (default: 1) a parameter for how far away from the frame to put the labels. Type ``line3d.options`` for a dictionary of the default options for lines, which are also available. EXAMPLES: We can use it directly:: sage: from sage.plot.plot3d.shapes2 import frame_labels sage: frame_labels([1,2,3],[4,5,6],[1,2,3],[4,5,6]) This is usually used for making an actual plot:: sage: y = var('y') sage: P = plot3d(sin(x^2+y^2),(x,0,pi),(y,0,pi)) sage: a,b = P._rescale_for_frame_aspect_ratio_and_zoom(1.0,[1,1,1],1) sage: F = frame_labels(a,b,*P._box_for_aspect_ratio("automatic",a,b)) sage: F.jmol_repr(F.default_render_params())[0] [['select atomno = 1', 'color atom [76,76,76]', 'label "0.0"']] TESTS:: sage: frame_labels([1,2,3],[4,5,6],[1,2,3],[1,3,4]) Traceback (most recent call last): ... ValueError: Ensure the upper right labels are above and to the right of the lower left labels. """ x0,y0,z0 = lower_left x1,y1,z1 = upper_right lx0,ly0,lz0 = label_lower_left lx1,ly1,lz1 = label_upper_right if (lx1 - lx0) <= 0 or (ly1 - ly0) <= 0 or (lz1 - lz0) <= 0: raise ValueError, "Ensure the upper right labels are above and to the right of the lower left labels." # Helper function for formatting the frame labels from math import log log10 = log(10) nd = lambda a: int(log(a)/log10) def fmt_string(a): b = a/2.0 if b >= 1: return "%.1f" n = max(0, 2 - nd(a/2.0)) return "%%.%sf"%n # Slightly faster than mean for this situation def avg(a,b): return (a+b)/2.0 color = (0.3,0.3,0.3) fmt = fmt_string(lx1 - lx0) T = Text(fmt%lx0, color=color).translate((x0,y0-eps,z0)) T += Text(fmt%avg(lx0,lx1), color=color).translate((avg(x0,x1),y0-eps,z0)) T += Text(fmt%lx1, color=color).translate((x1,y0-eps,z0)) fmt = fmt_string(ly1 - ly0) T += Text(fmt%ly0, color=color).translate((x1+eps,y0,z0)) T += Text(fmt%avg(ly0,ly1), color=color).translate((x1+eps,avg(y0,y1),z0)) T += Text(fmt%ly1, color=color).translate((x1+eps,y1,z0)) fmt = fmt_string(lz1 - lz0) T += Text(fmt%lz0, color=color).translate((x0-eps,y0,z0)) T += Text(fmt%avg(lz0,lz1), color=color).translate((x0-eps,y0,avg(z0,z1))) T += Text(fmt%lz1, color=color).translate((x0-eps,y0,z1)) return T
def frame_labels(lower_left, upper_right, label_lower_left, label_upper_right, eps = 1, **kwds): """ Draw correct labels for a given frame in 3D. Primarily used as a helper function for creating frames for 3D graphics viewing - do not use directly unless you know what you are doing! INPUT: - ``lower_left`` - the lower left corner of the frame, as a list, tuple, or vector. - ``upper_right`` - the upper right corner of the frame, as a list, tuple, or vector. - ``label_lower_left`` - the label for the lower left corner of the frame, as a list, tuple, or vector. This label must actually have all coordinates less than the coordinates of the other label. - ``label_upper_right`` - the label for the upper right corner of the frame, as a list, tuple, or vector. This label must actually have all coordinates greater than the coordinates of the other label. - ``eps`` - (default: 1) a parameter for how far away from the frame to put the labels. Type ``line3d.options`` for a dictionary of the default options for lines, which are also available. EXAMPLES: We can use it directly:: sage: from sage.plot.plot3d.shapes2 import frame_labels sage: frame_labels([1,2,3],[4,5,6],[1,2,3],[4,5,6]) This is usually used for making an actual plot:: sage: y = var('y') sage: P = plot3d(sin(x^2+y^2),(x,0,pi),(y,0,pi)) sage: a,b = P._rescale_for_frame_aspect_ratio_and_zoom(1.0,[1,1,1],1) sage: F = frame_labels(a,b,*P._box_for_aspect_ratio("automatic",a,b)) sage: F.jmol_repr(F.default_render_params())[0] [['select atomno = 1', 'color atom [76,76,76]', 'label "0.0"']] TESTS:: sage: frame_labels([1,2,3],[4,5,6],[1,2,3],[1,3,4]) Traceback (most recent call last): ... ValueError: Ensure the upper right labels are above and to the right of the lower left labels. """ x0,y0,z0 = lower_left x1,y1,z1 = upper_right lx0,ly0,lz0 = label_lower_left lx1,ly1,lz1 = label_upper_right if (lx1 - lx0) <= 0 or (ly1 - ly0) <= 0 or (lz1 - lz0) <= 0: raise ValueError, "Ensure the upper right labels are above and to the right of the lower left labels." # Helper function for formatting the frame labels from math import log log10 = log(10) nd = lambda a: int(log(a)/log10) def fmt_string(a): b = a/2.0 if b >= 1: return "%.1f" n = max(0, 2 - nd(a/2.0)) return "%%.%sf"%n # Slightly faster than mean for this situation def avg(a,b): return (a+b)/2.0 color = (0.3,0.3,0.3) fmt = fmt_string(lx1 - lx0) T = Text(fmt%lx0, color=color).translate((x0,y0-eps,z0)) T += Text(fmt%avg(lx0,lx1), color=color).translate((avg(x0,x1),y0-eps,z0)) T += Text(fmt%lx1, color=color).translate((x1,y0-eps,z0)) fmt = fmt_string(ly1 - ly0) T += Text(fmt%ly0, color=color).translate((x1+eps,y0,z0)) T += Text(fmt%avg(ly0,ly1), color=color).translate((x1+eps,avg(y0,y1),z0)) T += Text(fmt%ly1, color=color).translate((x1+eps,y1,z0)) fmt = fmt_string(lz1 - lz0) T += Text(fmt%lz0, color=color).translate((x0-eps,y0,z0)) T += Text(fmt%avg(lz0,lz1), color=color).translate((x0-eps,y0,avg(z0,z1))) T += Text(fmt%lz1, color=color).translate((x0-eps,y0,z1)) return T
472,488
def frame_labels(lower_left, upper_right, label_lower_left, label_upper_right, eps = 1, **kwds): """ Draw correct labels for a given frame in 3D. Primarily used as a helper function for creating frames for 3D graphics viewing - do not use directly unless you know what you are doing! INPUT: - ``lower_left`` - the lower left corner of the frame, as a list, tuple, or vector - ``upper_right`` - the upper right corner of the frame, as a list, tuple, or vector - ``label_lower_left`` - the label for the lower left corner of the frame, as a list, tuple, or vector. This label must actually have all coordinates less than the coordinates of the other label. - ``label_upper_right`` - the label for the upper right corner of the frame, as a list, tuple, or vector. This label must actually have all coordinates greater than the coordinates of the other label. - ``eps`` - (default: 1) a parameter for how far away from the frame to put the labels. Type ``line3d.options`` for a dictionary of the default options for lines, which are also available. EXAMPLES: We can use it directly:: sage: from sage.plot.plot3d.shapes2 import frame_labels sage: frame_labels([1,2,3],[4,5,6],[1,2,3],[4,5,6]) This is usually used for making an actual plot:: sage: y = var('y') sage: P = plot3d(sin(x^2+y^2),(x,0,pi),(y,0,pi)) sage: a,b = P._rescale_for_frame_aspect_ratio_and_zoom(1.0,[1,1,1],1) sage: F = frame_labels(a,b,*P._box_for_aspect_ratio("automatic",a,b)) sage: F.jmol_repr(F.default_render_params())[0] [['select atomno = 1', 'color atom [76,76,76]', 'label "0.0"']] TESTS:: sage: frame_labels([1,2,3],[4,5,6],[1,2,3],[1,3,4]) Traceback (most recent call last): ... ValueError: Ensure the upper right labels are above and to the right of the lower left labels. """ x0,y0,z0 = lower_left x1,y1,z1 = upper_right lx0,ly0,lz0 = label_lower_left lx1,ly1,lz1 = label_upper_right if (lx1 - lx0) <= 0 or (ly1 - ly0) <= 0 or (lz1 - lz0) <= 0: raise ValueError, "Ensure the upper right labels are above and to the right of the lower left labels." # Helper function for formatting the frame labels from math import log log10 = log(10) nd = lambda a: int(log(a)/log10) def fmt_string(a): b = a/2.0 if b >= 1: return "%.1f" n = max(0, 2 - nd(a/2.0)) return "%%.%sf"%n # Slightly faster than mean for this situation def avg(a,b): return (a+b)/2.0 color = (0.3,0.3,0.3) fmt = fmt_string(lx1 - lx0) T = Text(fmt%lx0, color=color).translate((x0,y0-eps,z0)) T += Text(fmt%avg(lx0,lx1), color=color).translate((avg(x0,x1),y0-eps,z0)) T += Text(fmt%lx1, color=color).translate((x1,y0-eps,z0)) fmt = fmt_string(ly1 - ly0) T += Text(fmt%ly0, color=color).translate((x1+eps,y0,z0)) T += Text(fmt%avg(ly0,ly1), color=color).translate((x1+eps,avg(y0,y1),z0)) T += Text(fmt%ly1, color=color).translate((x1+eps,y1,z0)) fmt = fmt_string(lz1 - lz0) T += Text(fmt%lz0, color=color).translate((x0-eps,y0,z0)) T += Text(fmt%avg(lz0,lz1), color=color).translate((x0-eps,y0,avg(z0,z1))) T += Text(fmt%lz1, color=color).translate((x0-eps,y0,z1)) return T
def frame_labels(lower_left, upper_right, label_lower_left, label_upper_right, eps = 1, **kwds): """ Draw correct labels for a given frame in 3D. Primarily used as a helper function for creating frames for 3D graphics viewing - do not use directly unless you know what you are doing! INPUT: - ``lower_left`` - the lower left corner of the frame, as a list, tuple, or vector - ``upper_right`` - the upper right corner of the frame, as a list, tuple, or vector - ``label_lower_left`` - the label for the lower left corner of the frame, as a list, tuple, or vector. This label must actually have all coordinates less than the coordinates of the other label. - ``label_upper_right`` - the label for the upper right corner of the frame, as a list, tuple, or vector. This label must actually have all coordinates greater than the coordinates of the other label. - ``eps`` - (default: 1) a parameter for how far away from the frame to put the labels. Type ``line3d.options`` for a dictionary of the default options for lines, which are also available. EXAMPLES: We can use it directly:: sage: from sage.plot.plot3d.shapes2 import frame_labels sage: frame_labels([1,2,3],[4,5,6],[1,2,3],[4,5,6]) This is usually used for making an actual plot:: sage: y = var('y') sage: P = plot3d(sin(x^2+y^2),(x,0,pi),(y,0,pi)) sage: a,b = P._rescale_for_frame_aspect_ratio_and_zoom(1.0,[1,1,1],1) sage: F = frame_labels(a,b,*P._box_for_aspect_ratio("automatic",a,b)) sage: F.jmol_repr(F.default_render_params())[0] [['select atomno = 1', 'color atom [76,76,76]', 'label "0.0"']] TESTS:: sage: frame_labels([1,2,3],[4,5,6],[1,2,3],[1,3,4]) Traceback (most recent call last): ... ValueError: Ensure the upper right labels are above and to the right of the lower left labels. """ x0,y0,z0 = lower_left x1,y1,z1 = upper_right lx0,ly0,lz0 = label_lower_left lx1,ly1,lz1 = label_upper_right if (lx1 - lx0) <= 0 or (ly1 - ly0) <= 0 or (lz1 - lz0) <= 0: raise ValueError("Ensure the upper right labels are above and to the right of the lower left labels.") # Helper function for formatting the frame labels from math import log log10 = log(10) nd = lambda a: int(log(a)/log10) def fmt_string(a): b = a/2.0 if b >= 1: return "%.1f" n = max(0, 2 - nd(a/2.0)) return "%%.%sf"%n # Slightly faster than mean for this situation def avg(a,b): return (a+b)/2.0 color = (0.3,0.3,0.3) fmt = fmt_string(lx1 - lx0) T = Text(fmt%lx0, color=color).translate((x0,y0-eps,z0)) T += Text(fmt%avg(lx0,lx1), color=color).translate((avg(x0,x1),y0-eps,z0)) T += Text(fmt%lx1, color=color).translate((x1,y0-eps,z0)) fmt = fmt_string(ly1 - ly0) T += Text(fmt%ly0, color=color).translate((x1+eps,y0,z0)) T += Text(fmt%avg(ly0,ly1), color=color).translate((x1+eps,avg(y0,y1),z0)) T += Text(fmt%ly1, color=color).translate((x1+eps,y1,z0)) fmt = fmt_string(lz1 - lz0) T += Text(fmt%lz0, color=color).translate((x0-eps,y0,z0)) T += Text(fmt%avg(lz0,lz1), color=color).translate((x0-eps,y0,avg(z0,z1))) T += Text(fmt%lz1, color=color).translate((x0-eps,y0,z1)) return T
472,489
def ruler(start, end, ticks=4, sub_ticks=4, absolute=False, snap=False, **kwds): """ Draw a ruler in 3D, with major and minor ticks. INPUT: - ``start`` - the beginning of the ruler, as a list, tuple, or vector - ``end`` - the end of the ruler, as a list, tuple, or vector - ``ticks`` - (default: 4) the number of major ticks shown on the ruler - ``sub_ticks`` - (default: 4) the number of shown subdivisions between each major tick - ``absolute`` - (default: False) if True, makes a huge ruler in the direction of an axis - ``snap`` - (default: False) if True, snaps to an implied grid Type ``line3d.options`` for a dictionary of the default options for lines which are also available. EXAMPLES: A ruler:: sage: from sage.plot.plot3d.shapes2 import ruler sage: R = ruler([1,2,3],vector([2,3,4])); R A ruler with some options:: sage: R = ruler([1,2,3],vector([2,3,4]),ticks=6, sub_ticks=2, color='red'); R The keyword ``snap`` makes the ticks not necessarily coincide with the ruler:: sage: ruler([1,2,3],vector([1,2,4]),snap=True) The keyword ``absolute`` makes a huge ruler in one of the axis directions:: sage: ruler([1,2,3],vector([1,2,4]),absolute=True) TESTS:: sage: ruler([1,2,3],vector([1,3,4]),absolute=True) Traceback (most recent call last): ... ValueError: Absolute rulers only valid for axis-aligned paths """ start = vector(RDF, start) end = vector(RDF, end) dir = end - start dist = math.sqrt(dir.dot_product(dir)) dir /= dist one_tick = dist/ticks * 1.414 unit = 10 ** math.floor(math.log(dist/ticks, 10)) if unit * 5 < one_tick: unit *= 5 elif unit * 2 < one_tick: unit *= 2 if dir[0]: tick = dir.cross_product(vector(RDF, (0,0,-dist/30))) elif dir[1]: tick = dir.cross_product(vector(RDF, (0,0,dist/30))) else: tick = vector(RDF, (dist/30,0,0)) if snap: for i in range(3): start[i] = unit * math.floor(start[i]/unit + 1e-5) end[i] = unit * math.ceil(end[i]/unit - 1e-5) if absolute: if dir[0]*dir[1] or dir[1]*dir[2] or dir[0]*dir[2]: raise ValueError, "Absolute rulers only valid for axis-aligned paths" m = max(dir[0], dir[1], dir[2]) if dir[0] == m: off = start[0] elif dir[1] == m: off = start[1] else: off = start[2] first_tick = unit * math.ceil(off/unit - 1e-5) - off else: off = 0 first_tick = 0 ruler = shapes.LineSegment(start, end, **kwds) for k in range(1, int(sub_ticks * first_tick/unit)): P = start + dir*(k*unit/sub_ticks) ruler += shapes.LineSegment(P, P + tick/2, **kwds) for d in srange(first_tick, dist + unit/(sub_ticks+1), unit): P = start + dir*d ruler += shapes.LineSegment(P, P + tick, **kwds) ruler += shapes.Text(str(d+off), **kwds).translate(P - tick) if dist - d < unit: sub_ticks = int(sub_ticks * (dist - d)/unit) for k in range(1, sub_ticks): P += dir * (unit/sub_ticks) ruler += shapes.LineSegment(P, P + tick/2, **kwds) return ruler
def ruler(start, end, ticks=4, sub_ticks=4, absolute=False, snap=False, **kwds): """ Draw a ruler in 3-D, with major and minor ticks. INPUT: - ``start`` - the beginning of the ruler, as a list, tuple, or vector - ``end`` - the end of the ruler, as a list, tuple, or vector - ``ticks`` - (default: 4) the number of major ticks shown on the ruler - ``sub_ticks`` - (default: 4) the number of shown subdivisions between each major tick - ``absolute`` - (default: False) if True, makes a huge ruler in the direction of an axis - ``snap`` - (default: False) if True, snaps to an implied grid Type ``line3d.options`` for a dictionary of the default options for lines which are also available. EXAMPLES: A ruler:: sage: from sage.plot.plot3d.shapes2 import ruler sage: R = ruler([1,2,3],vector([2,3,4])); R A ruler with some options:: sage: R = ruler([1,2,3],vector([2,3,4]),ticks=6, sub_ticks=2, color='red'); R The keyword ``snap`` makes the ticks not necessarily coincide with the ruler:: sage: ruler([1,2,3],vector([1,2,4]),snap=True) The keyword ``absolute`` makes a huge ruler in one of the axis directions:: sage: ruler([1,2,3],vector([1,2,4]),absolute=True) TESTS:: sage: ruler([1,2,3],vector([1,3,4]),absolute=True) Traceback (most recent call last): ... ValueError: Absolute rulers only valid for axis-aligned paths """ start = vector(RDF, start) end = vector(RDF, end) dir = end - start dist = math.sqrt(dir.dot_product(dir)) dir /= dist one_tick = dist/ticks * 1.414 unit = 10 ** math.floor(math.log(dist/ticks, 10)) if unit * 5 < one_tick: unit *= 5 elif unit * 2 < one_tick: unit *= 2 if dir[0]: tick = dir.cross_product(vector(RDF, (0,0,-dist/30))) elif dir[1]: tick = dir.cross_product(vector(RDF, (0,0,dist/30))) else: tick = vector(RDF, (dist/30,0,0)) if snap: for i in range(3): start[i] = unit * math.floor(start[i]/unit + 1e-5) end[i] = unit * math.ceil(end[i]/unit - 1e-5) if absolute: if dir[0]*dir[1] or dir[1]*dir[2] or dir[0]*dir[2]: raise ValueError, "Absolute rulers only valid for axis-aligned paths" m = max(dir[0], dir[1], dir[2]) if dir[0] == m: off = start[0] elif dir[1] == m: off = start[1] else: off = start[2] first_tick = unit * math.ceil(off/unit - 1e-5) - off else: off = 0 first_tick = 0 ruler = shapes.LineSegment(start, end, **kwds) for k in range(1, int(sub_ticks * first_tick/unit)): P = start + dir*(k*unit/sub_ticks) ruler += shapes.LineSegment(P, P + tick/2, **kwds) for d in srange(first_tick, dist + unit/(sub_ticks+1), unit): P = start + dir*d ruler += shapes.LineSegment(P, P + tick, **kwds) ruler += shapes.Text(str(d+off), **kwds).translate(P - tick) if dist - d < unit: sub_ticks = int(sub_ticks * (dist - d)/unit) for k in range(1, sub_ticks): P += dir * (unit/sub_ticks) ruler += shapes.LineSegment(P, P + tick/2, **kwds) return ruler
472,490
def ruler(start, end, ticks=4, sub_ticks=4, absolute=False, snap=False, **kwds): """ Draw a ruler in 3D, with major and minor ticks. INPUT: - ``start`` - the beginning of the ruler, as a list, tuple, or vector - ``end`` - the end of the ruler, as a list, tuple, or vector - ``ticks`` - (default: 4) the number of major ticks shown on the ruler - ``sub_ticks`` - (default: 4) the number of shown subdivisions between each major tick - ``absolute`` - (default: False) if True, makes a huge ruler in the direction of an axis - ``snap`` - (default: False) if True, snaps to an implied grid Type ``line3d.options`` for a dictionary of the default options for lines which are also available. EXAMPLES: A ruler:: sage: from sage.plot.plot3d.shapes2 import ruler sage: R = ruler([1,2,3],vector([2,3,4])); R A ruler with some options:: sage: R = ruler([1,2,3],vector([2,3,4]),ticks=6, sub_ticks=2, color='red'); R The keyword ``snap`` makes the ticks not necessarily coincide with the ruler:: sage: ruler([1,2,3],vector([1,2,4]),snap=True) The keyword ``absolute`` makes a huge ruler in one of the axis directions:: sage: ruler([1,2,3],vector([1,2,4]),absolute=True) TESTS:: sage: ruler([1,2,3],vector([1,3,4]),absolute=True) Traceback (most recent call last): ... ValueError: Absolute rulers only valid for axis-aligned paths """ start = vector(RDF, start) end = vector(RDF, end) dir = end - start dist = math.sqrt(dir.dot_product(dir)) dir /= dist one_tick = dist/ticks * 1.414 unit = 10 ** math.floor(math.log(dist/ticks, 10)) if unit * 5 < one_tick: unit *= 5 elif unit * 2 < one_tick: unit *= 2 if dir[0]: tick = dir.cross_product(vector(RDF, (0,0,-dist/30))) elif dir[1]: tick = dir.cross_product(vector(RDF, (0,0,dist/30))) else: tick = vector(RDF, (dist/30,0,0)) if snap: for i in range(3): start[i] = unit * math.floor(start[i]/unit + 1e-5) end[i] = unit * math.ceil(end[i]/unit - 1e-5) if absolute: if dir[0]*dir[1] or dir[1]*dir[2] or dir[0]*dir[2]: raise ValueError, "Absolute rulers only valid for axis-aligned paths" m = max(dir[0], dir[1], dir[2]) if dir[0] == m: off = start[0] elif dir[1] == m: off = start[1] else: off = start[2] first_tick = unit * math.ceil(off/unit - 1e-5) - off else: off = 0 first_tick = 0 ruler = shapes.LineSegment(start, end, **kwds) for k in range(1, int(sub_ticks * first_tick/unit)): P = start + dir*(k*unit/sub_ticks) ruler += shapes.LineSegment(P, P + tick/2, **kwds) for d in srange(first_tick, dist + unit/(sub_ticks+1), unit): P = start + dir*d ruler += shapes.LineSegment(P, P + tick, **kwds) ruler += shapes.Text(str(d+off), **kwds).translate(P - tick) if dist - d < unit: sub_ticks = int(sub_ticks * (dist - d)/unit) for k in range(1, sub_ticks): P += dir * (unit/sub_ticks) ruler += shapes.LineSegment(P, P + tick/2, **kwds) return ruler
def ruler(start, end, ticks=4, sub_ticks=4, absolute=False, snap=False, **kwds): """ Draw a ruler in 3D, with major and minor ticks. INPUT: - ``start`` - the beginning of the ruler, as a list, tuple, or vector. - ``end`` - the end of the ruler, as a list, tuple, or vector. - ``ticks`` - (default: 4) the number of major ticks shown on the ruler - ``sub_ticks`` - (default: 4) the number of shown subdivisions between each major tick - ``absolute`` - (default: False) if True, makes a huge ruler in the direction of an axis - ``snap`` - (default: False) if True, snaps to an implied grid Type ``line3d.options`` for a dictionary of the default options for lines which are also available. EXAMPLES: A ruler:: sage: from sage.plot.plot3d.shapes2 import ruler sage: R = ruler([1,2,3],vector([2,3,4])); R A ruler with some options:: sage: R = ruler([1,2,3],vector([2,3,4]),ticks=6, sub_ticks=2, color='red'); R The keyword ``snap`` makes the ticks not necessarily coincide with the ruler:: sage: ruler([1,2,3],vector([1,2,4]),snap=True) The keyword ``absolute`` makes a huge ruler in one of the axis directions:: sage: ruler([1,2,3],vector([1,2,4]),absolute=True) TESTS:: sage: ruler([1,2,3],vector([1,3,4]),absolute=True) Traceback (most recent call last): ... ValueError: Absolute rulers only valid for axis-aligned paths """ start = vector(RDF, start) end = vector(RDF, end) dir = end - start dist = math.sqrt(dir.dot_product(dir)) dir /= dist one_tick = dist/ticks * 1.414 unit = 10 ** math.floor(math.log(dist/ticks, 10)) if unit * 5 < one_tick: unit *= 5 elif unit * 2 < one_tick: unit *= 2 if dir[0]: tick = dir.cross_product(vector(RDF, (0,0,-dist/30))) elif dir[1]: tick = dir.cross_product(vector(RDF, (0,0,dist/30))) else: tick = vector(RDF, (dist/30,0,0)) if snap: for i in range(3): start[i] = unit * math.floor(start[i]/unit + 1e-5) end[i] = unit * math.ceil(end[i]/unit - 1e-5) if absolute: if dir[0]*dir[1] or dir[1]*dir[2] or dir[0]*dir[2]: raise ValueError, "Absolute rulers only valid for axis-aligned paths" m = max(dir[0], dir[1], dir[2]) if dir[0] == m: off = start[0] elif dir[1] == m: off = start[1] else: off = start[2] first_tick = unit * math.ceil(off/unit - 1e-5) - off else: off = 0 first_tick = 0 ruler = shapes.LineSegment(start, end, **kwds) for k in range(1, int(sub_ticks * first_tick/unit)): P = start + dir*(k*unit/sub_ticks) ruler += shapes.LineSegment(P, P + tick/2, **kwds) for d in srange(first_tick, dist + unit/(sub_ticks+1), unit): P = start + dir*d ruler += shapes.LineSegment(P, P + tick, **kwds) ruler += shapes.Text(str(d+off), **kwds).translate(P - tick) if dist - d < unit: sub_ticks = int(sub_ticks * (dist - d)/unit) for k in range(1, sub_ticks): P += dir * (unit/sub_ticks) ruler += shapes.LineSegment(P, P + tick/2, **kwds) return ruler
472,491
def ruler(start, end, ticks=4, sub_ticks=4, absolute=False, snap=False, **kwds): """ Draw a ruler in 3D, with major and minor ticks. INPUT: - ``start`` - the beginning of the ruler, as a list, tuple, or vector - ``end`` - the end of the ruler, as a list, tuple, or vector - ``ticks`` - (default: 4) the number of major ticks shown on the ruler - ``sub_ticks`` - (default: 4) the number of shown subdivisions between each major tick - ``absolute`` - (default: False) if True, makes a huge ruler in the direction of an axis - ``snap`` - (default: False) if True, snaps to an implied grid Type ``line3d.options`` for a dictionary of the default options for lines which are also available. EXAMPLES: A ruler:: sage: from sage.plot.plot3d.shapes2 import ruler sage: R = ruler([1,2,3],vector([2,3,4])); R A ruler with some options:: sage: R = ruler([1,2,3],vector([2,3,4]),ticks=6, sub_ticks=2, color='red'); R The keyword ``snap`` makes the ticks not necessarily coincide with the ruler:: sage: ruler([1,2,3],vector([1,2,4]),snap=True) The keyword ``absolute`` makes a huge ruler in one of the axis directions:: sage: ruler([1,2,3],vector([1,2,4]),absolute=True) TESTS:: sage: ruler([1,2,3],vector([1,3,4]),absolute=True) Traceback (most recent call last): ... ValueError: Absolute rulers only valid for axis-aligned paths """ start = vector(RDF, start) end = vector(RDF, end) dir = end - start dist = math.sqrt(dir.dot_product(dir)) dir /= dist one_tick = dist/ticks * 1.414 unit = 10 ** math.floor(math.log(dist/ticks, 10)) if unit * 5 < one_tick: unit *= 5 elif unit * 2 < one_tick: unit *= 2 if dir[0]: tick = dir.cross_product(vector(RDF, (0,0,-dist/30))) elif dir[1]: tick = dir.cross_product(vector(RDF, (0,0,dist/30))) else: tick = vector(RDF, (dist/30,0,0)) if snap: for i in range(3): start[i] = unit * math.floor(start[i]/unit + 1e-5) end[i] = unit * math.ceil(end[i]/unit - 1e-5) if absolute: if dir[0]*dir[1] or dir[1]*dir[2] or dir[0]*dir[2]: raise ValueError, "Absolute rulers only valid for axis-aligned paths" m = max(dir[0], dir[1], dir[2]) if dir[0] == m: off = start[0] elif dir[1] == m: off = start[1] else: off = start[2] first_tick = unit * math.ceil(off/unit - 1e-5) - off else: off = 0 first_tick = 0 ruler = shapes.LineSegment(start, end, **kwds) for k in range(1, int(sub_ticks * first_tick/unit)): P = start + dir*(k*unit/sub_ticks) ruler += shapes.LineSegment(P, P + tick/2, **kwds) for d in srange(first_tick, dist + unit/(sub_ticks+1), unit): P = start + dir*d ruler += shapes.LineSegment(P, P + tick, **kwds) ruler += shapes.Text(str(d+off), **kwds).translate(P - tick) if dist - d < unit: sub_ticks = int(sub_ticks * (dist - d)/unit) for k in range(1, sub_ticks): P += dir * (unit/sub_ticks) ruler += shapes.LineSegment(P, P + tick/2, **kwds) return ruler
def ruler(start, end, ticks=4, sub_ticks=4, absolute=False, snap=False, **kwds): """ Draw a ruler in 3D, with major and minor ticks. INPUT: - ``start`` - the beginning of the ruler, as a list, tuple, or vector. - ``end`` - the end of the ruler, as a list, tuple, or vector. - ``ticks`` - (default: 4) the number of major ticks shown on the ruler - ``sub_ticks`` - (default: 4) the number of shown subdivisions between each major tick - ``absolute`` - (default: False) if True, makes a huge ruler in the direction of an axis - ``snap`` - (default: False) if True, snaps to an implied grid Type ``line3d.options`` for a dictionary of the default options for lines which are also available. EXAMPLES: A ruler:: sage: from sage.plot.plot3d.shapes2 import ruler sage: R = ruler([1,2,3],vector([2,3,4])); R A ruler with some options:: sage: R = ruler([1,2,3],vector([2,3,4]),ticks=6, sub_ticks=2, color='red'); R The keyword ``snap`` makes the ticks not necessarily coincide with the ruler:: sage: ruler([1,2,3],vector([1,2,4]),snap=True) The keyword ``absolute`` makes a huge ruler in one of the axis directions:: sage: ruler([1,2,3],vector([1,2,4]),absolute=True) TESTS:: sage: ruler([1,2,3],vector([1,3,4]),absolute=True) Traceback (most recent call last): ... ValueError: Absolute rulers only valid for axis-aligned paths """ start = vector(RDF, start) end = vector(RDF, end) dir = end - start dist = math.sqrt(dir.dot_product(dir)) dir /= dist one_tick = dist/ticks * 1.414 unit = 10 ** math.floor(math.log(dist/ticks, 10)) if unit * 5 < one_tick: unit *= 5 elif unit * 2 < one_tick: unit *= 2 if dir[0]: tick = dir.cross_product(vector(RDF, (0,0,-dist/30))) elif dir[1]: tick = dir.cross_product(vector(RDF, (0,0,dist/30))) else: tick = vector(RDF, (dist/30,0,0)) if snap: for i in range(3): start[i] = unit * math.floor(start[i]/unit + 1e-5) end[i] = unit * math.ceil(end[i]/unit - 1e-5) if absolute: if dir[0]*dir[1] or dir[1]*dir[2] or dir[0]*dir[2]: raise ValueError, "Absolute rulers only valid for axis-aligned paths" m = max(dir[0], dir[1], dir[2]) if dir[0] == m: off = start[0] elif dir[1] == m: off = start[1] else: off = start[2] first_tick = unit * math.ceil(off/unit - 1e-5) - off else: off = 0 first_tick = 0 ruler = shapes.LineSegment(start, end, **kwds) for k in range(1, int(sub_ticks * first_tick/unit)): P = start + dir*(k*unit/sub_ticks) ruler += shapes.LineSegment(P, P + tick/2, **kwds) for d in srange(first_tick, dist + unit/(sub_ticks+1), unit): P = start + dir*d ruler += shapes.LineSegment(P, P + tick, **kwds) ruler += shapes.Text(str(d+off), **kwds).translate(P - tick) if dist - d < unit: sub_ticks = int(sub_ticks * (dist - d)/unit) for k in range(1, sub_ticks): P += dir * (unit/sub_ticks) ruler += shapes.LineSegment(P, P + tick/2, **kwds) return ruler
472,492
def ruler(start, end, ticks=4, sub_ticks=4, absolute=False, snap=False, **kwds): """ Draw a ruler in 3D, with major and minor ticks. INPUT: - ``start`` - the beginning of the ruler, as a list, tuple, or vector - ``end`` - the end of the ruler, as a list, tuple, or vector - ``ticks`` - (default: 4) the number of major ticks shown on the ruler - ``sub_ticks`` - (default: 4) the number of shown subdivisions between each major tick - ``absolute`` - (default: False) if True, makes a huge ruler in the direction of an axis - ``snap`` - (default: False) if True, snaps to an implied grid Type ``line3d.options`` for a dictionary of the default options for lines which are also available. EXAMPLES: A ruler:: sage: from sage.plot.plot3d.shapes2 import ruler sage: R = ruler([1,2,3],vector([2,3,4])); R A ruler with some options:: sage: R = ruler([1,2,3],vector([2,3,4]),ticks=6, sub_ticks=2, color='red'); R The keyword ``snap`` makes the ticks not necessarily coincide with the ruler:: sage: ruler([1,2,3],vector([1,2,4]),snap=True) The keyword ``absolute`` makes a huge ruler in one of the axis directions:: sage: ruler([1,2,3],vector([1,2,4]),absolute=True) TESTS:: sage: ruler([1,2,3],vector([1,3,4]),absolute=True) Traceback (most recent call last): ... ValueError: Absolute rulers only valid for axis-aligned paths """ start = vector(RDF, start) end = vector(RDF, end) dir = end - start dist = math.sqrt(dir.dot_product(dir)) dir /= dist one_tick = dist/ticks * 1.414 unit = 10 ** math.floor(math.log(dist/ticks, 10)) if unit * 5 < one_tick: unit *= 5 elif unit * 2 < one_tick: unit *= 2 if dir[0]: tick = dir.cross_product(vector(RDF, (0,0,-dist/30))) elif dir[1]: tick = dir.cross_product(vector(RDF, (0,0,dist/30))) else: tick = vector(RDF, (dist/30,0,0)) if snap: for i in range(3): start[i] = unit * math.floor(start[i]/unit + 1e-5) end[i] = unit * math.ceil(end[i]/unit - 1e-5) if absolute: if dir[0]*dir[1] or dir[1]*dir[2] or dir[0]*dir[2]: raise ValueError, "Absolute rulers only valid for axis-aligned paths" m = max(dir[0], dir[1], dir[2]) if dir[0] == m: off = start[0] elif dir[1] == m: off = start[1] else: off = start[2] first_tick = unit * math.ceil(off/unit - 1e-5) - off else: off = 0 first_tick = 0 ruler = shapes.LineSegment(start, end, **kwds) for k in range(1, int(sub_ticks * first_tick/unit)): P = start + dir*(k*unit/sub_ticks) ruler += shapes.LineSegment(P, P + tick/2, **kwds) for d in srange(first_tick, dist + unit/(sub_ticks+1), unit): P = start + dir*d ruler += shapes.LineSegment(P, P + tick, **kwds) ruler += shapes.Text(str(d+off), **kwds).translate(P - tick) if dist - d < unit: sub_ticks = int(sub_ticks * (dist - d)/unit) for k in range(1, sub_ticks): P += dir * (unit/sub_ticks) ruler += shapes.LineSegment(P, P + tick/2, **kwds) return ruler
def ruler(start, end, ticks=4, sub_ticks=4, absolute=False, snap=False, **kwds): """ Draw a ruler in 3D, with major and minor ticks. INPUT: - ``start`` - the beginning of the ruler, as a list, tuple, or vector - ``end`` - the end of the ruler, as a list, tuple, or vector - ``ticks`` - (default: 4) the number of major ticks shown on the ruler. - ``sub_ticks`` - (default: 4) the number of shown subdivisions between each major tick - ``absolute`` - (default: False) if True, makes a huge ruler in the direction of an axis - ``snap`` - (default: False) if True, snaps to an implied grid Type ``line3d.options`` for a dictionary of the default options for lines which are also available. EXAMPLES: A ruler:: sage: from sage.plot.plot3d.shapes2 import ruler sage: R = ruler([1,2,3],vector([2,3,4])); R A ruler with some options:: sage: R = ruler([1,2,3],vector([2,3,4]),ticks=6, sub_ticks=2, color='red'); R The keyword ``snap`` makes the ticks not necessarily coincide with the ruler:: sage: ruler([1,2,3],vector([1,2,4]),snap=True) The keyword ``absolute`` makes a huge ruler in one of the axis directions:: sage: ruler([1,2,3],vector([1,2,4]),absolute=True) TESTS:: sage: ruler([1,2,3],vector([1,3,4]),absolute=True) Traceback (most recent call last): ... ValueError: Absolute rulers only valid for axis-aligned paths """ start = vector(RDF, start) end = vector(RDF, end) dir = end - start dist = math.sqrt(dir.dot_product(dir)) dir /= dist one_tick = dist/ticks * 1.414 unit = 10 ** math.floor(math.log(dist/ticks, 10)) if unit * 5 < one_tick: unit *= 5 elif unit * 2 < one_tick: unit *= 2 if dir[0]: tick = dir.cross_product(vector(RDF, (0,0,-dist/30))) elif dir[1]: tick = dir.cross_product(vector(RDF, (0,0,dist/30))) else: tick = vector(RDF, (dist/30,0,0)) if snap: for i in range(3): start[i] = unit * math.floor(start[i]/unit + 1e-5) end[i] = unit * math.ceil(end[i]/unit - 1e-5) if absolute: if dir[0]*dir[1] or dir[1]*dir[2] or dir[0]*dir[2]: raise ValueError, "Absolute rulers only valid for axis-aligned paths" m = max(dir[0], dir[1], dir[2]) if dir[0] == m: off = start[0] elif dir[1] == m: off = start[1] else: off = start[2] first_tick = unit * math.ceil(off/unit - 1e-5) - off else: off = 0 first_tick = 0 ruler = shapes.LineSegment(start, end, **kwds) for k in range(1, int(sub_ticks * first_tick/unit)): P = start + dir*(k*unit/sub_ticks) ruler += shapes.LineSegment(P, P + tick/2, **kwds) for d in srange(first_tick, dist + unit/(sub_ticks+1), unit): P = start + dir*d ruler += shapes.LineSegment(P, P + tick, **kwds) ruler += shapes.Text(str(d+off), **kwds).translate(P - tick) if dist - d < unit: sub_ticks = int(sub_ticks * (dist - d)/unit) for k in range(1, sub_ticks): P += dir * (unit/sub_ticks) ruler += shapes.LineSegment(P, P + tick/2, **kwds) return ruler
472,493
def ruler(start, end, ticks=4, sub_ticks=4, absolute=False, snap=False, **kwds): """ Draw a ruler in 3D, with major and minor ticks. INPUT: - ``start`` - the beginning of the ruler, as a list, tuple, or vector - ``end`` - the end of the ruler, as a list, tuple, or vector - ``ticks`` - (default: 4) the number of major ticks shown on the ruler - ``sub_ticks`` - (default: 4) the number of shown subdivisions between each major tick - ``absolute`` - (default: False) if True, makes a huge ruler in the direction of an axis - ``snap`` - (default: False) if True, snaps to an implied grid Type ``line3d.options`` for a dictionary of the default options for lines which are also available. EXAMPLES: A ruler:: sage: from sage.plot.plot3d.shapes2 import ruler sage: R = ruler([1,2,3],vector([2,3,4])); R A ruler with some options:: sage: R = ruler([1,2,3],vector([2,3,4]),ticks=6, sub_ticks=2, color='red'); R The keyword ``snap`` makes the ticks not necessarily coincide with the ruler:: sage: ruler([1,2,3],vector([1,2,4]),snap=True) The keyword ``absolute`` makes a huge ruler in one of the axis directions:: sage: ruler([1,2,3],vector([1,2,4]),absolute=True) TESTS:: sage: ruler([1,2,3],vector([1,3,4]),absolute=True) Traceback (most recent call last): ... ValueError: Absolute rulers only valid for axis-aligned paths """ start = vector(RDF, start) end = vector(RDF, end) dir = end - start dist = math.sqrt(dir.dot_product(dir)) dir /= dist one_tick = dist/ticks * 1.414 unit = 10 ** math.floor(math.log(dist/ticks, 10)) if unit * 5 < one_tick: unit *= 5 elif unit * 2 < one_tick: unit *= 2 if dir[0]: tick = dir.cross_product(vector(RDF, (0,0,-dist/30))) elif dir[1]: tick = dir.cross_product(vector(RDF, (0,0,dist/30))) else: tick = vector(RDF, (dist/30,0,0)) if snap: for i in range(3): start[i] = unit * math.floor(start[i]/unit + 1e-5) end[i] = unit * math.ceil(end[i]/unit - 1e-5) if absolute: if dir[0]*dir[1] or dir[1]*dir[2] or dir[0]*dir[2]: raise ValueError, "Absolute rulers only valid for axis-aligned paths" m = max(dir[0], dir[1], dir[2]) if dir[0] == m: off = start[0] elif dir[1] == m: off = start[1] else: off = start[2] first_tick = unit * math.ceil(off/unit - 1e-5) - off else: off = 0 first_tick = 0 ruler = shapes.LineSegment(start, end, **kwds) for k in range(1, int(sub_ticks * first_tick/unit)): P = start + dir*(k*unit/sub_ticks) ruler += shapes.LineSegment(P, P + tick/2, **kwds) for d in srange(first_tick, dist + unit/(sub_ticks+1), unit): P = start + dir*d ruler += shapes.LineSegment(P, P + tick, **kwds) ruler += shapes.Text(str(d+off), **kwds).translate(P - tick) if dist - d < unit: sub_ticks = int(sub_ticks * (dist - d)/unit) for k in range(1, sub_ticks): P += dir * (unit/sub_ticks) ruler += shapes.LineSegment(P, P + tick/2, **kwds) return ruler
def ruler(start, end, ticks=4, sub_ticks=4, absolute=False, snap=False, **kwds): """ Draw a ruler in 3D, with major and minor ticks. INPUT: - ``start`` - the beginning of the ruler, as a list, tuple, or vector - ``end`` - the end of the ruler, as a list, tuple, or vector - ``ticks`` - (default: 4) the number of major ticks shown on the ruler - ``sub_ticks`` - (default: 4) the number of shown subdivisions between each major tick. - ``absolute`` - (default: ``False``) if ``True``, makes a huge ruler in the direction of an axis. - ``snap`` - (default: ``False``) if ``True``, snaps to an implied grid. Type ``line3d.options`` for a dictionary of the default options for lines which are also available. EXAMPLES: A ruler:: sage: from sage.plot.plot3d.shapes2 import ruler sage: R = ruler([1,2,3],vector([2,3,4])); R A ruler with some options:: sage: R = ruler([1,2,3],vector([2,3,4]),ticks=6, sub_ticks=2, color='red'); R The keyword ``snap`` makes the ticks not necessarily coincide with the ruler:: sage: ruler([1,2,3],vector([1,2,4]),snap=True) The keyword ``absolute`` makes a huge ruler in one of the axis directions:: sage: ruler([1,2,3],vector([1,2,4]),absolute=True) TESTS:: sage: ruler([1,2,3],vector([1,3,4]),absolute=True) Traceback (most recent call last): ... ValueError: Absolute rulers only valid for axis-aligned paths """ start = vector(RDF, start) end = vector(RDF, end) dir = end - start dist = math.sqrt(dir.dot_product(dir)) dir /= dist one_tick = dist/ticks * 1.414 unit = 10 ** math.floor(math.log(dist/ticks, 10)) if unit * 5 < one_tick: unit *= 5 elif unit * 2 < one_tick: unit *= 2 if dir[0]: tick = dir.cross_product(vector(RDF, (0,0,-dist/30))) elif dir[1]: tick = dir.cross_product(vector(RDF, (0,0,dist/30))) else: tick = vector(RDF, (dist/30,0,0)) if snap: for i in range(3): start[i] = unit * math.floor(start[i]/unit + 1e-5) end[i] = unit * math.ceil(end[i]/unit - 1e-5) if absolute: if dir[0]*dir[1] or dir[1]*dir[2] or dir[0]*dir[2]: raise ValueError, "Absolute rulers only valid for axis-aligned paths" m = max(dir[0], dir[1], dir[2]) if dir[0] == m: off = start[0] elif dir[1] == m: off = start[1] else: off = start[2] first_tick = unit * math.ceil(off/unit - 1e-5) - off else: off = 0 first_tick = 0 ruler = shapes.LineSegment(start, end, **kwds) for k in range(1, int(sub_ticks * first_tick/unit)): P = start + dir*(k*unit/sub_ticks) ruler += shapes.LineSegment(P, P + tick/2, **kwds) for d in srange(first_tick, dist + unit/(sub_ticks+1), unit): P = start + dir*d ruler += shapes.LineSegment(P, P + tick, **kwds) ruler += shapes.Text(str(d+off), **kwds).translate(P - tick) if dist - d < unit: sub_ticks = int(sub_ticks * (dist - d)/unit) for k in range(1, sub_ticks): P += dir * (unit/sub_ticks) ruler += shapes.LineSegment(P, P + tick/2, **kwds) return ruler
472,494
def ruler(start, end, ticks=4, sub_ticks=4, absolute=False, snap=False, **kwds): """ Draw a ruler in 3D, with major and minor ticks. INPUT: - ``start`` - the beginning of the ruler, as a list, tuple, or vector - ``end`` - the end of the ruler, as a list, tuple, or vector - ``ticks`` - (default: 4) the number of major ticks shown on the ruler - ``sub_ticks`` - (default: 4) the number of shown subdivisions between each major tick - ``absolute`` - (default: False) if True, makes a huge ruler in the direction of an axis - ``snap`` - (default: False) if True, snaps to an implied grid Type ``line3d.options`` for a dictionary of the default options for lines which are also available. EXAMPLES: A ruler:: sage: from sage.plot.plot3d.shapes2 import ruler sage: R = ruler([1,2,3],vector([2,3,4])); R A ruler with some options:: sage: R = ruler([1,2,3],vector([2,3,4]),ticks=6, sub_ticks=2, color='red'); R The keyword ``snap`` makes the ticks not necessarily coincide with the ruler:: sage: ruler([1,2,3],vector([1,2,4]),snap=True) The keyword ``absolute`` makes a huge ruler in one of the axis directions:: sage: ruler([1,2,3],vector([1,2,4]),absolute=True) TESTS:: sage: ruler([1,2,3],vector([1,3,4]),absolute=True) Traceback (most recent call last): ... ValueError: Absolute rulers only valid for axis-aligned paths """ start = vector(RDF, start) end = vector(RDF, end) dir = end - start dist = math.sqrt(dir.dot_product(dir)) dir /= dist one_tick = dist/ticks * 1.414 unit = 10 ** math.floor(math.log(dist/ticks, 10)) if unit * 5 < one_tick: unit *= 5 elif unit * 2 < one_tick: unit *= 2 if dir[0]: tick = dir.cross_product(vector(RDF, (0,0,-dist/30))) elif dir[1]: tick = dir.cross_product(vector(RDF, (0,0,dist/30))) else: tick = vector(RDF, (dist/30,0,0)) if snap: for i in range(3): start[i] = unit * math.floor(start[i]/unit + 1e-5) end[i] = unit * math.ceil(end[i]/unit - 1e-5) if absolute: if dir[0]*dir[1] or dir[1]*dir[2] or dir[0]*dir[2]: raise ValueError, "Absolute rulers only valid for axis-aligned paths" m = max(dir[0], dir[1], dir[2]) if dir[0] == m: off = start[0] elif dir[1] == m: off = start[1] else: off = start[2] first_tick = unit * math.ceil(off/unit - 1e-5) - off else: off = 0 first_tick = 0 ruler = shapes.LineSegment(start, end, **kwds) for k in range(1, int(sub_ticks * first_tick/unit)): P = start + dir*(k*unit/sub_ticks) ruler += shapes.LineSegment(P, P + tick/2, **kwds) for d in srange(first_tick, dist + unit/(sub_ticks+1), unit): P = start + dir*d ruler += shapes.LineSegment(P, P + tick, **kwds) ruler += shapes.Text(str(d+off), **kwds).translate(P - tick) if dist - d < unit: sub_ticks = int(sub_ticks * (dist - d)/unit) for k in range(1, sub_ticks): P += dir * (unit/sub_ticks) ruler += shapes.LineSegment(P, P + tick/2, **kwds) return ruler
def ruler(start, end, ticks=4, sub_ticks=4, absolute=False, snap=False, **kwds): """ Draw a ruler in 3D, with major and minor ticks. INPUT: - ``start`` - the beginning of the ruler, as a list, tuple, or vector - ``end`` - the end of the ruler, as a list, tuple, or vector - ``ticks`` - (default: 4) the number of major ticks shown on the ruler - ``sub_ticks`` - (default: 4) the number of shown subdivisions between each major tick - ``absolute`` - (default: False) if True, makes a huge ruler in the direction of an axis - ``snap`` - (default: False) if True, snaps to an implied grid Type ``line3d.options`` for a dictionary of the default options for lines, which are also available. EXAMPLES: A ruler:: sage: from sage.plot.plot3d.shapes2 import ruler sage: R = ruler([1,2,3],vector([2,3,4])); R A ruler with some options:: sage: R = ruler([1,2,3],vector([2,3,4]),ticks=6, sub_ticks=2, color='red'); R The keyword ``snap`` makes the ticks not necessarily coincide with the ruler:: sage: ruler([1,2,3],vector([1,2,4]),snap=True) The keyword ``absolute`` makes a huge ruler in one of the axis directions:: sage: ruler([1,2,3],vector([1,2,4]),absolute=True) TESTS:: sage: ruler([1,2,3],vector([1,3,4]),absolute=True) Traceback (most recent call last): ... ValueError: Absolute rulers only valid for axis-aligned paths """ start = vector(RDF, start) end = vector(RDF, end) dir = end - start dist = math.sqrt(dir.dot_product(dir)) dir /= dist one_tick = dist/ticks * 1.414 unit = 10 ** math.floor(math.log(dist/ticks, 10)) if unit * 5 < one_tick: unit *= 5 elif unit * 2 < one_tick: unit *= 2 if dir[0]: tick = dir.cross_product(vector(RDF, (0,0,-dist/30))) elif dir[1]: tick = dir.cross_product(vector(RDF, (0,0,dist/30))) else: tick = vector(RDF, (dist/30,0,0)) if snap: for i in range(3): start[i] = unit * math.floor(start[i]/unit + 1e-5) end[i] = unit * math.ceil(end[i]/unit - 1e-5) if absolute: if dir[0]*dir[1] or dir[1]*dir[2] or dir[0]*dir[2]: raise ValueError, "Absolute rulers only valid for axis-aligned paths" m = max(dir[0], dir[1], dir[2]) if dir[0] == m: off = start[0] elif dir[1] == m: off = start[1] else: off = start[2] first_tick = unit * math.ceil(off/unit - 1e-5) - off else: off = 0 first_tick = 0 ruler = shapes.LineSegment(start, end, **kwds) for k in range(1, int(sub_ticks * first_tick/unit)): P = start + dir*(k*unit/sub_ticks) ruler += shapes.LineSegment(P, P + tick/2, **kwds) for d in srange(first_tick, dist + unit/(sub_ticks+1), unit): P = start + dir*d ruler += shapes.LineSegment(P, P + tick, **kwds) ruler += shapes.Text(str(d+off), **kwds).translate(P - tick) if dist - d < unit: sub_ticks = int(sub_ticks * (dist - d)/unit) for k in range(1, sub_ticks): P += dir * (unit/sub_ticks) ruler += shapes.LineSegment(P, P + tick/2, **kwds) return ruler
472,495
def ruler_frame(lower_left, upper_right, ticks=4, sub_ticks=4, **kwds): """ Draw a frame made of 3D rulers, with major and minor ticks. INPUT: - ``lower_left`` - the lower left corner of the frame, as a list, tuple, or vector - ``upper_right`` - the upper right corner of the frame, as a list, tuple, or vector - ``ticks`` - (default: 4) the number of major ticks shown on each ruler - ``sub_ticks`` - (default: 4) the number of shown subdivisions between each major tick Type ``line3d.options`` for a dictionary of the default options for lines which are also available. EXAMPLES: A ruler frame:: sage: from sage.plot.plot3d.shapes2 import ruler_frame sage: F = ruler_frame([1,2,3],vector([2,3,4])); F A ruler frame with some options:: sage: F = ruler_frame([1,2,3],vector([2,3,4]),ticks=6, sub_ticks=2, color='red'); F """ return ruler(lower_left, (upper_right[0], lower_left[1], lower_left[2]), ticks=ticks, sub_ticks=sub_ticks, absolute=True, **kwds) \ + ruler(lower_left, (lower_left[0], upper_right[1], lower_left[2]), ticks=ticks, sub_ticks=sub_ticks, absolute=True, **kwds) \ + ruler(lower_left, (lower_left[0], lower_left[1], upper_right[2]), ticks=ticks, sub_ticks=sub_ticks, absolute=True, **kwds)
def ruler_frame(lower_left, upper_right, ticks=4, sub_ticks=4, **kwds): """ Draw a frame made of 3-D rulers, with major and minor ticks. INPUT: - ``lower_left`` - the lower left corner of the frame, as a list, tuple, or vector - ``upper_right`` - the upper right corner of the frame, as a list, tuple, or vector - ``ticks`` - (default: 4) the number of major ticks shown on each ruler - ``sub_ticks`` - (default: 4) the number of shown subdivisions between each major tick Type ``line3d.options`` for a dictionary of the default options for lines which are also available. EXAMPLES: A ruler frame:: sage: from sage.plot.plot3d.shapes2 import ruler_frame sage: F = ruler_frame([1,2,3],vector([2,3,4])); F A ruler frame with some options:: sage: F = ruler_frame([1,2,3],vector([2,3,4]),ticks=6, sub_ticks=2, color='red'); F """ return ruler(lower_left, (upper_right[0], lower_left[1], lower_left[2]), ticks=ticks, sub_ticks=sub_ticks, absolute=True, **kwds) \ + ruler(lower_left, (lower_left[0], upper_right[1], lower_left[2]), ticks=ticks, sub_ticks=sub_ticks, absolute=True, **kwds) \ + ruler(lower_left, (lower_left[0], lower_left[1], upper_right[2]), ticks=ticks, sub_ticks=sub_ticks, absolute=True, **kwds)
472,496
def ruler_frame(lower_left, upper_right, ticks=4, sub_ticks=4, **kwds): """ Draw a frame made of 3D rulers, with major and minor ticks. INPUT: - ``lower_left`` - the lower left corner of the frame, as a list, tuple, or vector - ``upper_right`` - the upper right corner of the frame, as a list, tuple, or vector - ``ticks`` - (default: 4) the number of major ticks shown on each ruler - ``sub_ticks`` - (default: 4) the number of shown subdivisions between each major tick Type ``line3d.options`` for a dictionary of the default options for lines which are also available. EXAMPLES: A ruler frame:: sage: from sage.plot.plot3d.shapes2 import ruler_frame sage: F = ruler_frame([1,2,3],vector([2,3,4])); F A ruler frame with some options:: sage: F = ruler_frame([1,2,3],vector([2,3,4]),ticks=6, sub_ticks=2, color='red'); F """ return ruler(lower_left, (upper_right[0], lower_left[1], lower_left[2]), ticks=ticks, sub_ticks=sub_ticks, absolute=True, **kwds) \ + ruler(lower_left, (lower_left[0], upper_right[1], lower_left[2]), ticks=ticks, sub_ticks=sub_ticks, absolute=True, **kwds) \ + ruler(lower_left, (lower_left[0], lower_left[1], upper_right[2]), ticks=ticks, sub_ticks=sub_ticks, absolute=True, **kwds)
def ruler_frame(lower_left, upper_right, ticks=4, sub_ticks=4, **kwds): """ Draw a frame made of 3D rulers, with major and minor ticks. INPUT: - ``lower_left`` - the lower left corner of the frame, as a list, tuple, or vector. - ``upper_right`` - the upper right corner of the frame, as a list, tuple, or vector. - ``ticks`` - (default: 4) the number of major ticks shown on each ruler - ``sub_ticks`` - (default: 4) the number of shown subdivisions between each major tick Type ``line3d.options`` for a dictionary of the default options for lines which are also available. EXAMPLES: A ruler frame:: sage: from sage.plot.plot3d.shapes2 import ruler_frame sage: F = ruler_frame([1,2,3],vector([2,3,4])); F A ruler frame with some options:: sage: F = ruler_frame([1,2,3],vector([2,3,4]),ticks=6, sub_ticks=2, color='red'); F """ return ruler(lower_left, (upper_right[0], lower_left[1], lower_left[2]), ticks=ticks, sub_ticks=sub_ticks, absolute=True, **kwds) \ + ruler(lower_left, (lower_left[0], upper_right[1], lower_left[2]), ticks=ticks, sub_ticks=sub_ticks, absolute=True, **kwds) \ + ruler(lower_left, (lower_left[0], lower_left[1], upper_right[2]), ticks=ticks, sub_ticks=sub_ticks, absolute=True, **kwds)
472,497
def ruler_frame(lower_left, upper_right, ticks=4, sub_ticks=4, **kwds): """ Draw a frame made of 3D rulers, with major and minor ticks. INPUT: - ``lower_left`` - the lower left corner of the frame, as a list, tuple, or vector - ``upper_right`` - the upper right corner of the frame, as a list, tuple, or vector - ``ticks`` - (default: 4) the number of major ticks shown on each ruler - ``sub_ticks`` - (default: 4) the number of shown subdivisions between each major tick Type ``line3d.options`` for a dictionary of the default options for lines which are also available. EXAMPLES: A ruler frame:: sage: from sage.plot.plot3d.shapes2 import ruler_frame sage: F = ruler_frame([1,2,3],vector([2,3,4])); F A ruler frame with some options:: sage: F = ruler_frame([1,2,3],vector([2,3,4]),ticks=6, sub_ticks=2, color='red'); F """ return ruler(lower_left, (upper_right[0], lower_left[1], lower_left[2]), ticks=ticks, sub_ticks=sub_ticks, absolute=True, **kwds) \ + ruler(lower_left, (lower_left[0], upper_right[1], lower_left[2]), ticks=ticks, sub_ticks=sub_ticks, absolute=True, **kwds) \ + ruler(lower_left, (lower_left[0], lower_left[1], upper_right[2]), ticks=ticks, sub_ticks=sub_ticks, absolute=True, **kwds)
def ruler_frame(lower_left, upper_right, ticks=4, sub_ticks=4, **kwds): """ Draw a frame made of 3D rulers, with major and minor ticks. INPUT: - ``lower_left`` - the lower left corner of the frame, as a list, tuple, or vector. - ``upper_right`` - the upper right corner of the frame, as a list, tuple, or vector. - ``ticks`` - (default: 4) the number of major ticks shown on each ruler - ``sub_ticks`` - (default: 4) the number of shown subdivisions between each major tick Type ``line3d.options`` for a dictionary of the default options for lines which are also available. EXAMPLES: A ruler frame:: sage: from sage.plot.plot3d.shapes2 import ruler_frame sage: F = ruler_frame([1,2,3],vector([2,3,4])); F A ruler frame with some options:: sage: F = ruler_frame([1,2,3],vector([2,3,4]),ticks=6, sub_ticks=2, color='red'); F """ return ruler(lower_left, (upper_right[0], lower_left[1], lower_left[2]), ticks=ticks, sub_ticks=sub_ticks, absolute=True, **kwds) \ + ruler(lower_left, (lower_left[0], upper_right[1], lower_left[2]), ticks=ticks, sub_ticks=sub_ticks, absolute=True, **kwds) \ + ruler(lower_left, (lower_left[0], lower_left[1], upper_right[2]), ticks=ticks, sub_ticks=sub_ticks, absolute=True, **kwds)
472,498
def ruler_frame(lower_left, upper_right, ticks=4, sub_ticks=4, **kwds): """ Draw a frame made of 3D rulers, with major and minor ticks. INPUT: - ``lower_left`` - the lower left corner of the frame, as a list, tuple, or vector - ``upper_right`` - the upper right corner of the frame, as a list, tuple, or vector - ``ticks`` - (default: 4) the number of major ticks shown on each ruler - ``sub_ticks`` - (default: 4) the number of shown subdivisions between each major tick Type ``line3d.options`` for a dictionary of the default options for lines which are also available. EXAMPLES: A ruler frame:: sage: from sage.plot.plot3d.shapes2 import ruler_frame sage: F = ruler_frame([1,2,3],vector([2,3,4])); F A ruler frame with some options:: sage: F = ruler_frame([1,2,3],vector([2,3,4]),ticks=6, sub_ticks=2, color='red'); F """ return ruler(lower_left, (upper_right[0], lower_left[1], lower_left[2]), ticks=ticks, sub_ticks=sub_ticks, absolute=True, **kwds) \ + ruler(lower_left, (lower_left[0], upper_right[1], lower_left[2]), ticks=ticks, sub_ticks=sub_ticks, absolute=True, **kwds) \ + ruler(lower_left, (lower_left[0], lower_left[1], upper_right[2]), ticks=ticks, sub_ticks=sub_ticks, absolute=True, **kwds)
def ruler_frame(lower_left, upper_right, ticks=4, sub_ticks=4, **kwds): """ Draw a frame made of 3D rulers, with major and minor ticks. INPUT: - ``lower_left`` - the lower left corner of the frame, as a list, tuple, or vector - ``upper_right`` - the upper right corner of the frame, as a list, tuple, or vector - ``ticks`` - (default: 4) the number of major ticks shown on each ruler. - ``sub_ticks`` - (default: 4) the number of shown subdivisions between each major tick Type ``line3d.options`` for a dictionary of the default options for lines which are also available. EXAMPLES: A ruler frame:: sage: from sage.plot.plot3d.shapes2 import ruler_frame sage: F = ruler_frame([1,2,3],vector([2,3,4])); F A ruler frame with some options:: sage: F = ruler_frame([1,2,3],vector([2,3,4]),ticks=6, sub_ticks=2, color='red'); F """ return ruler(lower_left, (upper_right[0], lower_left[1], lower_left[2]), ticks=ticks, sub_ticks=sub_ticks, absolute=True, **kwds) \ + ruler(lower_left, (lower_left[0], upper_right[1], lower_left[2]), ticks=ticks, sub_ticks=sub_ticks, absolute=True, **kwds) \ + ruler(lower_left, (lower_left[0], lower_left[1], upper_right[2]), ticks=ticks, sub_ticks=sub_ticks, absolute=True, **kwds)
472,499