rem
stringlengths 0
322k
| add
stringlengths 0
2.05M
| context
stringlengths 8
228k
|
---|---|---|
sage: T = _ArbCoordTrans((x + y, x - y, z), x) The independent and dependent variables don't really matter in the case of an arbitrary transformation (since it is already in terms of its own variables), so default values are provided:: sage: T.indep_var 'f' sage: T.dep_vars ['u', 'v'] Finally, an example of gen_transform():: sage: T.gen_transform(f=z) [y + z, -y + z, z] """ return [t.subs({self.fvar: f}) for t in self.custom_trans] class Spherical(_CoordTrans):
|
sage: T = _ArbitraryCoordinates((x + y, x - y, z), x,[y,z]) sage: T.transform(x=z,y=1) (z + 1, z - 1, z) """ return tuple(t.subs(**kwds) for t in self.custom_trans) class Spherical(_Coordinates):
|
def gen_transform(self, f=None, u=None, v=None): """ EXAMPLE:: sage: from sage.plot.plot3d.plot3d import _ArbCoordTrans sage: x, y, z = var('x y z') sage: T = _ArbCoordTrans((x + y, x - y, z), x)
|
- the *radial distance* (``r``), - the *elevation angle* (``theta``), - and the *azimuth angle* (``phi``).
|
- the *radial distance* (``radius``) from the origin - the *azimuth angle* (``azimuth``) from the positive `x`-axis
|
def gen_transform(self, f=None, u=None, v=None): """ EXAMPLE:: sage: from sage.plot.plot3d.plot3d import _ArbCoordTrans sage: x, y, z = var('x y z') sage: T = _ArbCoordTrans((x + y, x - y, z), x)
|
Construct a spherical transformation for a function ``r`` in terms of ``theta`` and ``phi``:: sage: T = Spherical('r', ['phi', 'theta']) If we construct some concrete variables, we can get a transformation::
|
Construct a spherical transformation for a function for the radius in terms of the azimuth and inclination:: sage: T = Spherical('radius', ['azimuth', 'inclination']) If we construct some concrete variables, we can get a transformation in terms of those variables::
|
def gen_transform(self, f=None, u=None, v=None): """ EXAMPLE:: sage: from sage.plot.plot3d.plot3d import _ArbCoordTrans sage: x, y, z = var('x y z') sage: T = _ArbCoordTrans((x + y, x - y, z), x)
|
sage: T.gen_transform(r=r, theta=theta, phi=phi) (r*sin(theta)*cos(phi), r*sin(phi)*sin(theta), r*cos(theta)) Use with plot3d on a made-up function:: sage: plot3d(phi * theta, (phi, 0, 1), (theta, 0, 1), transformation=T) To graph a function ``theta`` in terms of ``r`` and ``phi``, you would use:: sage: Spherical('theta', ['r', 'phi']) Spherical coordinate system (theta in terms of r, phi) See also ``spherical_plot3d`` for more examples of plotting in spherical
|
sage: T.transform(radius=r, azimuth=theta, inclination=phi) (r*sin(phi)*cos(theta), r*sin(phi)*sin(theta), r*cos(phi)) We can plot with this transform. Remember that the independent variable is the radius, and the dependent variables are the azimuth and the inclination (in that order):: sage: plot3d(phi * theta, (theta, 0, pi), (phi, 0, 1), transformation=T) We next graph the function where the inclination angle is constant:: sage: S=Spherical('inclination', ['radius', 'azimuth']) sage: r,theta=var('r,theta') sage: plot3d(3, (r,0,3), (theta, 0, 2*pi), transformation=S) See also :func:`spherical_plot3d` for more examples of plotting in spherical
|
def gen_transform(self, f=None, u=None, v=None): """ EXAMPLE:: sage: from sage.plot.plot3d.plot3d import _ArbCoordTrans sage: x, y, z = var('x y z') sage: T = _ArbCoordTrans((x + y, x - y, z), x)
|
all_vars = ['r', 'theta', 'phi'] _name = 'Spherical coordinate system' def gen_transform(self, r=None, theta=None, phi=None): """
|
def transform(self, radius=None, azimuth=None, inclination=None): """ A spherical coordinates transform.
|
def gen_transform(self, f=None, u=None, v=None): """ EXAMPLE:: sage: from sage.plot.plot3d.plot3d import _ArbCoordTrans sage: x, y, z = var('x y z') sage: T = _ArbCoordTrans((x + y, x - y, z), x)
|
sage: T = Spherical('r', ['theta', 'phi']) sage: T.gen_transform(r=var('r'), theta=var('theta'), phi=var('phi')) (r*sin(theta)*cos(phi), r*sin(phi)*sin(theta), r*cos(theta)) """ return (r * sin(theta) * cos(phi), r * sin(theta) * sin(phi), r * cos(theta)) class Cylindrical(_CoordTrans):
|
sage: T = Spherical('radius', ['azimuth', 'inclination']) sage: T.transform(radius=var('r'), azimuth=var('theta'), inclination=var('phi')) (r*sin(phi)*cos(theta), r*sin(phi)*sin(theta), r*cos(phi)) """ return (radius * sin(inclination) * cos(azimuth), radius * sin(inclination) * sin(azimuth), radius * cos(inclination)) class Cylindrical(_Coordinates):
|
def gen_transform(self, r=None, theta=None, phi=None): """ EXAMPLE:: sage: T = Spherical('r', ['theta', 'phi']) sage: T.gen_transform(r=var('r'), theta=var('theta'), phi=var('phi')) (r*sin(theta)*cos(phi), r*sin(phi)*sin(theta), r*cos(theta)) """ return (r * sin(theta) * cos(phi), r * sin(theta) * sin(phi), r * cos(theta))
|
- the *radial distance* (``rho``),
|
- the *radial distance* (``radius``) from the `z`-axis - the *azimuth angle* (``azimuth``) from the positive `x`-axis
|
def gen_transform(self, r=None, theta=None, phi=None): """ EXAMPLE:: sage: T = Spherical('r', ['theta', 'phi']) sage: T.gen_transform(r=var('r'), theta=var('theta'), phi=var('phi')) (r*sin(theta)*cos(phi), r*sin(phi)*sin(theta), r*cos(theta)) """ return (r * sin(theta) * cos(phi), r * sin(theta) * sin(phi), r * cos(theta))
|
- the *angular position* or *azimuth* (``phi``), - and the *height* or *altitude* (``z``).
|
- the *height* or *altitude* (``height``) above the `xy`-plane
|
def gen_transform(self, r=None, theta=None, phi=None): """ EXAMPLE:: sage: T = Spherical('r', ['theta', 'phi']) sage: T.gen_transform(r=var('r'), theta=var('theta'), phi=var('phi')) (r*sin(theta)*cos(phi), r*sin(phi)*sin(theta), r*cos(theta)) """ return (r * sin(theta) * cos(phi), r * sin(theta) * sin(phi), r * cos(theta))
|
Construct a cylindrical transformation for a function ``rho`` in terms of ``phi`` and ``z``:: sage: T = Cylindrical('rho', ['phi', 'z'])
|
Construct a cylindrical transformation for a function for ``height`` in terms of ``radius`` and ``azimuth``:: sage: T = Cylindrical('height', ['radius', 'azimuth'])
|
def gen_transform(self, r=None, theta=None, phi=None): """ EXAMPLE:: sage: T = Spherical('r', ['theta', 'phi']) sage: T.gen_transform(r=var('r'), theta=var('theta'), phi=var('phi')) (r*sin(theta)*cos(phi), r*sin(phi)*sin(theta), r*cos(theta)) """ return (r * sin(theta) * cos(phi), r * sin(theta) * sin(phi), r * cos(theta))
|
sage: rho, phi, z = var('rho phi z') sage: T.gen_transform(rho=rho, phi=phi, z=z) (rho*cos(phi), rho*sin(phi), z) Use with plot3d on a made-up function:: sage: plot3d(phi * z, (phi, 0, 1), (z, 0, 1), transformation=T) To graph a function ``z`` in terms of ``phi`` and ``rho`` you would use:: sage: Cylindrical('z', ['phi', 'rho']) Cylindrical coordinate system (z in terms of phi, rho) See also ``cylindrical_plot3d`` for more examples of plotting in cylindrical
|
sage: r, theta, z = var('r theta z') sage: T.transform(radius=r, azimuth=theta, height=z) (r*cos(theta), r*sin(theta), z) We can plot with this transform. Remember that the independent variable is the height, and the dependent variables are the radius and the azimuth (in that order):: sage: plot3d(9-r^2, (r, 0, 3), (theta, 0, pi), transformation=T) We next graph the function where the radius is constant:: sage: S=Cylindrical('radius', ['azimuth', 'height']) sage: theta,z=var('theta, z') sage: plot3d(3, (theta,0,2*pi), (z, -2, 2), transformation=S) See also :func:`cylindrical_plot3d` for more examples of plotting in cylindrical
|
def gen_transform(self, r=None, theta=None, phi=None): """ EXAMPLE:: sage: T = Spherical('r', ['theta', 'phi']) sage: T.gen_transform(r=var('r'), theta=var('theta'), phi=var('phi')) (r*sin(theta)*cos(phi), r*sin(phi)*sin(theta), r*cos(theta)) """ return (r * sin(theta) * cos(phi), r * sin(theta) * sin(phi), r * cos(theta))
|
_name = 'Cylindrical coordinate system' all_vars = ['rho', 'phi', 'z'] def gen_transform(self, rho=None, phi=None, z=None): """
|
def transform(self, radius=None, azimuth=None, height=None): """ A cylindrical coordinates transform.
|
def gen_transform(self, r=None, theta=None, phi=None): """ EXAMPLE:: sage: T = Spherical('r', ['theta', 'phi']) sage: T.gen_transform(r=var('r'), theta=var('theta'), phi=var('phi')) (r*sin(theta)*cos(phi), r*sin(phi)*sin(theta), r*cos(theta)) """ return (r * sin(theta) * cos(phi), r * sin(theta) * sin(phi), r * cos(theta))
|
sage: T = Cylindrical('z', ['phi', 'rho']) sage: T.gen_transform(rho=var('rho'), phi=var('phi'), z=var('z')) (rho*cos(phi), rho*sin(phi), z) """ return (rho * cos(phi), rho * sin(phi), z)
|
sage: T = Cylindrical('height', ['azimuth', 'radius']) sage: T.transform(radius=var('r'), azimuth=var('theta'), height=var('z')) (r*cos(theta), r*sin(theta), z) """ return (radius * cos(azimuth), radius * sin(azimuth), height)
|
def gen_transform(self, rho=None, phi=None, z=None): """ EXAMPLE::
|
- ``transformation`` - (default: None) a transformation to apply. May be a 4-tuple (x_func, y_func, z_func, fvar) where the first 3 items indicate a transformation to cartesian coordinates (from your coordinate system) in terms of u, v, and the function variable fvar (for which the value of f will be substituted). May also be a predefined coordinate system transformation like Spherical or Cylindrical.
|
- ``transformation`` - (default: None) a transformation to apply. May be a 3 or 4-tuple (x_func, y_func, z_func, independent_vars) where the first 3 items indicate a transformation to cartesian coordinates (from your coordinate system) in terms of u, v, and the function variable fvar (for which the value of f will be substituted). If a 3-tuple is specified, the independent variables are chosen from the range variables. If a 4-tuple is specified, the 4th element is a list of independent variables. ``transformation`` may also be a predefined coordinate system transformation like Spherical or Cylindrical.
|
def plot3d(f, urange, vrange, adaptive=False, transformation=None, **kwds): """ INPUT: - ``f`` - a symbolic expression or function of 2 variables - ``urange`` - a 2-tuple (u_min, u_max) or a 3-tuple (u, u_min, u_max) - ``vrange`` - a 2-tuple (v_min, v_max) or a 3-tuple (v, v_min, v_max) - ``adaptive`` - (default: False) whether to use adaptive refinement to draw the plot (slower, but may look better). This option does NOT work in conjuction with a transformation (see below). - ``mesh`` - bool (default: False) whether to display mesh grid lines - ``dots`` - bool (default: False) whether to display dots at mesh grid points - ``plot_points`` - (default: "automatic") initial number of sample points in each direction; an integer or a pair of integers - ``transformation`` - (default: None) a transformation to apply. May be a 4-tuple (x_func, y_func, z_func, fvar) where the first 3 items indicate a transformation to cartesian coordinates (from your coordinate system) in terms of u, v, and the function variable fvar (for which the value of f will be substituted). May also be a predefined coordinate system transformation like Spherical or Cylindrical. .. note:: ``mesh`` and ``dots`` are not supported when using the Tachyon raytracer renderer. EXAMPLES: We plot a 3d function defined as a Python function:: sage: plot3d(lambda x, y: x^2 + y^2, (-2,2), (-2,2)) We plot the same 3d function but using adaptive refinement:: sage: plot3d(lambda x, y: x^2 + y^2, (-2,2), (-2,2), adaptive=True) Adaptive refinement but with more points:: sage: plot3d(lambda x, y: x^2 + y^2, (-2,2), (-2,2), adaptive=True, initial_depth=5) We plot some 3d symbolic functions:: sage: var('x,y') (x, y) sage: plot3d(x^2 + y^2, (x,-2,2), (y,-2,2)) sage: plot3d(sin(x*y), (x, -pi, pi), (y, -pi, pi)) We give a plot with extra sample points:: sage: var('x,y') (x, y) sage: plot3d(sin(x^2+y^2),(x,-5,5),(y,-5,5), plot_points=200) sage: plot3d(sin(x^2+y^2),(x,-5,5),(y,-5,5), plot_points=[10,100]) A 3d plot with a mesh:: sage: var('x,y') (x, y) sage: plot3d(sin(x-y)*y*cos(x),(x,-3,3),(y,-3,3), mesh=True) Two wobby translucent planes:: sage: x,y = var('x,y') sage: P = plot3d(x+y+sin(x*y), (x,-10,10),(y,-10,10), opacity=0.87, color='blue') sage: Q = plot3d(x-2*y-cos(x*y),(x,-10,10),(y,-10,10),opacity=0.3,color='red') sage: P + Q We draw two parametric surfaces and a transparent plane:: sage: L = plot3d(lambda x,y: 0, (-5,5), (-5,5), color="lightblue", opacity=0.8) sage: P = plot3d(lambda x,y: 4 - x^3 - y^2, (-2,2), (-2,2), color='green') sage: Q = plot3d(lambda x,y: x^3 + y^2 - 4, (-2,2), (-2,2), color='orange') sage: L + P + Q We draw the "Sinus" function (water ripple-like surface):: sage: x, y = var('x y') sage: plot3d(sin(pi*(x^2+y^2))/2,(x,-1,1),(y,-1,1)) Hill and valley (flat surface with a bump and a dent):: sage: x, y = var('x y') sage: plot3d( 4*x*exp(-x^2-y^2), (x,-2,2), (y,-2,2)) An example of a transformation:: sage: r, phi, z = var('r phi z') sage: trans=(r*cos(phi),r*sin(phi),z,z) sage: plot3d(cos(r),(r,0,17*pi/2),(phi,0,2*pi),transformation=trans,opacity=0.87).show(aspect_ratio=(1,1,2),frame=False) Many more examples of transformations:: sage: u, v, w = var('u v w') sage: rectangular=(u,v,w,w) sage: spherical=(w*cos(u)*sin(v),w*sin(u)*sin(v),w*cos(v),w) sage: cylindric_radial=(w*cos(u),w*sin(u),v,w) sage: cylindric_axial=(v*cos(u),v*sin(u),w,w) sage: parabolic_cylindrical=(w*v,(v^2-w^2)/2,u,w) Plot a constant function of each of these to get an idea of what it does:: sage: A = plot3d(2,(u,-pi,pi),(v,0,pi),transformation=rectangular,plot_points=[100,100]) sage: B = plot3d(2,(u,-pi,pi),(v,0,pi),transformation=spherical,plot_points=[100,100]) sage: C = plot3d(2,(u,-pi,pi),(v,0,pi),transformation=cylindric_radial,plot_points=[100,100]) sage: D = plot3d(2,(u,-pi,pi),(v,0,pi),transformation=cylindric_axial,plot_points=[100,100]) sage: E = plot3d(2,(u,-pi,pi),(v,-pi,pi),transformation=parabolic_cylindrical,plot_points=[100,100]) sage: @interact sage: def _(which_plot=[A,B,C,D,E]): ... show(which_plot) Now plot a function:: sage: g=3+sin(4*u)/2+cos(4*v)/2 sage: F = plot3d(g,(u,-pi,pi),(v,0,pi),transformation=rectangular,plot_points=[100,100]) sage: G = plot3d(g,(u,-pi,pi),(v,0,pi),transformation=spherical,plot_points=[100,100]) sage: H = plot3d(g,(u,-pi,pi),(v,0,pi),transformation=cylindric_radial,plot_points=[100,100]) sage: I = plot3d(g,(u,-pi,pi),(v,0,pi),transformation=cylindric_axial,plot_points=[100,100]) sage: J = plot3d(g,(u,-pi,pi),(v,0,pi),transformation=parabolic_cylindrical,plot_points=[100,100]) sage: @interact sage: def _(which_plot=[F, G, H, I, J]): ... show(which_plot) TESTS: Make sure the transformation plots work:: sage: show(A + B + C + D + E) sage: show(F + G + H + I + J) Listing the same plot variable twice gives an error:: sage: x, y = var('x y') sage: plot3d( 4*x*exp(-x^2-y^2), (x,-2,2), (x,-2,2)) Traceback (most recent call last): ... ValueError: range variables should be distinct, but there are duplicates """ if transformation is not None: from sage.symbolic.callable import is_CallableSymbolicExpression # First, determine the parameters for f (from the first item of urange # and vrange, preferably). if len(urange) == 3 and len(vrange) == 3: params = (urange[0], vrange[0]) elif is_CallableSymbolicExpression(f): params = f.variables() else: # There's no way to find out raise ValueError, 'expected 3-tuple for urange and vrange' if isinstance(transformation, (tuple, list)): transformation = _ArbCoordTrans(transformation[0:3], transformation[3]) if isinstance(transformation, _CoordTrans): R = transformation.to_cartesian(f, params) return parametric_plot3d.parametric_plot3d(R, urange, vrange, **kwds) else: raise ValueError, 'unknown transformation type' elif adaptive: P = plot3d_adaptive(f, urange, vrange, **kwds) else: u=fast_float_arg(0) v=fast_float_arg(1) P=parametric_plot3d.parametric_plot3d((u,v,f), urange, vrange, **kwds) P.frame_aspect_ratio([1.0,1.0,0.5]) return P
|
sage: trans=(r*cos(phi),r*sin(phi),z,z)
|
sage: trans=(r*cos(phi),r*sin(phi),z)
|
def plot3d(f, urange, vrange, adaptive=False, transformation=None, **kwds): """ INPUT: - ``f`` - a symbolic expression or function of 2 variables - ``urange`` - a 2-tuple (u_min, u_max) or a 3-tuple (u, u_min, u_max) - ``vrange`` - a 2-tuple (v_min, v_max) or a 3-tuple (v, v_min, v_max) - ``adaptive`` - (default: False) whether to use adaptive refinement to draw the plot (slower, but may look better). This option does NOT work in conjuction with a transformation (see below). - ``mesh`` - bool (default: False) whether to display mesh grid lines - ``dots`` - bool (default: False) whether to display dots at mesh grid points - ``plot_points`` - (default: "automatic") initial number of sample points in each direction; an integer or a pair of integers - ``transformation`` - (default: None) a transformation to apply. May be a 4-tuple (x_func, y_func, z_func, fvar) where the first 3 items indicate a transformation to cartesian coordinates (from your coordinate system) in terms of u, v, and the function variable fvar (for which the value of f will be substituted). May also be a predefined coordinate system transformation like Spherical or Cylindrical. .. note:: ``mesh`` and ``dots`` are not supported when using the Tachyon raytracer renderer. EXAMPLES: We plot a 3d function defined as a Python function:: sage: plot3d(lambda x, y: x^2 + y^2, (-2,2), (-2,2)) We plot the same 3d function but using adaptive refinement:: sage: plot3d(lambda x, y: x^2 + y^2, (-2,2), (-2,2), adaptive=True) Adaptive refinement but with more points:: sage: plot3d(lambda x, y: x^2 + y^2, (-2,2), (-2,2), adaptive=True, initial_depth=5) We plot some 3d symbolic functions:: sage: var('x,y') (x, y) sage: plot3d(x^2 + y^2, (x,-2,2), (y,-2,2)) sage: plot3d(sin(x*y), (x, -pi, pi), (y, -pi, pi)) We give a plot with extra sample points:: sage: var('x,y') (x, y) sage: plot3d(sin(x^2+y^2),(x,-5,5),(y,-5,5), plot_points=200) sage: plot3d(sin(x^2+y^2),(x,-5,5),(y,-5,5), plot_points=[10,100]) A 3d plot with a mesh:: sage: var('x,y') (x, y) sage: plot3d(sin(x-y)*y*cos(x),(x,-3,3),(y,-3,3), mesh=True) Two wobby translucent planes:: sage: x,y = var('x,y') sage: P = plot3d(x+y+sin(x*y), (x,-10,10),(y,-10,10), opacity=0.87, color='blue') sage: Q = plot3d(x-2*y-cos(x*y),(x,-10,10),(y,-10,10),opacity=0.3,color='red') sage: P + Q We draw two parametric surfaces and a transparent plane:: sage: L = plot3d(lambda x,y: 0, (-5,5), (-5,5), color="lightblue", opacity=0.8) sage: P = plot3d(lambda x,y: 4 - x^3 - y^2, (-2,2), (-2,2), color='green') sage: Q = plot3d(lambda x,y: x^3 + y^2 - 4, (-2,2), (-2,2), color='orange') sage: L + P + Q We draw the "Sinus" function (water ripple-like surface):: sage: x, y = var('x y') sage: plot3d(sin(pi*(x^2+y^2))/2,(x,-1,1),(y,-1,1)) Hill and valley (flat surface with a bump and a dent):: sage: x, y = var('x y') sage: plot3d( 4*x*exp(-x^2-y^2), (x,-2,2), (y,-2,2)) An example of a transformation:: sage: r, phi, z = var('r phi z') sage: trans=(r*cos(phi),r*sin(phi),z,z) sage: plot3d(cos(r),(r,0,17*pi/2),(phi,0,2*pi),transformation=trans,opacity=0.87).show(aspect_ratio=(1,1,2),frame=False) Many more examples of transformations:: sage: u, v, w = var('u v w') sage: rectangular=(u,v,w,w) sage: spherical=(w*cos(u)*sin(v),w*sin(u)*sin(v),w*cos(v),w) sage: cylindric_radial=(w*cos(u),w*sin(u),v,w) sage: cylindric_axial=(v*cos(u),v*sin(u),w,w) sage: parabolic_cylindrical=(w*v,(v^2-w^2)/2,u,w) Plot a constant function of each of these to get an idea of what it does:: sage: A = plot3d(2,(u,-pi,pi),(v,0,pi),transformation=rectangular,plot_points=[100,100]) sage: B = plot3d(2,(u,-pi,pi),(v,0,pi),transformation=spherical,plot_points=[100,100]) sage: C = plot3d(2,(u,-pi,pi),(v,0,pi),transformation=cylindric_radial,plot_points=[100,100]) sage: D = plot3d(2,(u,-pi,pi),(v,0,pi),transformation=cylindric_axial,plot_points=[100,100]) sage: E = plot3d(2,(u,-pi,pi),(v,-pi,pi),transformation=parabolic_cylindrical,plot_points=[100,100]) sage: @interact sage: def _(which_plot=[A,B,C,D,E]): ... show(which_plot) Now plot a function:: sage: g=3+sin(4*u)/2+cos(4*v)/2 sage: F = plot3d(g,(u,-pi,pi),(v,0,pi),transformation=rectangular,plot_points=[100,100]) sage: G = plot3d(g,(u,-pi,pi),(v,0,pi),transformation=spherical,plot_points=[100,100]) sage: H = plot3d(g,(u,-pi,pi),(v,0,pi),transformation=cylindric_radial,plot_points=[100,100]) sage: I = plot3d(g,(u,-pi,pi),(v,0,pi),transformation=cylindric_axial,plot_points=[100,100]) sage: J = plot3d(g,(u,-pi,pi),(v,0,pi),transformation=parabolic_cylindrical,plot_points=[100,100]) sage: @interact sage: def _(which_plot=[F, G, H, I, J]): ... show(which_plot) TESTS: Make sure the transformation plots work:: sage: show(A + B + C + D + E) sage: show(F + G + H + I + J) Listing the same plot variable twice gives an error:: sage: x, y = var('x y') sage: plot3d( 4*x*exp(-x^2-y^2), (x,-2,2), (x,-2,2)) Traceback (most recent call last): ... ValueError: range variables should be distinct, but there are duplicates """ if transformation is not None: from sage.symbolic.callable import is_CallableSymbolicExpression # First, determine the parameters for f (from the first item of urange # and vrange, preferably). if len(urange) == 3 and len(vrange) == 3: params = (urange[0], vrange[0]) elif is_CallableSymbolicExpression(f): params = f.variables() else: # There's no way to find out raise ValueError, 'expected 3-tuple for urange and vrange' if isinstance(transformation, (tuple, list)): transformation = _ArbCoordTrans(transformation[0:3], transformation[3]) if isinstance(transformation, _CoordTrans): R = transformation.to_cartesian(f, params) return parametric_plot3d.parametric_plot3d(R, urange, vrange, **kwds) else: raise ValueError, 'unknown transformation type' elif adaptive: P = plot3d_adaptive(f, urange, vrange, **kwds) else: u=fast_float_arg(0) v=fast_float_arg(1) P=parametric_plot3d.parametric_plot3d((u,v,f), urange, vrange, **kwds) P.frame_aspect_ratio([1.0,1.0,0.5]) return P
|
sage: rectangular=(u,v,w,w) sage: spherical=(w*cos(u)*sin(v),w*sin(u)*sin(v),w*cos(v),w) sage: cylindric_radial=(w*cos(u),w*sin(u),v,w) sage: cylindric_axial=(v*cos(u),v*sin(u),w,w) sage: parabolic_cylindrical=(w*v,(v^2-w^2)/2,u,w)
|
sage: rectangular=(u,v,w) sage: spherical=(w*cos(u)*sin(v),w*sin(u)*sin(v),w*cos(v)) sage: cylindric_radial=(w*cos(u),w*sin(u),v) sage: cylindric_axial=(v*cos(u),v*sin(u),w) sage: parabolic_cylindrical=(w*v,(v^2-w^2)/2,u)
|
def plot3d(f, urange, vrange, adaptive=False, transformation=None, **kwds): """ INPUT: - ``f`` - a symbolic expression or function of 2 variables - ``urange`` - a 2-tuple (u_min, u_max) or a 3-tuple (u, u_min, u_max) - ``vrange`` - a 2-tuple (v_min, v_max) or a 3-tuple (v, v_min, v_max) - ``adaptive`` - (default: False) whether to use adaptive refinement to draw the plot (slower, but may look better). This option does NOT work in conjuction with a transformation (see below). - ``mesh`` - bool (default: False) whether to display mesh grid lines - ``dots`` - bool (default: False) whether to display dots at mesh grid points - ``plot_points`` - (default: "automatic") initial number of sample points in each direction; an integer or a pair of integers - ``transformation`` - (default: None) a transformation to apply. May be a 4-tuple (x_func, y_func, z_func, fvar) where the first 3 items indicate a transformation to cartesian coordinates (from your coordinate system) in terms of u, v, and the function variable fvar (for which the value of f will be substituted). May also be a predefined coordinate system transformation like Spherical or Cylindrical. .. note:: ``mesh`` and ``dots`` are not supported when using the Tachyon raytracer renderer. EXAMPLES: We plot a 3d function defined as a Python function:: sage: plot3d(lambda x, y: x^2 + y^2, (-2,2), (-2,2)) We plot the same 3d function but using adaptive refinement:: sage: plot3d(lambda x, y: x^2 + y^2, (-2,2), (-2,2), adaptive=True) Adaptive refinement but with more points:: sage: plot3d(lambda x, y: x^2 + y^2, (-2,2), (-2,2), adaptive=True, initial_depth=5) We plot some 3d symbolic functions:: sage: var('x,y') (x, y) sage: plot3d(x^2 + y^2, (x,-2,2), (y,-2,2)) sage: plot3d(sin(x*y), (x, -pi, pi), (y, -pi, pi)) We give a plot with extra sample points:: sage: var('x,y') (x, y) sage: plot3d(sin(x^2+y^2),(x,-5,5),(y,-5,5), plot_points=200) sage: plot3d(sin(x^2+y^2),(x,-5,5),(y,-5,5), plot_points=[10,100]) A 3d plot with a mesh:: sage: var('x,y') (x, y) sage: plot3d(sin(x-y)*y*cos(x),(x,-3,3),(y,-3,3), mesh=True) Two wobby translucent planes:: sage: x,y = var('x,y') sage: P = plot3d(x+y+sin(x*y), (x,-10,10),(y,-10,10), opacity=0.87, color='blue') sage: Q = plot3d(x-2*y-cos(x*y),(x,-10,10),(y,-10,10),opacity=0.3,color='red') sage: P + Q We draw two parametric surfaces and a transparent plane:: sage: L = plot3d(lambda x,y: 0, (-5,5), (-5,5), color="lightblue", opacity=0.8) sage: P = plot3d(lambda x,y: 4 - x^3 - y^2, (-2,2), (-2,2), color='green') sage: Q = plot3d(lambda x,y: x^3 + y^2 - 4, (-2,2), (-2,2), color='orange') sage: L + P + Q We draw the "Sinus" function (water ripple-like surface):: sage: x, y = var('x y') sage: plot3d(sin(pi*(x^2+y^2))/2,(x,-1,1),(y,-1,1)) Hill and valley (flat surface with a bump and a dent):: sage: x, y = var('x y') sage: plot3d( 4*x*exp(-x^2-y^2), (x,-2,2), (y,-2,2)) An example of a transformation:: sage: r, phi, z = var('r phi z') sage: trans=(r*cos(phi),r*sin(phi),z,z) sage: plot3d(cos(r),(r,0,17*pi/2),(phi,0,2*pi),transformation=trans,opacity=0.87).show(aspect_ratio=(1,1,2),frame=False) Many more examples of transformations:: sage: u, v, w = var('u v w') sage: rectangular=(u,v,w,w) sage: spherical=(w*cos(u)*sin(v),w*sin(u)*sin(v),w*cos(v),w) sage: cylindric_radial=(w*cos(u),w*sin(u),v,w) sage: cylindric_axial=(v*cos(u),v*sin(u),w,w) sage: parabolic_cylindrical=(w*v,(v^2-w^2)/2,u,w) Plot a constant function of each of these to get an idea of what it does:: sage: A = plot3d(2,(u,-pi,pi),(v,0,pi),transformation=rectangular,plot_points=[100,100]) sage: B = plot3d(2,(u,-pi,pi),(v,0,pi),transformation=spherical,plot_points=[100,100]) sage: C = plot3d(2,(u,-pi,pi),(v,0,pi),transformation=cylindric_radial,plot_points=[100,100]) sage: D = plot3d(2,(u,-pi,pi),(v,0,pi),transformation=cylindric_axial,plot_points=[100,100]) sage: E = plot3d(2,(u,-pi,pi),(v,-pi,pi),transformation=parabolic_cylindrical,plot_points=[100,100]) sage: @interact sage: def _(which_plot=[A,B,C,D,E]): ... show(which_plot) Now plot a function:: sage: g=3+sin(4*u)/2+cos(4*v)/2 sage: F = plot3d(g,(u,-pi,pi),(v,0,pi),transformation=rectangular,plot_points=[100,100]) sage: G = plot3d(g,(u,-pi,pi),(v,0,pi),transformation=spherical,plot_points=[100,100]) sage: H = plot3d(g,(u,-pi,pi),(v,0,pi),transformation=cylindric_radial,plot_points=[100,100]) sage: I = plot3d(g,(u,-pi,pi),(v,0,pi),transformation=cylindric_axial,plot_points=[100,100]) sage: J = plot3d(g,(u,-pi,pi),(v,0,pi),transformation=parabolic_cylindrical,plot_points=[100,100]) sage: @interact sage: def _(which_plot=[F, G, H, I, J]): ... show(which_plot) TESTS: Make sure the transformation plots work:: sage: show(A + B + C + D + E) sage: show(F + G + H + I + J) Listing the same plot variable twice gives an error:: sage: x, y = var('x y') sage: plot3d( 4*x*exp(-x^2-y^2), (x,-2,2), (x,-2,2)) Traceback (most recent call last): ... ValueError: range variables should be distinct, but there are duplicates """ if transformation is not None: from sage.symbolic.callable import is_CallableSymbolicExpression # First, determine the parameters for f (from the first item of urange # and vrange, preferably). if len(urange) == 3 and len(vrange) == 3: params = (urange[0], vrange[0]) elif is_CallableSymbolicExpression(f): params = f.variables() else: # There's no way to find out raise ValueError, 'expected 3-tuple for urange and vrange' if isinstance(transformation, (tuple, list)): transformation = _ArbCoordTrans(transformation[0:3], transformation[3]) if isinstance(transformation, _CoordTrans): R = transformation.to_cartesian(f, params) return parametric_plot3d.parametric_plot3d(R, urange, vrange, **kwds) else: raise ValueError, 'unknown transformation type' elif adaptive: P = plot3d_adaptive(f, urange, vrange, **kwds) else: u=fast_float_arg(0) v=fast_float_arg(1) P=parametric_plot3d.parametric_plot3d((u,v,f), urange, vrange, **kwds) P.frame_aspect_ratio([1.0,1.0,0.5]) return P
|
sage: def _(which_plot=[A,B,C,D,E]):
|
... def _(which_plot=[A,B,C,D,E]):
|
sage: def _(which_plot=[A,B,C,D,E]):
|
sage: def _(which_plot=[F, G, H, I, J]):
|
... def _(which_plot=[F, G, H, I, J]):
|
sage: def _(which_plot=[F, G, H, I, J]):
|
else: raise ValueError, 'expected 3-tuple for urange and vrange'
|
sage: def _(which_plot=[F, G, H, I, J]):
|
|
transformation = _ArbCoordTrans(transformation[0:3], transformation[3]) if isinstance(transformation, _CoordTrans):
|
if len(transformation)==3: if params is None: raise ValueError, "must specify independent variable names in the ranges when using generic transformation" indep_vars = params elif len(transformation)==4: indep_vars = transformation[3] transformation = transformation[0:3] else: raise ValueError, "unknown transformation type" all_vars = set(sum([list(s.variables()) for s in transformation],[])) dep_var=all_vars - set(indep_vars) if len(dep_var)==1: dep_var = dep_var.pop() transformation = _ArbitraryCoordinates(transformation, dep_var, indep_vars) else: raise ValueError, "unable to determine the function variable in the transform" if isinstance(transformation, _Coordinates):
|
sage: def _(which_plot=[F, G, H, I, J]):
|
Takes a function and plots it in spherical coordinates in the domain specified by urange and vrange. This function is equivalent to:: sage: var('r,u,u') sage: T = (r*cos(u)*sin(v), r*sin(u)*sin(v), r*cos(v), r)
|
Plots a function in spherical coordinates. This function is equivalent to:: sage: r,u,v=var('r,u,v') sage: f=u*v; urange=(u,0,pi); vrange=(v,0,pi) sage: T = (r*cos(u)*sin(v), r*sin(u)*sin(v), r*cos(v), [u,v])
|
def spherical_plot3d(f, urange, vrange, **kwds): """ Takes a function and plots it in spherical coordinates in the domain specified by urange and vrange. This function is equivalent to:: sage: var('r,u,u') sage: T = (r*cos(u)*sin(v), r*sin(u)*sin(v), r*cos(v), r) sage: plot3d(f, urange, vrange, transformation=T) INPUT: - ``f`` - a symbolic expression or function of two variables. - ``urange`` - a 3-tuple (u, u_min, u_max), the domain of the azimuth variable. - ``vrange`` - a 3-tuple (v, v_min, v_max), the domain of the inclination variable. EXAMPLES: A sphere of radius 2:: sage: spherical_plot3d(2,(x,0,2*pi),(y,0,pi)) A drop of water:: sage: spherical_plot3d(e^-y,(x,0,2*pi),(y,0,pi),opacity=0.5).show(frame=False) An object similar to a heart:: sage: spherical_plot3d((2+cos(2*x))*(y+1),(x,0,2*pi),(y,0,pi),rgbcolor=(1,.1,.1)) Some random figures: :: sage: spherical_plot3d(1+sin(5*x)/5,(x,0,2*pi),(y,0,pi),rgbcolor=(1,0.5,0),plot_points=(80,80),opacity=0.7) :: sage: spherical_plot3d(1+2*cos(2*y),(x,0,3*pi/2),(y,0,pi)).show(aspect_ratio=(1,1,1)) """ return plot3d(f, urange, vrange, transformation=Spherical('r', ['phi', 'theta']), **kwds)
|
return plot3d(f, urange, vrange, transformation=Spherical('r', ['phi', 'theta']), **kwds)
|
return plot3d(f, urange, vrange, transformation=Spherical('radius', ['azimuth', 'inclination']), **kwds)
|
def spherical_plot3d(f, urange, vrange, **kwds): """ Takes a function and plots it in spherical coordinates in the domain specified by urange and vrange. This function is equivalent to:: sage: var('r,u,u') sage: T = (r*cos(u)*sin(v), r*sin(u)*sin(v), r*cos(v), r) sage: plot3d(f, urange, vrange, transformation=T) INPUT: - ``f`` - a symbolic expression or function of two variables. - ``urange`` - a 3-tuple (u, u_min, u_max), the domain of the azimuth variable. - ``vrange`` - a 3-tuple (v, v_min, v_max), the domain of the inclination variable. EXAMPLES: A sphere of radius 2:: sage: spherical_plot3d(2,(x,0,2*pi),(y,0,pi)) A drop of water:: sage: spherical_plot3d(e^-y,(x,0,2*pi),(y,0,pi),opacity=0.5).show(frame=False) An object similar to a heart:: sage: spherical_plot3d((2+cos(2*x))*(y+1),(x,0,2*pi),(y,0,pi),rgbcolor=(1,.1,.1)) Some random figures: :: sage: spherical_plot3d(1+sin(5*x)/5,(x,0,2*pi),(y,0,pi),rgbcolor=(1,0.5,0),plot_points=(80,80),opacity=0.7) :: sage: spherical_plot3d(1+2*cos(2*y),(x,0,3*pi/2),(y,0,pi)).show(aspect_ratio=(1,1,1)) """ return plot3d(f, urange, vrange, transformation=Spherical('r', ['phi', 'theta']), **kwds)
|
Takes a function and plots it in cylindrical coordinates in the domain specified by urange and vrange. This command is equivalent to:: sage: var('r,u,v') sage: T = (r*cos(u), r*sin(u), v, r)
|
Plots a function in cylindrical coordinates. This function is equivalent to:: sage: r,u,v=var('r,u,v') sage: f=u*v; urange=(u,0,pi); vrange=(v,0,pi) sage: T = (r*cos(u), r*sin(u), v, [u,v])
|
def cylindrical_plot3d(f, urange, vrange, **kwds): """ Takes a function and plots it in cylindrical coordinates in the domain specified by urange and vrange. This command is equivalent to:: sage: var('r,u,v') sage: T = (r*cos(u), r*sin(u), v, r) sage: plot3d(f, urange, vrange, transformation=T) INPUT: - ``f`` - a symbolic expression or function of two variables. - ``urange`` - a 3-tuple (u, u_min, u_max), the domain of the azimuth variable. - ``vrange`` - a 3-tuple (v, v_min, v_max), the domain of the elevation (z) variable. EXAMPLES: A portion of a cylinder of radius 2:: sage: var('fi,z') sage: cylindrical_plot3d(2,(fi,0,3*pi/2),(z,-2,2)) Some random figures: :: sage: cylindrical_plot3d(cosh(z),(fi,0,2*pi),(z,-2,2)) :: sage: cylindrical_plot3d(e^(-z^2)*(cos(4*fi)+2)+1,(fi,0,2*pi),(z,-2,2),plot_points=[80,80]).show(aspect_ratio=(1,1,1)) """ return plot3d(f, urange, vrange, transformation=Cylindrical('rho', ['phi', 'z']), **kwds)
|
- ``f`` - a symbolic expression or function of two variables. - ``urange`` - a 3-tuple (u, u_min, u_max), the domain of the azimuth variable. - ``vrange`` - a 3-tuple (v, v_min, v_max), the domain of the elevation (z) variable.
|
- ``f`` - a symbolic expression or function of two variables, representing the radius from the `z`-axis. - ``urange`` - a 3-tuple (u, u_min, u_max), the domain of the azimuth variable. - ``vrange`` - a 3-tuple (v, v_min, v_max), the domain of the elevation (`z`) variable.
|
def cylindrical_plot3d(f, urange, vrange, **kwds): """ Takes a function and plots it in cylindrical coordinates in the domain specified by urange and vrange. This command is equivalent to:: sage: var('r,u,v') sage: T = (r*cos(u), r*sin(u), v, r) sage: plot3d(f, urange, vrange, transformation=T) INPUT: - ``f`` - a symbolic expression or function of two variables. - ``urange`` - a 3-tuple (u, u_min, u_max), the domain of the azimuth variable. - ``vrange`` - a 3-tuple (v, v_min, v_max), the domain of the elevation (z) variable. EXAMPLES: A portion of a cylinder of radius 2:: sage: var('fi,z') sage: cylindrical_plot3d(2,(fi,0,3*pi/2),(z,-2,2)) Some random figures: :: sage: cylindrical_plot3d(cosh(z),(fi,0,2*pi),(z,-2,2)) :: sage: cylindrical_plot3d(e^(-z^2)*(cos(4*fi)+2)+1,(fi,0,2*pi),(z,-2,2),plot_points=[80,80]).show(aspect_ratio=(1,1,1)) """ return plot3d(f, urange, vrange, transformation=Cylindrical('rho', ['phi', 'z']), **kwds)
|
sage: var('fi,z') sage: cylindrical_plot3d(2,(fi,0,3*pi/2),(z,-2,2))
|
sage: theta,z=var('theta,z') sage: cylindrical_plot3d(2,(theta,0,3*pi/2),(z,-2,2))
|
def cylindrical_plot3d(f, urange, vrange, **kwds): """ Takes a function and plots it in cylindrical coordinates in the domain specified by urange and vrange. This command is equivalent to:: sage: var('r,u,v') sage: T = (r*cos(u), r*sin(u), v, r) sage: plot3d(f, urange, vrange, transformation=T) INPUT: - ``f`` - a symbolic expression or function of two variables. - ``urange`` - a 3-tuple (u, u_min, u_max), the domain of the azimuth variable. - ``vrange`` - a 3-tuple (v, v_min, v_max), the domain of the elevation (z) variable. EXAMPLES: A portion of a cylinder of radius 2:: sage: var('fi,z') sage: cylindrical_plot3d(2,(fi,0,3*pi/2),(z,-2,2)) Some random figures: :: sage: cylindrical_plot3d(cosh(z),(fi,0,2*pi),(z,-2,2)) :: sage: cylindrical_plot3d(e^(-z^2)*(cos(4*fi)+2)+1,(fi,0,2*pi),(z,-2,2),plot_points=[80,80]).show(aspect_ratio=(1,1,1)) """ return plot3d(f, urange, vrange, transformation=Cylindrical('rho', ['phi', 'z']), **kwds)
|
sage: cylindrical_plot3d(cosh(z),(fi,0,2*pi),(z,-2,2))
|
sage: cylindrical_plot3d(cosh(z),(theta,0,2*pi),(z,-2,2))
|
def cylindrical_plot3d(f, urange, vrange, **kwds): """ Takes a function and plots it in cylindrical coordinates in the domain specified by urange and vrange. This command is equivalent to:: sage: var('r,u,v') sage: T = (r*cos(u), r*sin(u), v, r) sage: plot3d(f, urange, vrange, transformation=T) INPUT: - ``f`` - a symbolic expression or function of two variables. - ``urange`` - a 3-tuple (u, u_min, u_max), the domain of the azimuth variable. - ``vrange`` - a 3-tuple (v, v_min, v_max), the domain of the elevation (z) variable. EXAMPLES: A portion of a cylinder of radius 2:: sage: var('fi,z') sage: cylindrical_plot3d(2,(fi,0,3*pi/2),(z,-2,2)) Some random figures: :: sage: cylindrical_plot3d(cosh(z),(fi,0,2*pi),(z,-2,2)) :: sage: cylindrical_plot3d(e^(-z^2)*(cos(4*fi)+2)+1,(fi,0,2*pi),(z,-2,2),plot_points=[80,80]).show(aspect_ratio=(1,1,1)) """ return plot3d(f, urange, vrange, transformation=Cylindrical('rho', ['phi', 'z']), **kwds)
|
sage: cylindrical_plot3d(e^(-z^2)*(cos(4*fi)+2)+1,(fi,0,2*pi),(z,-2,2),plot_points=[80,80]).show(aspect_ratio=(1,1,1)) """ return plot3d(f, urange, vrange, transformation=Cylindrical('rho', ['phi', 'z']), **kwds)
|
sage: cylindrical_plot3d(e^(-z^2)*(cos(4*theta)+2)+1,(theta,0,2*pi),(z,-2,2),plot_points=[80,80]).show(aspect_ratio=(1,1,1)) """ return plot3d(f, urange, vrange, transformation=Cylindrical('radius', ['azimuth', 'height']), **kwds)
|
def cylindrical_plot3d(f, urange, vrange, **kwds): """ Takes a function and plots it in cylindrical coordinates in the domain specified by urange and vrange. This command is equivalent to:: sage: var('r,u,v') sage: T = (r*cos(u), r*sin(u), v, r) sage: plot3d(f, urange, vrange, transformation=T) INPUT: - ``f`` - a symbolic expression or function of two variables. - ``urange`` - a 3-tuple (u, u_min, u_max), the domain of the azimuth variable. - ``vrange`` - a 3-tuple (v, v_min, v_max), the domain of the elevation (z) variable. EXAMPLES: A portion of a cylinder of radius 2:: sage: var('fi,z') sage: cylindrical_plot3d(2,(fi,0,3*pi/2),(z,-2,2)) Some random figures: :: sage: cylindrical_plot3d(cosh(z),(fi,0,2*pi),(z,-2,2)) :: sage: cylindrical_plot3d(e^(-z^2)*(cos(4*fi)+2)+1,(fi,0,2*pi),(z,-2,2),plot_points=[80,80]).show(aspect_ratio=(1,1,1)) """ return plot3d(f, urange, vrange, transformation=Cylindrical('rho', ['phi', 'z']), **kwds)
|
""" Theta_Precision = bound
|
sage: Q = QuadraticForm(ZZ, 4, [1,1,1,1, 1,0,0, 1,0, 1]) sage: map(len, Q.vectors_by_length(2)) [1, 12, 12] """ eps = RDF(1e-6) bound = ZZ(floor(bound)) Theta_Precision = bound + eps
|
def vectors_by_length(self, bound): """ Returns a list of short vectors together with their values. This is a naive algorithm which uses the Cholesky decomposition, but does not use the LLL-reduction algorithm. INPUT: bound -- an integer >= 0 OUTPUT: A list L of length (bound + 1) whose entry L[i] is a list of all vectors of length i. Reference: This is a slightly modified version of Cohn's Algorithm 2.7.5 in "A Course in Computational Number Theory", with the increment step moved around and slightly re-indexed to allow clean looping. Note: We could speed this up for very skew matrices by using LLL first, and then changing coordinates back, but for our purposes the simpler method is efficient enough. =) EXAMPLES: sage: Q = DiagonalQuadraticForm(ZZ, [1,1]) sage: Q.vectors_by_length(5) [[[0, 0]], [[0, -1], [-1, 0]], [[-1, -1], [1, -1]], [], [[0, -2], [-2, 0]], [[-1, -2], [1, -2], [-2, -1], [2, -1]]] sage: Q1 = DiagonalQuadraticForm(ZZ, [1,3,5,7]) sage: Q1.vectors_by_length(5) [[[0, 0, 0, 0]], [[-1, 0, 0, 0]], [], [[0, -1, 0, 0]], [[-1, -1, 0, 0], [1, -1, 0, 0], [-2, 0, 0, 0]], [[0, 0, -1, 0]]] """ Theta_Precision = bound ## Unsigned long n = self.dim() ## Make the vector of vectors which have a given value ## (So theta_vec[i] will have all vectors v with Q(v) = i.) empty_vec_list = [[] for i in range(Theta_Precision + 1)] theta_vec = [[] for i in range(Theta_Precision + 1)] ## Initialize Q with zeros and Copy the Cholesky array into Q Q = self.cholesky_decomposition() ## 1. Initialize T = n * [RDF(0)] ## Note: We index the entries as 0 --> n-1 U = n * [RDF(0)] i = n-1 T[i] = RDF(Theta_Precision) U[i] = RDF(0) L = n * [0] x = n * [0] Z = RDF(0) ## 2. Compute bounds Z = sqrt(T[i] / Q[i][i]) L[i] = ZZ(floor(Z - U[i])) x[i] = ZZ(ceil(-Z - U[i]) - 0) done_flag = False Q_val_double = RDF(0) Q_val = 0 ## WARNING: Still need a good way of checking overflow for this value... ## Big loop which runs through all vectors while not done_flag: ## 3b. Main loop -- try to generate a complete vector x (when i=0) while (i > 0): #print " i = ", i #print " T[i] = ", T[i] #print " Q[i][i] = ", Q[i][i] #print " x[i] = ", x[i] #print " U[i] = ", U[i] #print " x[i] + U[i] = ", (x[i] + U[i]) #print " T[i-1] = ", T[i-1] T[i-1] = T[i] - Q[i][i] * (x[i] + U[i]) * (x[i] + U[i]) #print " T[i-1] = ", T[i-1] #print " x = ", x #print i = i - 1 U[i] = 0 for j in range(i+1, n): U[i] = U[i] + Q[i][j] * x[j] ## Now go back and compute the bounds... ## 2. Compute bounds Z = sqrt(T[i] / Q[i][i]) L[i] = ZZ(floor(Z - U[i])) x[i] = ZZ(ceil(-Z - U[i]) - 0) ## 4. Solution found (This happens when i = 0) #print "-- Solution found! --" #print " x = ", x #print " Q_val = Q(x) = ", Q_val Q_val_double = Theta_Precision - T[0] + Q[0][0] * (x[0] + U[0]) * (x[0] + U[0]) Q_val = ZZ(floor(round(Q_val_double))) ## SANITY CHECK: Roundoff Error is < 0.001 if abs(Q_val_double - Q_val) > 0.001: print " x = ", x print " Float = ", Q_val_double, " Long = ", Q_val raise RuntimeError, "The roundoff error is bigger than 0.001, so we should use more precision somewhere..." #print " Float = ", Q_val_double, " Long = ", Q_val, " XX " #print " The float value is ", Q_val_double #print " The associated long value is ", Q_val if (Q_val <= Theta_Precision): #print " Have vector ", x, " with value ", Q_val theta_vec[Q_val].append(deepcopy(x)) ## 5. Check if x = 0, for exit condition. =) j = 0 done_flag = True while (j < n): if (x[j] != 0): done_flag = False j += 1 ## 3a. Increment (and carry if we go out of bounds) x[i] += 1 while (x[i] > L[i]) and (i < n-1): i += 1 x[i] += 1 #print " Leaving ThetaVectors()" return theta_vec
|
empty_vec_list = [[] for i in range(Theta_Precision + 1)] theta_vec = [[] for i in range(Theta_Precision + 1)]
|
theta_vec = [[] for i in range(bound + 1)]
|
def vectors_by_length(self, bound): """ Returns a list of short vectors together with their values. This is a naive algorithm which uses the Cholesky decomposition, but does not use the LLL-reduction algorithm. INPUT: bound -- an integer >= 0 OUTPUT: A list L of length (bound + 1) whose entry L[i] is a list of all vectors of length i. Reference: This is a slightly modified version of Cohn's Algorithm 2.7.5 in "A Course in Computational Number Theory", with the increment step moved around and slightly re-indexed to allow clean looping. Note: We could speed this up for very skew matrices by using LLL first, and then changing coordinates back, but for our purposes the simpler method is efficient enough. =) EXAMPLES: sage: Q = DiagonalQuadraticForm(ZZ, [1,1]) sage: Q.vectors_by_length(5) [[[0, 0]], [[0, -1], [-1, 0]], [[-1, -1], [1, -1]], [], [[0, -2], [-2, 0]], [[-1, -2], [1, -2], [-2, -1], [2, -1]]] sage: Q1 = DiagonalQuadraticForm(ZZ, [1,3,5,7]) sage: Q1.vectors_by_length(5) [[[0, 0, 0, 0]], [[-1, 0, 0, 0]], [], [[0, -1, 0, 0]], [[-1, -1, 0, 0], [1, -1, 0, 0], [-2, 0, 0, 0]], [[0, 0, -1, 0]]] """ Theta_Precision = bound ## Unsigned long n = self.dim() ## Make the vector of vectors which have a given value ## (So theta_vec[i] will have all vectors v with Q(v) = i.) empty_vec_list = [[] for i in range(Theta_Precision + 1)] theta_vec = [[] for i in range(Theta_Precision + 1)] ## Initialize Q with zeros and Copy the Cholesky array into Q Q = self.cholesky_decomposition() ## 1. Initialize T = n * [RDF(0)] ## Note: We index the entries as 0 --> n-1 U = n * [RDF(0)] i = n-1 T[i] = RDF(Theta_Precision) U[i] = RDF(0) L = n * [0] x = n * [0] Z = RDF(0) ## 2. Compute bounds Z = sqrt(T[i] / Q[i][i]) L[i] = ZZ(floor(Z - U[i])) x[i] = ZZ(ceil(-Z - U[i]) - 0) done_flag = False Q_val_double = RDF(0) Q_val = 0 ## WARNING: Still need a good way of checking overflow for this value... ## Big loop which runs through all vectors while not done_flag: ## 3b. Main loop -- try to generate a complete vector x (when i=0) while (i > 0): #print " i = ", i #print " T[i] = ", T[i] #print " Q[i][i] = ", Q[i][i] #print " x[i] = ", x[i] #print " U[i] = ", U[i] #print " x[i] + U[i] = ", (x[i] + U[i]) #print " T[i-1] = ", T[i-1] T[i-1] = T[i] - Q[i][i] * (x[i] + U[i]) * (x[i] + U[i]) #print " T[i-1] = ", T[i-1] #print " x = ", x #print i = i - 1 U[i] = 0 for j in range(i+1, n): U[i] = U[i] + Q[i][j] * x[j] ## Now go back and compute the bounds... ## 2. Compute bounds Z = sqrt(T[i] / Q[i][i]) L[i] = ZZ(floor(Z - U[i])) x[i] = ZZ(ceil(-Z - U[i]) - 0) ## 4. Solution found (This happens when i = 0) #print "-- Solution found! --" #print " x = ", x #print " Q_val = Q(x) = ", Q_val Q_val_double = Theta_Precision - T[0] + Q[0][0] * (x[0] + U[0]) * (x[0] + U[0]) Q_val = ZZ(floor(round(Q_val_double))) ## SANITY CHECK: Roundoff Error is < 0.001 if abs(Q_val_double - Q_val) > 0.001: print " x = ", x print " Float = ", Q_val_double, " Long = ", Q_val raise RuntimeError, "The roundoff error is bigger than 0.001, so we should use more precision somewhere..." #print " Float = ", Q_val_double, " Long = ", Q_val, " XX " #print " The float value is ", Q_val_double #print " The associated long value is ", Q_val if (Q_val <= Theta_Precision): #print " Have vector ", x, " with value ", Q_val theta_vec[Q_val].append(deepcopy(x)) ## 5. Check if x = 0, for exit condition. =) j = 0 done_flag = True while (j < n): if (x[j] != 0): done_flag = False j += 1 ## 3a. Increment (and carry if we go out of bounds) x[i] += 1 while (x[i] > L[i]) and (i < n-1): i += 1 x[i] += 1 #print " Leaving ThetaVectors()" return theta_vec
|
Z = sqrt(T[i] / Q[i][i]) L[i] = ZZ(floor(Z - U[i])) x[i] = ZZ(ceil(-Z - U[i]) - 0)
|
Z = (T[i] / Q[i][i]).sqrt(extend=False) L[i] = ( Z - U[i]).floor() x[i] = (-Z - U[i]).ceil()
|
def vectors_by_length(self, bound): """ Returns a list of short vectors together with their values. This is a naive algorithm which uses the Cholesky decomposition, but does not use the LLL-reduction algorithm. INPUT: bound -- an integer >= 0 OUTPUT: A list L of length (bound + 1) whose entry L[i] is a list of all vectors of length i. Reference: This is a slightly modified version of Cohn's Algorithm 2.7.5 in "A Course in Computational Number Theory", with the increment step moved around and slightly re-indexed to allow clean looping. Note: We could speed this up for very skew matrices by using LLL first, and then changing coordinates back, but for our purposes the simpler method is efficient enough. =) EXAMPLES: sage: Q = DiagonalQuadraticForm(ZZ, [1,1]) sage: Q.vectors_by_length(5) [[[0, 0]], [[0, -1], [-1, 0]], [[-1, -1], [1, -1]], [], [[0, -2], [-2, 0]], [[-1, -2], [1, -2], [-2, -1], [2, -1]]] sage: Q1 = DiagonalQuadraticForm(ZZ, [1,3,5,7]) sage: Q1.vectors_by_length(5) [[[0, 0, 0, 0]], [[-1, 0, 0, 0]], [], [[0, -1, 0, 0]], [[-1, -1, 0, 0], [1, -1, 0, 0], [-2, 0, 0, 0]], [[0, 0, -1, 0]]] """ Theta_Precision = bound ## Unsigned long n = self.dim() ## Make the vector of vectors which have a given value ## (So theta_vec[i] will have all vectors v with Q(v) = i.) empty_vec_list = [[] for i in range(Theta_Precision + 1)] theta_vec = [[] for i in range(Theta_Precision + 1)] ## Initialize Q with zeros and Copy the Cholesky array into Q Q = self.cholesky_decomposition() ## 1. Initialize T = n * [RDF(0)] ## Note: We index the entries as 0 --> n-1 U = n * [RDF(0)] i = n-1 T[i] = RDF(Theta_Precision) U[i] = RDF(0) L = n * [0] x = n * [0] Z = RDF(0) ## 2. Compute bounds Z = sqrt(T[i] / Q[i][i]) L[i] = ZZ(floor(Z - U[i])) x[i] = ZZ(ceil(-Z - U[i]) - 0) done_flag = False Q_val_double = RDF(0) Q_val = 0 ## WARNING: Still need a good way of checking overflow for this value... ## Big loop which runs through all vectors while not done_flag: ## 3b. Main loop -- try to generate a complete vector x (when i=0) while (i > 0): #print " i = ", i #print " T[i] = ", T[i] #print " Q[i][i] = ", Q[i][i] #print " x[i] = ", x[i] #print " U[i] = ", U[i] #print " x[i] + U[i] = ", (x[i] + U[i]) #print " T[i-1] = ", T[i-1] T[i-1] = T[i] - Q[i][i] * (x[i] + U[i]) * (x[i] + U[i]) #print " T[i-1] = ", T[i-1] #print " x = ", x #print i = i - 1 U[i] = 0 for j in range(i+1, n): U[i] = U[i] + Q[i][j] * x[j] ## Now go back and compute the bounds... ## 2. Compute bounds Z = sqrt(T[i] / Q[i][i]) L[i] = ZZ(floor(Z - U[i])) x[i] = ZZ(ceil(-Z - U[i]) - 0) ## 4. Solution found (This happens when i = 0) #print "-- Solution found! --" #print " x = ", x #print " Q_val = Q(x) = ", Q_val Q_val_double = Theta_Precision - T[0] + Q[0][0] * (x[0] + U[0]) * (x[0] + U[0]) Q_val = ZZ(floor(round(Q_val_double))) ## SANITY CHECK: Roundoff Error is < 0.001 if abs(Q_val_double - Q_val) > 0.001: print " x = ", x print " Float = ", Q_val_double, " Long = ", Q_val raise RuntimeError, "The roundoff error is bigger than 0.001, so we should use more precision somewhere..." #print " Float = ", Q_val_double, " Long = ", Q_val, " XX " #print " The float value is ", Q_val_double #print " The associated long value is ", Q_val if (Q_val <= Theta_Precision): #print " Have vector ", x, " with value ", Q_val theta_vec[Q_val].append(deepcopy(x)) ## 5. Check if x = 0, for exit condition. =) j = 0 done_flag = True while (j < n): if (x[j] != 0): done_flag = False j += 1 ## 3a. Increment (and carry if we go out of bounds) x[i] += 1 while (x[i] > L[i]) and (i < n-1): i += 1 x[i] += 1 #print " Leaving ThetaVectors()" return theta_vec
|
Q_val = ZZ(floor(round(Q_val_double)))
|
Q_val = Q_val_double.round()
|
def vectors_by_length(self, bound): """ Returns a list of short vectors together with their values. This is a naive algorithm which uses the Cholesky decomposition, but does not use the LLL-reduction algorithm. INPUT: bound -- an integer >= 0 OUTPUT: A list L of length (bound + 1) whose entry L[i] is a list of all vectors of length i. Reference: This is a slightly modified version of Cohn's Algorithm 2.7.5 in "A Course in Computational Number Theory", with the increment step moved around and slightly re-indexed to allow clean looping. Note: We could speed this up for very skew matrices by using LLL first, and then changing coordinates back, but for our purposes the simpler method is efficient enough. =) EXAMPLES: sage: Q = DiagonalQuadraticForm(ZZ, [1,1]) sage: Q.vectors_by_length(5) [[[0, 0]], [[0, -1], [-1, 0]], [[-1, -1], [1, -1]], [], [[0, -2], [-2, 0]], [[-1, -2], [1, -2], [-2, -1], [2, -1]]] sage: Q1 = DiagonalQuadraticForm(ZZ, [1,3,5,7]) sage: Q1.vectors_by_length(5) [[[0, 0, 0, 0]], [[-1, 0, 0, 0]], [], [[0, -1, 0, 0]], [[-1, -1, 0, 0], [1, -1, 0, 0], [-2, 0, 0, 0]], [[0, 0, -1, 0]]] """ Theta_Precision = bound ## Unsigned long n = self.dim() ## Make the vector of vectors which have a given value ## (So theta_vec[i] will have all vectors v with Q(v) = i.) empty_vec_list = [[] for i in range(Theta_Precision + 1)] theta_vec = [[] for i in range(Theta_Precision + 1)] ## Initialize Q with zeros and Copy the Cholesky array into Q Q = self.cholesky_decomposition() ## 1. Initialize T = n * [RDF(0)] ## Note: We index the entries as 0 --> n-1 U = n * [RDF(0)] i = n-1 T[i] = RDF(Theta_Precision) U[i] = RDF(0) L = n * [0] x = n * [0] Z = RDF(0) ## 2. Compute bounds Z = sqrt(T[i] / Q[i][i]) L[i] = ZZ(floor(Z - U[i])) x[i] = ZZ(ceil(-Z - U[i]) - 0) done_flag = False Q_val_double = RDF(0) Q_val = 0 ## WARNING: Still need a good way of checking overflow for this value... ## Big loop which runs through all vectors while not done_flag: ## 3b. Main loop -- try to generate a complete vector x (when i=0) while (i > 0): #print " i = ", i #print " T[i] = ", T[i] #print " Q[i][i] = ", Q[i][i] #print " x[i] = ", x[i] #print " U[i] = ", U[i] #print " x[i] + U[i] = ", (x[i] + U[i]) #print " T[i-1] = ", T[i-1] T[i-1] = T[i] - Q[i][i] * (x[i] + U[i]) * (x[i] + U[i]) #print " T[i-1] = ", T[i-1] #print " x = ", x #print i = i - 1 U[i] = 0 for j in range(i+1, n): U[i] = U[i] + Q[i][j] * x[j] ## Now go back and compute the bounds... ## 2. Compute bounds Z = sqrt(T[i] / Q[i][i]) L[i] = ZZ(floor(Z - U[i])) x[i] = ZZ(ceil(-Z - U[i]) - 0) ## 4. Solution found (This happens when i = 0) #print "-- Solution found! --" #print " x = ", x #print " Q_val = Q(x) = ", Q_val Q_val_double = Theta_Precision - T[0] + Q[0][0] * (x[0] + U[0]) * (x[0] + U[0]) Q_val = ZZ(floor(round(Q_val_double))) ## SANITY CHECK: Roundoff Error is < 0.001 if abs(Q_val_double - Q_val) > 0.001: print " x = ", x print " Float = ", Q_val_double, " Long = ", Q_val raise RuntimeError, "The roundoff error is bigger than 0.001, so we should use more precision somewhere..." #print " Float = ", Q_val_double, " Long = ", Q_val, " XX " #print " The float value is ", Q_val_double #print " The associated long value is ", Q_val if (Q_val <= Theta_Precision): #print " Have vector ", x, " with value ", Q_val theta_vec[Q_val].append(deepcopy(x)) ## 5. Check if x = 0, for exit condition. =) j = 0 done_flag = True while (j < n): if (x[j] != 0): done_flag = False j += 1 ## 3a. Increment (and carry if we go out of bounds) x[i] += 1 while (x[i] > L[i]) and (i < n-1): i += 1 x[i] += 1 #print " Leaving ThetaVectors()" return theta_vec
|
if (Q_val <= Theta_Precision):
|
if (Q_val <= bound):
|
def vectors_by_length(self, bound): """ Returns a list of short vectors together with their values. This is a naive algorithm which uses the Cholesky decomposition, but does not use the LLL-reduction algorithm. INPUT: bound -- an integer >= 0 OUTPUT: A list L of length (bound + 1) whose entry L[i] is a list of all vectors of length i. Reference: This is a slightly modified version of Cohn's Algorithm 2.7.5 in "A Course in Computational Number Theory", with the increment step moved around and slightly re-indexed to allow clean looping. Note: We could speed this up for very skew matrices by using LLL first, and then changing coordinates back, but for our purposes the simpler method is efficient enough. =) EXAMPLES: sage: Q = DiagonalQuadraticForm(ZZ, [1,1]) sage: Q.vectors_by_length(5) [[[0, 0]], [[0, -1], [-1, 0]], [[-1, -1], [1, -1]], [], [[0, -2], [-2, 0]], [[-1, -2], [1, -2], [-2, -1], [2, -1]]] sage: Q1 = DiagonalQuadraticForm(ZZ, [1,3,5,7]) sage: Q1.vectors_by_length(5) [[[0, 0, 0, 0]], [[-1, 0, 0, 0]], [], [[0, -1, 0, 0]], [[-1, -1, 0, 0], [1, -1, 0, 0], [-2, 0, 0, 0]], [[0, 0, -1, 0]]] """ Theta_Precision = bound ## Unsigned long n = self.dim() ## Make the vector of vectors which have a given value ## (So theta_vec[i] will have all vectors v with Q(v) = i.) empty_vec_list = [[] for i in range(Theta_Precision + 1)] theta_vec = [[] for i in range(Theta_Precision + 1)] ## Initialize Q with zeros and Copy the Cholesky array into Q Q = self.cholesky_decomposition() ## 1. Initialize T = n * [RDF(0)] ## Note: We index the entries as 0 --> n-1 U = n * [RDF(0)] i = n-1 T[i] = RDF(Theta_Precision) U[i] = RDF(0) L = n * [0] x = n * [0] Z = RDF(0) ## 2. Compute bounds Z = sqrt(T[i] / Q[i][i]) L[i] = ZZ(floor(Z - U[i])) x[i] = ZZ(ceil(-Z - U[i]) - 0) done_flag = False Q_val_double = RDF(0) Q_val = 0 ## WARNING: Still need a good way of checking overflow for this value... ## Big loop which runs through all vectors while not done_flag: ## 3b. Main loop -- try to generate a complete vector x (when i=0) while (i > 0): #print " i = ", i #print " T[i] = ", T[i] #print " Q[i][i] = ", Q[i][i] #print " x[i] = ", x[i] #print " U[i] = ", U[i] #print " x[i] + U[i] = ", (x[i] + U[i]) #print " T[i-1] = ", T[i-1] T[i-1] = T[i] - Q[i][i] * (x[i] + U[i]) * (x[i] + U[i]) #print " T[i-1] = ", T[i-1] #print " x = ", x #print i = i - 1 U[i] = 0 for j in range(i+1, n): U[i] = U[i] + Q[i][j] * x[j] ## Now go back and compute the bounds... ## 2. Compute bounds Z = sqrt(T[i] / Q[i][i]) L[i] = ZZ(floor(Z - U[i])) x[i] = ZZ(ceil(-Z - U[i]) - 0) ## 4. Solution found (This happens when i = 0) #print "-- Solution found! --" #print " x = ", x #print " Q_val = Q(x) = ", Q_val Q_val_double = Theta_Precision - T[0] + Q[0][0] * (x[0] + U[0]) * (x[0] + U[0]) Q_val = ZZ(floor(round(Q_val_double))) ## SANITY CHECK: Roundoff Error is < 0.001 if abs(Q_val_double - Q_val) > 0.001: print " x = ", x print " Float = ", Q_val_double, " Long = ", Q_val raise RuntimeError, "The roundoff error is bigger than 0.001, so we should use more precision somewhere..." #print " Float = ", Q_val_double, " Long = ", Q_val, " XX " #print " The float value is ", Q_val_double #print " The associated long value is ", Q_val if (Q_val <= Theta_Precision): #print " Have vector ", x, " with value ", Q_val theta_vec[Q_val].append(deepcopy(x)) ## 5. Check if x = 0, for exit condition. =) j = 0 done_flag = True while (j < n): if (x[j] != 0): done_flag = False j += 1 ## 3a. Increment (and carry if we go out of bounds) x[i] += 1 while (x[i] > L[i]) and (i < n-1): i += 1 x[i] += 1 #print " Leaving ThetaVectors()" return theta_vec
|
n = x.parent()(1)
|
n = parent(x)(1)
|
def squarefree_part(x): """ Returns the square free part of `x`, i.e., a divisor `z` such that `x = z y^2`, for a perfect square `y^2`. EXAMPLES:: sage: squarefree_part(100) 1 sage: squarefree_part(12) 3 sage: squarefree_part(10) 10 :: sage: x = QQ['x'].0 sage: S = squarefree_part(-9*x*(x-6)^7*(x-3)^2); S -9*x^2 + 54*x sage: S.factor() (-9) * (x - 6) * x :: sage: f = (x^3 + x + 1)^3*(x-1); f x^10 - x^9 + 3*x^8 + 3*x^5 - 2*x^4 - x^3 - 2*x - 1 sage: g = squarefree_part(f); g x^4 - x^3 + x^2 - 1 sage: g.factor() (x - 1) * (x^3 + x + 1) """ try: return x.squarefree_part() except AttributeError: pass F = factor(x) n = x.parent()(1) for p, e in F: if e%2 != 0: n *= p return n * F.unit()
|
bug reported in trac
|
Bug reported in trac
|
sage: def my_carmichael(n):
|
import sage.rings.integer n = sage.rings.integer.Integer(n)
|
n = Integer(n)
|
sage: def my_carmichael(n):
|
return map(lambda x: int(x), list(n.binary()[-k:]))
|
return map(int, list(n.binary()[-k:]))
|
def least_significant_bits(n, k): r""" Return the ``k`` least significant bits of ``n``. INPUT: - ``n`` -- an integer. - ``k`` -- a positive integer. OUTPUT: - The ``k`` least significant bits of the integer ``n``. If ``k=1``, then return the parity bit of the integer ``n``. Let `b` be the binary representation of ``n``, where `m` is the length of the binary string `b`. If `k \geq m`, then return the binary representation of ``n``. EXAMPLES: Obtain the parity bits of some integers:: sage: from sage.crypto.util import least_significant_bits sage: least_significant_bits(0, 1) [0] sage: least_significant_bits(2, 1) [0] sage: least_significant_bits(3, 1) [1] sage: least_significant_bits(-2, 1) [0] sage: least_significant_bits(-3, 1) [1] Obtain the 4 least significant bits of some integers:: sage: least_significant_bits(101, 4) [0, 1, 0, 1] sage: least_significant_bits(-101, 4) [0, 1, 0, 1] sage: least_significant_bits(124, 4) [1, 1, 0, 0] sage: least_significant_bits(-124, 4) [1, 1, 0, 0] The binary representation of 123:: sage: n = 123; b = n.binary(); b '1111011' sage: least_significant_bits(n, len(b)) [1, 1, 1, 1, 0, 1, 1] """ return map(lambda x: int(x), list(n.binary()[-k:]))
|
def CharacteristicSturmianWord(self, cf, alphabet=(0, 1), bits=None): r""" Returns the characteristic Sturmian word of the given slope ``cf``. The `n`-th term of the characteristic Sturmian word of an irrational slope `\alpha` is `\lfloor\alpha(n+1)\rfloor - \lfloor\alpha n\rfloor + \lfloor\alpha\rfloor`. [1]
|
def CharacteristicSturmianWord(self, slope, alphabet=(0, 1), bits=None): r""" Returns the characteristic Sturmian word (also called standard Sturmian word) of given slope. Over a binary alphabet `\{a,b\}`, the characteristic Sturmian word `c_\alpha` of slope `\alpha` is the infinite word satisfying `s_{\alpha,0} = ac_\alpha` and `s'_{\alpha,0} = bc_\alpha`, where `s_{\alpha,0}` and `s'_{\alpha,0}` are respectively the lower and upper mechanical words with slope `\alpha` and intercept `0`. Equivalently, `c_\alpha = s_{\alpha,\alpha} = s'_{\alpha,\alpha}`. Let `\alpha = [0, d_1 + 1, d_2, d_3, \ldots]` be the continued fraction expansion of `\alpha`. It has been shown that the characteristic Sturmian word of slope `\alpha` is also the limit of the sequence: `s_0 = b, s_1 = a, \ldots, s_{n+1} = s_n^{d_n} s_{n-1}` for `n > 0`. See Section 2.1 of [1] for more details.
|
def CharacteristicSturmianWord(self, cf, alphabet=(0, 1), bits=None): r""" Returns the characteristic Sturmian word of the given slope ``cf``.
|
- ``cf`` - the slope of the word. It can be one of the following :
|
- ``slope`` - the slope of the word. It can be one of the following :
|
def CharacteristicSturmianWord(self, cf, alphabet=(0, 1), bits=None): r""" Returns the characteristic Sturmian word of the given slope ``cf``.
|
- ``bits`` - integer (optional and considered only if ``cf`` is a real number) the number of bits to consider when computing the
|
- ``bits`` - integer (optional and considered only if ``slope`` is a real number) the number of bits to consider when computing the
|
def CharacteristicSturmianWord(self, cf, alphabet=(0, 1), bits=None): r""" Returns the characteristic Sturmian word of the given slope ``cf``.
|
slope `\alpha` is the limit of the sequence: `s_0 = 1`, `s_1 = 0`
|
slope `\alpha` is the limit of the sequence: `s_0 = b`, `s_1 = a`
|
def CharacteristicSturmianWord(self, cf, alphabet=(0, 1), bits=None): r""" Returns the characteristic Sturmian word of the given slope ``cf``.
|
The characteristic sturmian word of slope `(\sqrt(3)-1)/2`::
|
The characteristic sturmian word of slope `(\sqrt{3}-1)/2`::
|
sage: def cf():
|
`(\sqrt(3)-1)/2`::
|
`(\sqrt{3}-1)/2`::
|
sage: def cf():
|
sturmian word of slope `(\sqrt(3)-1)/2`::
|
sturmian word of slope `(\sqrt{3}-1)/2`::
|
sage: def cf():
|
NotImplementedError: The argument cf (=5/4) must be in ]0,1[.
|
ValueError: The argument slope (=5/4) must be in ]0,1[.
|
sage: def cf():
|
if cf in RR: if not 0 < cf < 1: msg = "The argument cf (=%s) must be in ]0,1[."%cf raise NotImplementedError, msg
|
if slope in RR: if not 0 < slope < 1: msg = "The argument slope (=%s) must be in ]0,1[."%slope raise ValueError, msg
|
sage: def cf():
|
cf = iter(CFF(cf, bits=bits))
|
cf = iter(CFF(slope, bits=bits))
|
sage: def cf():
|
elif hasattr(cf, '__iter__'): cf = iter(cf)
|
elif hasattr(slope, '__iter__'): cf = iter(slope)
|
sage: def cf():
|
raise TypeError("cf (=%s) must be a real number"%cf +
|
raise TypeError("slope (=%s) must be a real number"%slope +
|
sage: def cf():
|
Returns the lower mechanical word. The word `s_{\alpha,\rho}` is the *lower mechanical word* with slope `\alpha` and intercept `\rho` defined by
|
Returns the lower mechanical word with slope `\alpha` and intercept `\rho` The lower mechanical word `s_{\alpha,\rho}` with slope `\alpha` and intercept `\rho` is defined by
|
def LowerMechanicalWord(self, alpha, rho=0, alphabet=None): r""" Returns the lower mechanical word.
|
\lfloor\alpha n + \rho\rfloor`. [1]
|
\lfloor\alpha n + \rho\rfloor` [1].
|
def LowerMechanicalWord(self, alpha, rho=0, alphabet=None): r""" Returns the lower mechanical word.
|
raise NotImplementedError, msg
|
raise ValueError, msg
|
def LowerMechanicalWord(self, alpha, rho=0, alphabet=None): r""" Returns the lower mechanical word.
|
Returns the upper mechanical word. The word `s'_{\alpha,\rho}` is the *upper mechanical word* with slope `\alpha` and intercept `\rho` defined by
|
Returns the upper mechanical word with slope `\alpha` and intercept `\rho` The upper mechanical word `s'_{\alpha,\rho}` with slope `\alpha` and intercept `\rho` is defined by
|
def UpperMechanicalWord(self, alpha, rho=0, alphabet=None): r""" Returns the upper mechanical word.
|
raise NotImplementedError, msg
|
raise ValueError, msg
|
def UpperMechanicalWord(self, alpha, rho=0, alphabet=None): r""" Returns the upper mechanical word.
|
"""
|
r"""
|
def strip_answer(self, s): """ Returns the string s with Matlab's answer prompt removed. EXAMPLES:: sage: s = '\nans =\n\n 2\n' sage: matlab.strip_answer(s) ' 2' """ i = s.find('=') return s[i+1:].strip('\n')
|
The error occurs only when printed::
|
The error only occurs upon printing::
|
... def __repr__(self):
|
.. rubric:: Common Usage:
|
Most of the time, ``__repr__`` methods are only called during user interaction, and therefore need not be fast; and indeed there are objects ``x`` in Sage such ``x.__repr__()`` is time consuming.
|
... def __repr__(self):
|
A priori, since they are mostly called during user interaction, there is no particular need to write fast ``__repr__`` methods, and indeed there are some objects ``x`` whose call ``x.__repr__()`` is quite time expensive. However, there are several use case where it is actually called and when the results is simply discarded. In particular writing ``"%s"%x`` actually calls ``x.__repr__()`` even the results is not printed. A typical use case is during tests when there is a tester which tests an assertion and prints an error message on failure::
|
There are however some uses cases where many format strings are constructed but not actually printed. This includes error handling messages in :mod:`unittest` or :class:`TestSuite` executions::
|
... def __repr__(self):
|
I the previous case ``QQ.__repr__()`` has been called. To show this we replace QQ in the format string argument with out broken object::
|
In the above ``QQ.__repr__()`` has been called, and the result immediately discarded. To demonstrate this we replace ``QQ`` in the format string argument with our broken object::
|
... def __repr__(self):
|
There is no need to call ``IDontLikeBeingPrinted().__repr__()``, but itx can't be avoided with usual strings. Note that with the usual assert, the call is not performed::
|
This behavior can induce major performance penalties when testing. Note that this issue does not impact the usual assert:
|
... def __repr__(self):
|
We now check that :class:`LazyFormat` indeed solve the assertion problem::
|
We now check that :class:`LazyFormat` indeed solves the assertion problem::
|
... def __repr__(self):
|
Binds the lazy format with its parameters
|
Binds the lazy format string with its parameters
|
def __mod__(self, args): """ Binds the lazy format with its parameters
|
raise ValueError, "%s is not a valid perfect matching: all elements of the list must be pairs"%p
|
raise ValueError, ("%s is not a valid perfect matching:\n" "all elements of the list must be pairs"%p)
|
def __classcall_private__(cls,p): r""" This function tries to recognize the input (it can be either a list or a tuple of pairs, or a fix-point free involution given as a list or as a permutation), constructs the parent (enumerated set of PerfectMatchings of the ground set) and calls the __init__ function to construct our object.
|
raise ValueError, "%s is not a valid perfect matching: there are some repetitions"%p
|
raise ValueError, ("%s is not a valid perfect matching:\n" "there are some repetitions"%p)
|
def __classcall_private__(cls,p): r""" This function tries to recognize the input (it can be either a list or a tuple of pairs, or a fix-point free involution given as a list or as a permutation), constructs the parent (enumerated set of PerfectMatchings of the ground set) and calls the __init__ function to construct our object.
|
or isinstance(p,sage.combinat.permutation.Permutation_class)):
|
or isinstance(p,Permutation_class)):
|
def __classcall_private__(cls,p): r""" This function tries to recognize the input (it can be either a list or a tuple of pairs, or a fix-point free involution given as a list or as a permutation), constructs the parent (enumerated set of PerfectMatchings of the ground set) and calls the __init__ function to construct our object.
|
s="The permutation p (= %s) is not a fixpoint-free involution"%p raise ValueError,s
|
raise ValueError, ("The permutation p (= %s) is not a " "fixed point free involution"%p)
|
def __classcall_private__(cls,p): r""" This function tries to recognize the input (it can be either a list or a tuple of pairs, or a fix-point free involution given as a list or as a permutation), constructs the parent (enumerated set of PerfectMatchings of the ground set) and calls the __init__ function to construct our object.
|
We can plot with this transform. Remember that the independent variable is the radius, and the dependent variables are the
|
We can plot with this transform. Remember that the dependent variable is the radius, and the independent variables are the
|
def transform(self, **kwds): """ EXAMPLE:: sage: from sage.plot.plot3d.plot3d import _ArbitraryCoordinates sage: x, y, z = var('x y z') sage: T = _ArbitraryCoordinates((x + y, x - y, z), x,[y,z])
|
We can plot with this transform. Remember that the independent variable is the height, and the dependent variables are the
|
We can plot with this transform. Remember that the dependent variable is the height, and the independent variables are the
|
def transform(self, radius=None, azimuth=None, inclination=None): """ A spherical coordinates transform.
|
... __metaclass__ = sage.structure.unique_representation.ClasscallMetaclass
|
... __metaclass__ = ClasscallMetaclass
|
def __call__(cls, *args, **options): """ This method implements ``cls(<some arguments>)``.
|
... print "calling call_cls"
|
... print "calling classcall"
|
... def __classcall__(cls):
|
calling call_cls
|
calling classcall
|
... def __init__(self):
|
try:
|
if '__classcall_private__' in cls.__dict__: return cls.__classcall_private__(cls, *args, **options) elif hasattr(cls, "__classcall__"):
|
... def __init__(self):
|
except AttributeError:
|
else:
|
... def __init__(self):
|
Return a new Weierstrass model of self under the standard transformation `(u,r,s,,t)`
|
Return a new Weierstrass model of self under the standard transformation `(u,r,s,t)`
|
def change_weierstrass_model(self, *urst): r""" Return a new Weierstrass model of self under the standard transformation `(u,r,s,,t)` .. math:: (x,y) \mapsto (x',y') = (u^2xr , u^3y + su^2x' + t). EXAMPLES:: sage: E = EllipticCurve('15a') sage: F1 = E.change_weierstrass_model([1/2,0,0,0]); F1 Elliptic Curve defined by y^2 + 2*x*y + 8*y = x^3 + 4*x^2 - 160*x - 640 over Rational Field sage: F2 = E.change_weierstrass_model([7,2,1/3,5]); F2 Elliptic Curve defined by y^2 + 5/21*x*y + 13/343*y = x^3 + 59/441*x^2 - 10/7203*x - 58/117649 over Rational Field sage: F1.is_isomorphic(F2) True """ if isinstance(urst[0], (tuple, list)): urst = urst[0] return constructor.EllipticCurve((wm.baseWI(*urst))(self.ainvs()))
|
(x,y) \mapsto (x',y') = (u^2xr , u^3y + su^2x' + t).
|
(x,y) \mapsto (x',y') = (u^2x + r , u^3y + su^2x + t).
|
def change_weierstrass_model(self, *urst): r""" Return a new Weierstrass model of self under the standard transformation `(u,r,s,,t)` .. math:: (x,y) \mapsto (x',y') = (u^2xr , u^3y + su^2x' + t). EXAMPLES:: sage: E = EllipticCurve('15a') sage: F1 = E.change_weierstrass_model([1/2,0,0,0]); F1 Elliptic Curve defined by y^2 + 2*x*y + 8*y = x^3 + 4*x^2 - 160*x - 640 over Rational Field sage: F2 = E.change_weierstrass_model([7,2,1/3,5]); F2 Elliptic Curve defined by y^2 + 5/21*x*y + 13/343*y = x^3 + 59/441*x^2 - 10/7203*x - 58/117649 over Rational Field sage: F1.is_isomorphic(F2) True """ if isinstance(urst[0], (tuple, list)): urst = urst[0] return constructor.EllipticCurve((wm.baseWI(*urst))(self.ainvs()))
|
if options['labels']:
|
if options.get('labels', False):
|
def _render_on_subplot(self, subplot): """ TESTS:
|
if options['colorbar']:
|
if options.get('colorbar', False):
|
def _render_on_subplot(self, subplot): """ TESTS:
|
dict(contours=[-1e307, 0, 1e307], cmap=cmap, fill=True, labels=False, **options)))
|
dict(contours=[-1e307, 0, 1e307], cmap=cmap, fill=True, **options)))
|
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
|
contours=[0], cmap=[bordercol], fill=False, labels=False, **options)))
|
contours=[0], cmap=[bordercol], fill=False, **options)))
|
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
|
sage: def is_4regular(G): ... D = G.degree_sequence() ... return all(d == 4 for d in D) sage: is_4regular(G)
|
sage: G.is_regular(4)
|
sage: def is_4regular(G):
|
self.n = ZZ(max(S)+1).exact_log(2)
|
self.n = ZZ(max(S)).nbits()
|
def __init__(self, *args, **kwargs): """ Construct a substitution box (S-box) for a given lookup table `S`.
|
and the fourth has no control points: path = [[p1, c1, c2, p2], [c3, c4, p3], [c5, p4], [p5], ...]
|
and the fourth has no control points:: path = [[p1, c1, c2, p2], [c3, c4, p3], [c5, p4], [p5], ...]
|
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
|
EXAMPLES:
|
EXAMPLES::
|
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
|
To construct a simple curve, create a list containing a single list:
|
To construct a simple curve, create a list containing a single list::
|
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
|
Draw a frame in 3D. Primarily used as a helper function for creating frames for 3D graphics viewing.
|
Draw a frame in 3-D. Primarily used as a helper function for creating frames for 3-D graphics viewing.
|
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
|
list, tuple, or vector
|
list, tuple, or vector.
|
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
|
Draw correct labels for a given frame in 3D. Primarily used as a helper function for creating frames for 3D graphics
|
Draw correct labels for a given frame in 3-D. Primarily used as a helper function for creating frames for 3-D graphics
|
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
|
list, tuple, or vector
|
list, tuple, or vector.
|
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
|
raise ValueError, "Ensure the upper right labels are above and to the right of the lower left labels."
|
raise ValueError("Ensure the upper right labels are above and to the right of the lower left labels.")
|
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
|
Draw a ruler in 3D, with major and minor ticks.
|
Draw a ruler in 3-D, with major and minor ticks.
|
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
|
tuple, or vector
|
tuple, or vector.
|
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
|
or vector
|
or vector.
|
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
|
shown on the ruler
|
shown on the 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
|
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
|
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.
|
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
|
options for lines which are also available.
|
options for lines, which are also available.
|
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
|
Draw a frame made of 3D rulers, with major and minor ticks.
|
Draw a frame made of 3-D rulers, with major and minor ticks.
|
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)
|
list, tuple, or vector
|
list, tuple, or vector.
|
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)
|
shown on each ruler
|
shown on each ruler.
|
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)
|
subdivisions between each major tick
|
subdivisions between each major tick.
|
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)
|
options for lines which are also available.
|
options for lines, which are also available.
|
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)
|
We normally access this via the point3d function. Note that extra
|
We normally access this via the ``point3d`` function. Note that extra
|
def text3d(txt, (x,y,z), **kwds): r""" Display 3d text. INPUT: - ``txt`` - some text - ``(x,y,z)`` - position - ``**kwds`` - standard 3d graphics options .. note:: There is no way to change the font size or opacity yet. EXAMPLES: We write the word Sage in red at position (1,2,3):: sage: text3d("Sage", (1,2,3), color=(0.5,0,0)) We draw a multicolor spiral of numbers:: sage: sum([text3d('%.1f'%n, (cos(n),sin(n),n), color=(n/2,1-n/2,0)) \ for n in [0,0.2,..,8]]) Another example :: sage: text3d("Sage is really neat!!",(2,12,1)) And in 3d in two places:: sage: text3d("Sage is...",(2,12,1), rgbcolor=(1,0,0)) + text3d("quite powerful!!",(4,10,0), rgbcolor=(0,0,1)) """ if not kwds.has_key('color') and not kwds.has_key('rgbcolor'): kwds['color'] = (0,0,0) G = Text(txt, **kwds).translate((x,y,z)) G._set_extra_kwds(kwds) return G
|
Create the graphics primitive :class:`Point` in 3D. See the
|
Create the graphics primitive :class:`Point` in 3-D. See the
|
def __init__(self, center, size=1, **kwds): """ Create the graphics primitive :class:`Point` in 3D. See the docstring of this class for full documentation.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.