rem
stringlengths
1
322k
add
stringlengths
0
2.05M
context
stringlengths
4
228k
meta
stringlengths
156
215
is_ray.__doc__ = Vrepresentation.is_ray.__doc__
def is_ray(self): """ Tests if this object is a ray. Always True by construction.
58a962fefc201dcfd3e2e47df0f7b0e2cedced92 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/58a962fefc201dcfd3e2e47df0f7b0e2cedced92/polyhedra.py
is_line.__doc__ = Vrepresentation.is_line.__doc__
def is_line(self): """ Tests if the object is a line. By construction it must be.
58a962fefc201dcfd3e2e47df0f7b0e2cedced92 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/58a962fefc201dcfd3e2e47df0f7b0e2cedced92/polyhedra.py
Returns the identity projection.
Returns the identity projection of the polyhedron.
def identity(self): """ Returns the identity projection.
58a962fefc201dcfd3e2e47df0f7b0e2cedced92 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/58a962fefc201dcfd3e2e47df0f7b0e2cedced92/polyhedra.py
identity.__doc__ = projection_func_identity.__doc__
def identity(self): """ Returns the identity projection.
58a962fefc201dcfd3e2e47df0f7b0e2cedced92 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/58a962fefc201dcfd3e2e47df0f7b0e2cedced92/polyhedra.py
- ``algorithm`` - string (default: 'gmp') - ``'gmp'`` - use the GMP C-library factorial function - ``'pari'`` - use PARI's factorial function
- ``algorithm`` - string (default: 'gmp'): - ``'gmp'`` - use the GMP C-library factorial function - ``'pari'`` - use PARI's factorial function
def factorial(n, algorithm='gmp'): r""" Compute the factorial of `n`, which is the product `1\cdot 2\cdot 3 \cdots (n-1)\cdot n`. INPUT: - ``n`` - an integer - ``algorithm`` - string (default: 'gmp') - ``'gmp'`` - use the GMP C-library factorial function - ``'pari'`` - use PARI's factorial function OUTPUT: an integer EXAMPLES:: sage: from sage.rings.arith import factorial sage: factorial(0) 1 sage: factorial(4) 24 sage: factorial(10) 3628800 sage: factorial(1) == factorial(0) True sage: factorial(6) == 6*5*4*3*2 True sage: factorial(1) == factorial(0) True sage: factorial(71) == 71* factorial(70) True sage: factorial(-32) Traceback (most recent call last): ... ValueError: factorial -- must be nonnegative PERFORMANCE: This discussion is valid as of April 2006. All timings below are on a Pentium Core Duo 2Ghz MacBook Pro running Linux with a 2.6.16.1 kernel. - It takes less than a minute to compute the factorial of `10^7` using the GMP algorithm, and the factorial of `10^6` takes less than 4 seconds. - The GMP algorithm is faster and more memory efficient than the PARI algorithm. E.g., PARI computes `10^7` factorial in 100 seconds on the core duo 2Ghz. - For comparison, computation in Magma `\leq` 2.12-10 of `n!` is best done using ``*[1..n]``. It takes 113 seconds to compute the factorial of `10^7` and 6 seconds to compute the factorial of `10^6`. Mathematica V5.2 compute the factorial of `10^7` in 136 seconds and the factorial of `10^6` in 7 seconds. (Mathematica is notably very efficient at memory usage when doing factorial calculations.) """ if n < 0: raise ValueError, "factorial -- must be nonnegative" if algorithm == 'gmp': return ZZ(n).factorial() elif algorithm == 'pari': return pari.factorial(n) else: raise ValueError, 'unknown algorithm'
8cdf5e032fbf03e3ba6bed3d1fbcb1c171370d1e /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/8cdf5e032fbf03e3ba6bed3d1fbcb1c171370d1e/arith.py
modulo `m\*n`.
modulo `m*n`.
def crt(a,b,m=None,n=None): r""" Use the Chinese Remainder Theorem to find some `x` such that `x=a \bmod m` and `x=b \bmod n`. Note that `x` is only well-defined modulo `m\*n`. EXAMPLES:: sage: crt(2, 1, 3, 5) -4 sage: crt(13,20,100,301) -2087 You can also use upper case:: sage: c = CRT(2,3, 3, 5); c 8 sage: c % 3 == 2 True sage: c % 5 == 3 True Note that this also works for polynomial rings:: sage: K.<a> = NumberField(x^3 - 7) sage: R.<y> = K[] sage: f = y^2 + 3 sage: g = y^3 - 5 sage: CRT(1,3,f,g) -3/26*y^4 + 5/26*y^3 + 15/26*y + 53/26 sage: CRT(1,a,f,g) (-3/52*a + 3/52)*y^4 + (5/52*a - 5/52)*y^3 + (15/52*a - 15/52)*y + 27/52*a + 25/52 You can also do this for any number of moduli:: sage: K.<a> = NumberField(x^3 - 7) sage: R.<x> = K[] sage: CRT([], []) 0 sage: CRT([a], [x]) a sage: f = x^2 + 3 sage: g = x^3 - 5 sage: h = x^5 + x^2 - 9 sage: k = CRT([1, a, 3], [f, g, h]); k (127/26988*a - 5807/386828)*x^9 + (45/8996*a - 33677/1160484)*x^8 + (2/173*a - 6/173)*x^7 + (133/6747*a - 5373/96707)*x^6 + (-6/2249*a + 18584/290121)*x^5 + (-277/8996*a + 38847/386828)*x^4 + (-135/4498*a + 42673/193414)*x^3 + (-1005/8996*a + 470245/1160484)*x^2 + (-1215/8996*a + 141165/386828)*x + 621/8996*a + 836445/386828 sage: k.mod(f) 1 sage: k.mod(g) a sage: k.mod(h) 3 """ if isinstance(a,list): return CRT_list(a,b) g, alpha, beta = XGCD(m,n) if g != 1: raise ValueError, "arguments a and b must be coprime" return a+(b-a)*alpha*m
8cdf5e032fbf03e3ba6bed3d1fbcb1c171370d1e /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/8cdf5e032fbf03e3ba6bed3d1fbcb1c171370d1e/arith.py
sage: region_plot([y>0, x>0, x^2+y^2<1], (-1.1, 1.1), (-1.1, 1.1), plot_points = 400).show(aspect_ratio=1)
sage: region_plot([y>0, x>0, x^2+y^2<1], (x,-1.1, 1.1), (y,-1.1, 1.1), plot_points = 400).show(aspect_ratio=1)
def region_plot(f, xrange, yrange, plot_points, incol, outcol, bordercol, borderstyle, borderwidth): r""" ``region_plot`` takes a boolean function of two variables, `f(x,y)` and plots the region where f is True over the specified ``xrange`` and ``yrange`` as demonstrated below. ``region_plot(f, (xmin, xmax), (ymin, ymax), ...)`` INPUT: - ``f`` -- a boolean function of two variables - ``(xmin, xmax)`` -- 2-tuple, the range of ``x`` values OR 3-tuple ``(x,xmin,xmax)`` - ``(ymin, ymax)`` -- 2-tuple, the range of ``y`` values OR 3-tuple ``(y,ymin,ymax)`` - ``plot_points`` -- integer (default: 100); number of points to plot in each direction of the grid - ``incol`` -- a color (default: ``'blue'``), the color inside the region - ``outcol`` -- a color (default: ``'white'``), the color of the outside of the region If any of these options are specified, the border will be shown as indicated, otherwise it is only implicit (with color ``incol``) as the border of the inside of the region. - ``bordercol`` -- a color (default: ``None``), the color of the border (``'black'`` if ``borderwidth`` or ``borderstyle`` is specified but not ``bordercol``) - ``borderstyle`` -- string (default: 'solid'), one of 'solid', 'dashed', 'dotted', 'dashdot' - ``borderwidth`` -- integer (default: None), the width of the border in pixels EXAMPLES: Here we plot a simple function of two variables:: sage: x,y = var('x,y') sage: region_plot(cos(x^2+y^2) <= 0, (x, -3, 3), (y, -3, 3)) Here we play with the colors:: sage: region_plot(x^2+y^3 < 2, (x, -2, 2), (y, -2, 2), incol='lightblue', bordercol='gray') An even more complicated plot, with dashed borders:: sage: region_plot(sin(x)*sin(y) >= 1/4, (x,-10,10), (y,-10,10), incol='yellow', bordercol='black', borderstyle='dashed', plot_points=250) A disk centered at the origin:: sage: region_plot(x^2+y^2<1, (x,-1,1), (y,-1,1)).show(aspect_ratio=1) A plot with more than one condition:: sage: region_plot([x^2+y^2<1, x<y], (x,-2,2), (y,-2,2)) Since it doesn't look very good, let's increase plot_points:: sage: region_plot([x^2+y^2<1, x<y], (x,-2,2), (y,-2,2), plot_points=400).show(aspect_ratio=1) #long time The first quadrant of the unit circle:: sage: region_plot([y>0, x>0, x^2+y^2<1], (-1.1, 1.1), (-1.1, 1.1), plot_points = 400).show(aspect_ratio=1) Here is another plot, with a huge border:: sage: region_plot(x*(x-1)*(x+1)+y^2<0, (x, -3, 2), (y, -3, 3), incol='lightblue', bordercol='gray', borderwidth=10, plot_points=50) If we want to keep only the region where x is positive:: sage: region_plot([x*(x-1)*(x+1)+y^2<0, x>-1], (x, -3, 2), (y, -3, 3), incol='lightblue', plot_points=50) Here we have a cut circle:: sage: region_plot([x^2+y^2<4, x>-1], (x, -2, 2), (y, -2, 2), incol='lightblue', bordercol='gray', plot_points=200).show(aspect_ratio=1) """ from sage.plot.plot import Graphics from sage.plot.misc import setup_for_eval_on_grid if not isinstance(f, (list, tuple)): f = [f] variables = reduce(lambda g1, g2: g1.union(g2), [set(g.variables()) for g in f], set([])) f = [equify(g, variables) 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 = map(lambda g: [[g(x, y) for x in xsrange(*ranges[0], include_endpoint=True)] for y in xsrange(*ranges[1], include_endpoint=True)], g) xy_data_array = map(lambda *rows: map(lambda *vals: mangle_neg(vals), *rows), *xy_data_arrays) from matplotlib.colors import ListedColormap incol = rgbcolor(incol) outcol = rgbcolor(outcol) cmap = ListedColormap([incol, outcol]) cmap.set_over(outcol) cmap.set_under(incol) g = Graphics() opt = contour_plot.options.copy() opt.pop('plot_points') opt.pop('fill') opt.pop('contours') opt.pop('frame') g.add_primitive(ContourPlot(xy_data_array, xrange,yrange, dict(plot_points=plot_points, contours=[-1e307, 0, 1e307], cmap=cmap, fill=True, **opt))) if bordercol or borderstyle or borderwidth: cmap = [rgbcolor(bordercol)] if bordercol else ['black'] linestyles = [borderstyle] if borderstyle else None linewidths = [borderwidth] if borderwidth else None opt.pop('linestyles') opt.pop('linewidths') g.add_primitive(ContourPlot(xy_data_array, xrange, yrange, dict(plot_points=plot_points, linestyles=linestyles, linewidths=linewidths, contours=[0], cmap=[bordercol], fill=False, **opt))) return g
15f84735cfff3b4b3bd19bc07056647b6e202dd7 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/15f84735cfff3b4b3bd19bc07056647b6e202dd7/contour_plot.py
variables = reduce(lambda g1, g2: g1.union(g2), [set(g.variables()) for g in f], set([])) f = [equify(g, variables) for g in f]
f = [equify(g) for g in f]
def region_plot(f, xrange, yrange, plot_points, incol, outcol, bordercol, borderstyle, borderwidth): r""" ``region_plot`` takes a boolean function of two variables, `f(x,y)` and plots the region where f is True over the specified ``xrange`` and ``yrange`` as demonstrated below. ``region_plot(f, (xmin, xmax), (ymin, ymax), ...)`` INPUT: - ``f`` -- a boolean function of two variables - ``(xmin, xmax)`` -- 2-tuple, the range of ``x`` values OR 3-tuple ``(x,xmin,xmax)`` - ``(ymin, ymax)`` -- 2-tuple, the range of ``y`` values OR 3-tuple ``(y,ymin,ymax)`` - ``plot_points`` -- integer (default: 100); number of points to plot in each direction of the grid - ``incol`` -- a color (default: ``'blue'``), the color inside the region - ``outcol`` -- a color (default: ``'white'``), the color of the outside of the region If any of these options are specified, the border will be shown as indicated, otherwise it is only implicit (with color ``incol``) as the border of the inside of the region. - ``bordercol`` -- a color (default: ``None``), the color of the border (``'black'`` if ``borderwidth`` or ``borderstyle`` is specified but not ``bordercol``) - ``borderstyle`` -- string (default: 'solid'), one of 'solid', 'dashed', 'dotted', 'dashdot' - ``borderwidth`` -- integer (default: None), the width of the border in pixels EXAMPLES: Here we plot a simple function of two variables:: sage: x,y = var('x,y') sage: region_plot(cos(x^2+y^2) <= 0, (x, -3, 3), (y, -3, 3)) Here we play with the colors:: sage: region_plot(x^2+y^3 < 2, (x, -2, 2), (y, -2, 2), incol='lightblue', bordercol='gray') An even more complicated plot, with dashed borders:: sage: region_plot(sin(x)*sin(y) >= 1/4, (x,-10,10), (y,-10,10), incol='yellow', bordercol='black', borderstyle='dashed', plot_points=250) A disk centered at the origin:: sage: region_plot(x^2+y^2<1, (x,-1,1), (y,-1,1)).show(aspect_ratio=1) A plot with more than one condition:: sage: region_plot([x^2+y^2<1, x<y], (x,-2,2), (y,-2,2)) Since it doesn't look very good, let's increase plot_points:: sage: region_plot([x^2+y^2<1, x<y], (x,-2,2), (y,-2,2), plot_points=400).show(aspect_ratio=1) #long time The first quadrant of the unit circle:: sage: region_plot([y>0, x>0, x^2+y^2<1], (-1.1, 1.1), (-1.1, 1.1), plot_points = 400).show(aspect_ratio=1) Here is another plot, with a huge border:: sage: region_plot(x*(x-1)*(x+1)+y^2<0, (x, -3, 2), (y, -3, 3), incol='lightblue', bordercol='gray', borderwidth=10, plot_points=50) If we want to keep only the region where x is positive:: sage: region_plot([x*(x-1)*(x+1)+y^2<0, x>-1], (x, -3, 2), (y, -3, 3), incol='lightblue', plot_points=50) Here we have a cut circle:: sage: region_plot([x^2+y^2<4, x>-1], (x, -2, 2), (y, -2, 2), incol='lightblue', bordercol='gray', plot_points=200).show(aspect_ratio=1) """ from sage.plot.plot import Graphics from sage.plot.misc import setup_for_eval_on_grid if not isinstance(f, (list, tuple)): f = [f] variables = reduce(lambda g1, g2: g1.union(g2), [set(g.variables()) for g in f], set([])) f = [equify(g, variables) 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 = map(lambda g: [[g(x, y) for x in xsrange(*ranges[0], include_endpoint=True)] for y in xsrange(*ranges[1], include_endpoint=True)], g) xy_data_array = map(lambda *rows: map(lambda *vals: mangle_neg(vals), *rows), *xy_data_arrays) from matplotlib.colors import ListedColormap incol = rgbcolor(incol) outcol = rgbcolor(outcol) cmap = ListedColormap([incol, outcol]) cmap.set_over(outcol) cmap.set_under(incol) g = Graphics() opt = contour_plot.options.copy() opt.pop('plot_points') opt.pop('fill') opt.pop('contours') opt.pop('frame') g.add_primitive(ContourPlot(xy_data_array, xrange,yrange, dict(plot_points=plot_points, contours=[-1e307, 0, 1e307], cmap=cmap, fill=True, **opt))) if bordercol or borderstyle or borderwidth: cmap = [rgbcolor(bordercol)] if bordercol else ['black'] linestyles = [borderstyle] if borderstyle else None linewidths = [borderwidth] if borderwidth else None opt.pop('linestyles') opt.pop('linewidths') g.add_primitive(ContourPlot(xy_data_array, xrange, yrange, dict(plot_points=plot_points, linestyles=linestyles, linewidths=linewidths, contours=[0], cmap=[bordercol], fill=False, **opt))) return g
15f84735cfff3b4b3bd19bc07056647b6e202dd7 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/15f84735cfff3b4b3bd19bc07056647b6e202dd7/contour_plot.py
def equify(f, variables = None):
def equify(f):
def equify(f, variables = None): """ Returns the equation rewritten as a symbolic function to give negative values when True, positive when False. EXAMPLES:: sage: from sage.plot.contour_plot import equify sage: var('x, y') (x, y) sage: equify(x^2 < 2) x |--> x^2 - 2 sage: equify(x^2 > 2) x |--> -x^2 + 2 sage: equify(x*y > 1) (x, y) |--> -x*y + 1 sage: equify(y > 0, (x,y)) (x, y) |--> -y """ import operator from sage.calculus.all import symbolic_expression op = f.operator() if variables == None: variables = f.variables() if op is operator.gt or op is operator.ge: s = symbolic_expression(f.rhs() - f.lhs()).function(*variables) return s else: s = symbolic_expression(f.lhs() - f.rhs()).function(*variables) return s
15f84735cfff3b4b3bd19bc07056647b6e202dd7 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/15f84735cfff3b4b3bd19bc07056647b6e202dd7/contour_plot.py
x |--> x^2 - 2
x^2 - 2
def equify(f, variables = None): """ Returns the equation rewritten as a symbolic function to give negative values when True, positive when False. EXAMPLES:: sage: from sage.plot.contour_plot import equify sage: var('x, y') (x, y) sage: equify(x^2 < 2) x |--> x^2 - 2 sage: equify(x^2 > 2) x |--> -x^2 + 2 sage: equify(x*y > 1) (x, y) |--> -x*y + 1 sage: equify(y > 0, (x,y)) (x, y) |--> -y """ import operator from sage.calculus.all import symbolic_expression op = f.operator() if variables == None: variables = f.variables() if op is operator.gt or op is operator.ge: s = symbolic_expression(f.rhs() - f.lhs()).function(*variables) return s else: s = symbolic_expression(f.lhs() - f.rhs()).function(*variables) return s
15f84735cfff3b4b3bd19bc07056647b6e202dd7 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/15f84735cfff3b4b3bd19bc07056647b6e202dd7/contour_plot.py
x |--> -x^2 + 2
-x^2 + 2
def equify(f, variables = None): """ Returns the equation rewritten as a symbolic function to give negative values when True, positive when False. EXAMPLES:: sage: from sage.plot.contour_plot import equify sage: var('x, y') (x, y) sage: equify(x^2 < 2) x |--> x^2 - 2 sage: equify(x^2 > 2) x |--> -x^2 + 2 sage: equify(x*y > 1) (x, y) |--> -x*y + 1 sage: equify(y > 0, (x,y)) (x, y) |--> -y """ import operator from sage.calculus.all import symbolic_expression op = f.operator() if variables == None: variables = f.variables() if op is operator.gt or op is operator.ge: s = symbolic_expression(f.rhs() - f.lhs()).function(*variables) return s else: s = symbolic_expression(f.lhs() - f.rhs()).function(*variables) return s
15f84735cfff3b4b3bd19bc07056647b6e202dd7 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/15f84735cfff3b4b3bd19bc07056647b6e202dd7/contour_plot.py
(x, y) |--> -x*y + 1 sage: equify(y > 0, (x,y)) (x, y) |--> -y
-x*y + 1 sage: equify(y > 0) -y
def equify(f, variables = None): """ Returns the equation rewritten as a symbolic function to give negative values when True, positive when False. EXAMPLES:: sage: from sage.plot.contour_plot import equify sage: var('x, y') (x, y) sage: equify(x^2 < 2) x |--> x^2 - 2 sage: equify(x^2 > 2) x |--> -x^2 + 2 sage: equify(x*y > 1) (x, y) |--> -x*y + 1 sage: equify(y > 0, (x,y)) (x, y) |--> -y """ import operator from sage.calculus.all import symbolic_expression op = f.operator() if variables == None: variables = f.variables() if op is operator.gt or op is operator.ge: s = symbolic_expression(f.rhs() - f.lhs()).function(*variables) return s else: s = symbolic_expression(f.lhs() - f.rhs()).function(*variables) return s
15f84735cfff3b4b3bd19bc07056647b6e202dd7 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/15f84735cfff3b4b3bd19bc07056647b6e202dd7/contour_plot.py
if variables == None: variables = f.variables()
def equify(f, variables = None): """ Returns the equation rewritten as a symbolic function to give negative values when True, positive when False. EXAMPLES:: sage: from sage.plot.contour_plot import equify sage: var('x, y') (x, y) sage: equify(x^2 < 2) x |--> x^2 - 2 sage: equify(x^2 > 2) x |--> -x^2 + 2 sage: equify(x*y > 1) (x, y) |--> -x*y + 1 sage: equify(y > 0, (x,y)) (x, y) |--> -y """ import operator from sage.calculus.all import symbolic_expression op = f.operator() if variables == None: variables = f.variables() if op is operator.gt or op is operator.ge: s = symbolic_expression(f.rhs() - f.lhs()).function(*variables) return s else: s = symbolic_expression(f.lhs() - f.rhs()).function(*variables) return s
15f84735cfff3b4b3bd19bc07056647b6e202dd7 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/15f84735cfff3b4b3bd19bc07056647b6e202dd7/contour_plot.py
s = symbolic_expression(f.rhs() - f.lhs()).function(*variables) return s
return symbolic_expression(f.rhs() - f.lhs())
def equify(f, variables = None): """ Returns the equation rewritten as a symbolic function to give negative values when True, positive when False. EXAMPLES:: sage: from sage.plot.contour_plot import equify sage: var('x, y') (x, y) sage: equify(x^2 < 2) x |--> x^2 - 2 sage: equify(x^2 > 2) x |--> -x^2 + 2 sage: equify(x*y > 1) (x, y) |--> -x*y + 1 sage: equify(y > 0, (x,y)) (x, y) |--> -y """ import operator from sage.calculus.all import symbolic_expression op = f.operator() if variables == None: variables = f.variables() if op is operator.gt or op is operator.ge: s = symbolic_expression(f.rhs() - f.lhs()).function(*variables) return s else: s = symbolic_expression(f.lhs() - f.rhs()).function(*variables) return s
15f84735cfff3b4b3bd19bc07056647b6e202dd7 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/15f84735cfff3b4b3bd19bc07056647b6e202dd7/contour_plot.py
s = symbolic_expression(f.lhs() - f.rhs()).function(*variables) return s
return symbolic_expression(f.lhs() - f.rhs())
def equify(f, variables = None): """ Returns the equation rewritten as a symbolic function to give negative values when True, positive when False. EXAMPLES:: sage: from sage.plot.contour_plot import equify sage: var('x, y') (x, y) sage: equify(x^2 < 2) x |--> x^2 - 2 sage: equify(x^2 > 2) x |--> -x^2 + 2 sage: equify(x*y > 1) (x, y) |--> -x*y + 1 sage: equify(y > 0, (x,y)) (x, y) |--> -y """ import operator from sage.calculus.all import symbolic_expression op = f.operator() if variables == None: variables = f.variables() if op is operator.gt or op is operator.ge: s = symbolic_expression(f.rhs() - f.lhs()).function(*variables) return s else: s = symbolic_expression(f.lhs() - f.rhs()).function(*variables) return s
15f84735cfff3b4b3bd19bc07056647b6e202dd7 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/15f84735cfff3b4b3bd19bc07056647b6e202dd7/contour_plot.py
- Oscar Lazo, William Cauchois (2009-2010): Adding coordinate transformations
- Oscar Lazo, William Cauchois, Jason Grout (2009-2010): Adding coordinate transformations
sage: def f(x,y): return math.exp(x/5)*math.cos(y)
85811d8c24ec26acc8a960fadc0b24274c01a5a8 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/85811d8c24ec26acc8a960fadc0b24274c01a5a8/plot3d.py
class _CoordTrans(object):
class _Coordinates(object):
sage: def f(x,y): return math.exp(x/5)*math.cos(y)
85811d8c24ec26acc8a960fadc0b24274c01a5a8 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/85811d8c24ec26acc8a960fadc0b24274c01a5a8/plot3d.py
Sub-classes must implement the ``gen_transform`` method which, given
Sub-classes must implement the :meth:`transform` method which, given
sage: def f(x,y): return math.exp(x/5)*math.cos(y)
85811d8c24ec26acc8a960fadc0b24274c01a5a8 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/85811d8c24ec26acc8a960fadc0b24274c01a5a8/plot3d.py
def __init__(self, indep_var, dep_vars):
def __init__(self, dep_var, indep_vars):
sage: def f(x,y): return math.exp(x/5)*math.cos(y)
85811d8c24ec26acc8a960fadc0b24274c01a5a8 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/85811d8c24ec26acc8a960fadc0b24274c01a5a8/plot3d.py
- ``indep_var`` - The independent variable (the function value will be
- ``dep_var`` - The dependent variable (the function value will be
def __init__(self, indep_var, dep_vars): """ INPUT:
85811d8c24ec26acc8a960fadc0b24274c01a5a8 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/85811d8c24ec26acc8a960fadc0b24274c01a5a8/plot3d.py
- ``dep_vars`` - A list of dependent variables (the parameters will be
- ``indep_vars`` - A list of independent variables (the parameters will be
def __init__(self, indep_var, dep_vars): """ INPUT:
85811d8c24ec26acc8a960fadc0b24274c01a5a8 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/85811d8c24ec26acc8a960fadc0b24274c01a5a8/plot3d.py
sage: from sage.plot.plot3d.plot3d import _CoordTrans sage: _CoordTrans('y', ['x']) Unknown coordinate system (y in terms of x) """ if hasattr(self, 'all_vars'): if set(self.all_vars) != set(dep_vars + [indep_var]): raise ValueError, 'not all variables were specified for ' + \ 'this coordinate system' self.indep_var = indep_var self.dep_vars = dep_vars def gen_transform(self, **kwds): """ Generate the transformation for this coordinate system in terms of the
sage: from sage.plot.plot3d.plot3d import _ArbitraryCoordinates as arb sage: x,y,z=var('x,y,z') sage: c=arb((x+z,y*z,z), z, (x,y)) sage: c._name 'Arbitrary Coordinates' """ return self.__class__.__name__ def transform(self, **kwds): """ Return the transformation for this coordinate system in terms of the
def __init__(self, indep_var, dep_vars): """ INPUT:
85811d8c24ec26acc8a960fadc0b24274c01a5a8 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/85811d8c24ec26acc8a960fadc0b24274c01a5a8/plot3d.py
def to_cartesian(self, func, params):
def to_cartesian(self, func, params=None):
def to_cartesian(self, func, params): """ Returns a 3-tuple of functions, parameterized over ``params``, that represents the cartesian coordinates of the value of ``func``.
85811d8c24ec26acc8a960fadc0b24274c01a5a8 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/85811d8c24ec26acc8a960fadc0b24274c01a5a8/plot3d.py
- ``params`` - The parameters of func. Correspond to the dependent
- ``params`` - The parameters of func. Corresponds to the dependent
def to_cartesian(self, func, params): """ Returns a 3-tuple of functions, parameterized over ``params``, that represents the cartesian coordinates of the value of ``func``.
85811d8c24ec26acc8a960fadc0b24274c01a5a8 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/85811d8c24ec26acc8a960fadc0b24274c01a5a8/plot3d.py
sage: from sage.plot.plot3d.plot3d import _ArbCoordTrans
sage: from sage.plot.plot3d.plot3d import _ArbitraryCoordinates
def to_cartesian(self, func, params): """ Returns a 3-tuple of functions, parameterized over ``params``, that represents the cartesian coordinates of the value of ``func``.
85811d8c24ec26acc8a960fadc0b24274c01a5a8 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/85811d8c24ec26acc8a960fadc0b24274c01a5a8/plot3d.py
sage: T = _ArbCoordTrans((x + y, x - y, z), z) sage: f(x, y) = x * y
sage: T = _ArbitraryCoordinates((x + y, x - y, z), z,[x,y]) sage: f(x, y) = 2*x+y
def to_cartesian(self, func, params): """ Returns a 3-tuple of functions, parameterized over ``params``, that represents the cartesian coordinates of the value of ``func``.
85811d8c24ec26acc8a960fadc0b24274c01a5a8 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/85811d8c24ec26acc8a960fadc0b24274c01a5a8/plot3d.py
[x + y, x - y, x*y] """
(x + y, x - y, 2*x + y) sage: [h(1,2) for h in T.to_cartesian(lambda x,y: 2*x+y)] [3, -1, 4] """
def to_cartesian(self, func, params): """ Returns a 3-tuple of functions, parameterized over ``params``, that represents the cartesian coordinates of the value of ``func``.
85811d8c24ec26acc8a960fadc0b24274c01a5a8 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/85811d8c24ec26acc8a960fadc0b24274c01a5a8/plot3d.py
if any([is_Expression(func), is_RealNumber(func), is_Integer(func)]): return self.gen_transform(**{ self.indep_var: func, self.dep_vars[0]: params[0], self.dep_vars[1]: params[1]
if params is not None and (is_Expression(func) or is_RealNumber(func) or is_Integer(func)): return self.transform(**{ self.dep_var: func, self.indep_vars[0]: params[0], self.indep_vars[1]: params[1]
def to_cartesian(self, func, params): """ Returns a 3-tuple of functions, parameterized over ``params``, that represents the cartesian coordinates of the value of ``func``.
85811d8c24ec26acc8a960fadc0b24274c01a5a8 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/85811d8c24ec26acc8a960fadc0b24274c01a5a8/plot3d.py
indep_var_dummy = sage.symbolic.ring.var(self.indep_var) dep_var_dummies = sage.symbolic.ring.var(','.join(self.dep_vars)) transformation = self.gen_transform(**{ self.indep_var: indep_var_dummy, self.dep_vars[0]: dep_var_dummies[0], self.dep_vars[1]: dep_var_dummies[1]
dep_var_dummy = sage.symbolic.ring.var(self.dep_var) indep_var_dummies = sage.symbolic.ring.var(','.join(self.indep_vars)) transformation = self.transform(**{ self.dep_var: dep_var_dummy, self.indep_vars[0]: indep_var_dummies[0], self.indep_vars[1]: indep_var_dummies[1]
def to_cartesian(self, func, params): """ Returns a 3-tuple of functions, parameterized over ``params``, that represents the cartesian coordinates of the value of ``func``.
85811d8c24ec26acc8a960fadc0b24274c01a5a8 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/85811d8c24ec26acc8a960fadc0b24274c01a5a8/plot3d.py
indep_var_dummy: func(x, y), dep_var_dummies[0]: x, dep_var_dummies[1]: y
dep_var_dummy: func(x, y), indep_var_dummies[0]: x, indep_var_dummies[1]: y
def subs_func(t): return lambda x,y: t.subs({ indep_var_dummy: func(x, y), dep_var_dummies[0]: x, dep_var_dummies[1]: y })
85811d8c24ec26acc8a960fadc0b24274c01a5a8 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/85811d8c24ec26acc8a960fadc0b24274c01a5a8/plot3d.py
_name = 'Unknown coordinate system'
def subs_func(t): return lambda x,y: t.subs({ indep_var_dummy: func(x, y), dep_var_dummies[0]: x, dep_var_dummies[1]: y })
85811d8c24ec26acc8a960fadc0b24274c01a5a8 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/85811d8c24ec26acc8a960fadc0b24274c01a5a8/plot3d.py
return '%s (%s in terms of %s)' % \ (self._name, self.indep_var, ', '.join(self.dep_vars)) class _ArbCoordTrans(_CoordTrans): """ An arbitrary coordinate system transformation. """ def __init__(self, custom_trans, fvar): """
""" Print out a coordinate system :: sage: from sage.plot.plot3d.plot3d import _ArbitraryCoordinates as arb sage: x,y,z=var('x,y,z') sage: c=arb((x+z,y*z,z), z, (x,y)) sage: c Arbitrary Coordinates coordinate transform (z in terms of x, y) sage: c.__dict__['_name'] = 'My Special Coordinates' sage: c My Special Coordinates coordinate transform (z in terms of x, y) """ return '%s coordinate transform (%s in terms of %s)' % \ (self._name, self.dep_var, ', '.join(self.indep_vars)) class _ArbitraryCoordinates(_Coordinates): """ An arbitrary coordinate system. """ _name = "Arbitrary Coordinates" def __init__(self, custom_trans, dep_var, indep_vars): """ Initialize an arbitrary coordinate system.
def __repr__(self): return '%s (%s in terms of %s)' % \ (self._name, self.indep_var, ', '.join(self.dep_vars))
85811d8c24ec26acc8a960fadc0b24274c01a5a8 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/85811d8c24ec26acc8a960fadc0b24274c01a5a8/plot3d.py
- ``custom_trans`` - A 3-tuple of transformations. This will be returned almost unchanged by ``gen_transform``, except the function variable will be substituted. - ``fvar`` - The function variable. """ super(_ArbCoordTrans, self).__init__('f', ['u', 'v']) self.custom_trans = custom_trans self.fvar = fvar def gen_transform(self, f=None, u=None, v=None):
- ``custom_trans`` - A 3-tuple of transformation functions. - ``dep_var`` - The dependent (function) variable. - ``indep_vars`` - a list of the two other independent variables. EXAMPLES:: sage: from sage.plot.plot3d.plot3d import _ArbitraryCoordinates sage: x, y, z = var('x y z') sage: T = _ArbitraryCoordinates((x + y, x - y, z), z,[x,y]) sage: f(x, y) = 2*x + y sage: T.to_cartesian(f, [x, y]) (x + y, x - y, 2*x + y) sage: [h(1,2) for h in T.to_cartesian(lambda x,y: 2*x+y)] [3, -1, 4] """ self.dep_var = str(dep_var) self.indep_vars = [str(i) for i in indep_vars] self.custom_trans = tuple(custom_trans) def transform(self, **kwds):
def __init__(self, custom_trans, fvar): """ INPUT:
85811d8c24ec26acc8a960fadc0b24274c01a5a8 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/85811d8c24ec26acc8a960fadc0b24274c01a5a8/plot3d.py
sage: from sage.plot.plot3d.plot3d import _ArbCoordTrans
sage: from sage.plot.plot3d.plot3d import _ArbitraryCoordinates
def gen_transform(self, f=None, u=None, v=None): """ EXAMPLE::
85811d8c24ec26acc8a960fadc0b24274c01a5a8 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/85811d8c24ec26acc8a960fadc0b24274c01a5a8/plot3d.py
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::
85811d8c24ec26acc8a960fadc0b24274c01a5a8 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/85811d8c24ec26acc8a960fadc0b24274c01a5a8/plot3d.py
- 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 - the *inclination angle* (``inclination``) from the positive `z`-axis
def gen_transform(self, f=None, u=None, v=None): """ EXAMPLE::
85811d8c24ec26acc8a960fadc0b24274c01a5a8 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/85811d8c24ec26acc8a960fadc0b24274c01a5a8/plot3d.py
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::
85811d8c24ec26acc8a960fadc0b24274c01a5a8 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/85811d8c24ec26acc8a960fadc0b24274c01a5a8/plot3d.py
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::
85811d8c24ec26acc8a960fadc0b24274c01a5a8 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/85811d8c24ec26acc8a960fadc0b24274c01a5a8/plot3d.py
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::
85811d8c24ec26acc8a960fadc0b24274c01a5a8 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/85811d8c24ec26acc8a960fadc0b24274c01a5a8/plot3d.py
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::
85811d8c24ec26acc8a960fadc0b24274c01a5a8 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/85811d8c24ec26acc8a960fadc0b24274c01a5a8/plot3d.py
- the *radial distance* (``rho``), - the *angular position* or *azimuth* (``phi``), - and the *height* or *altitude* (``z``).
- the *radial distance* (``radius``) from the `z`-axis - the *azimuth angle* (``azimuth``) from the positive `x`-axis - the *height* or *altitude* (``height``) above the `xy`-plane
def gen_transform(self, r=None, theta=None, phi=None): """ EXAMPLE::
85811d8c24ec26acc8a960fadc0b24274c01a5a8 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/85811d8c24ec26acc8a960fadc0b24274c01a5a8/plot3d.py
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::
85811d8c24ec26acc8a960fadc0b24274c01a5a8 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/85811d8c24ec26acc8a960fadc0b24274c01a5a8/plot3d.py
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::
85811d8c24ec26acc8a960fadc0b24274c01a5a8 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/85811d8c24ec26acc8a960fadc0b24274c01a5a8/plot3d.py
_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::
85811d8c24ec26acc8a960fadc0b24274c01a5a8 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/85811d8c24ec26acc8a960fadc0b24274c01a5a8/plot3d.py
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::
85811d8c24ec26acc8a960fadc0b24274c01a5a8 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/85811d8c24ec26acc8a960fadc0b24274c01a5a8/plot3d.py
- ``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
85811d8c24ec26acc8a960fadc0b24274c01a5a8 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/85811d8c24ec26acc8a960fadc0b24274c01a5a8/plot3d.py
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
85811d8c24ec26acc8a960fadc0b24274c01a5a8 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/85811d8c24ec26acc8a960fadc0b24274c01a5a8/plot3d.py
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
85811d8c24ec26acc8a960fadc0b24274c01a5a8 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/85811d8c24ec26acc8a960fadc0b24274c01a5a8/plot3d.py
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]):
85811d8c24ec26acc8a960fadc0b24274c01a5a8 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/85811d8c24ec26acc8a960fadc0b24274c01a5a8/plot3d.py
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]):
85811d8c24ec26acc8a960fadc0b24274c01a5a8 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/85811d8c24ec26acc8a960fadc0b24274c01a5a8/plot3d.py
else: raise ValueError, 'expected 3-tuple for urange and vrange'
sage: def _(which_plot=[F, G, H, I, J]):
85811d8c24ec26acc8a960fadc0b24274c01a5a8 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/85811d8c24ec26acc8a960fadc0b24274c01a5a8/plot3d.py
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]):
85811d8c24ec26acc8a960fadc0b24274c01a5a8 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/85811d8c24ec26acc8a960fadc0b24274c01a5a8/plot3d.py
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)
85811d8c24ec26acc8a960fadc0b24274c01a5a8 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/85811d8c24ec26acc8a960fadc0b24274c01a5a8/plot3d.py
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)
85811d8c24ec26acc8a960fadc0b24274c01a5a8 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/85811d8c24ec26acc8a960fadc0b24274c01a5a8/plot3d.py
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)
85811d8c24ec26acc8a960fadc0b24274c01a5a8 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/85811d8c24ec26acc8a960fadc0b24274c01a5a8/plot3d.py
- ``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)
85811d8c24ec26acc8a960fadc0b24274c01a5a8 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/85811d8c24ec26acc8a960fadc0b24274c01a5a8/plot3d.py
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)
85811d8c24ec26acc8a960fadc0b24274c01a5a8 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/85811d8c24ec26acc8a960fadc0b24274c01a5a8/plot3d.py
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)
85811d8c24ec26acc8a960fadc0b24274c01a5a8 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/85811d8c24ec26acc8a960fadc0b24274c01a5a8/plot3d.py
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)
85811d8c24ec26acc8a960fadc0b24274c01a5a8 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/85811d8c24ec26acc8a960fadc0b24274c01a5a8/plot3d.py
TypeError, "No lookup table provided."
raise TypeError("No lookup table provided.")
def __init__(self, *args, **kwargs): """ Construct a substitution box (S-box) for a given lookup table `S`.
7db71f52a07b6303429fd5109e3af046f6d5f775 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/7db71f52a07b6303429fd5109e3af046f6d5f775/sbox.py
length = ZZ(len(S)).exact_log(2) if length != int(length): TypeError, "lookup table length is not a power of 2." self.m = int(length)
self.m = ZZ(len(S)).exact_log(2)
def __init__(self, *args, **kwargs): """ Construct a substitution box (S-box) for a given lookup table `S`.
7db71f52a07b6303429fd5109e3af046f6d5f775 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/7db71f52a07b6303429fd5109e3af046f6d5f775/sbox.py
variables x,y::
variables `x`, `y`::
def contour_plot(f, xrange, yrange, **options): r""" ``contour_plot`` takes a function of two variables, `f(x,y)` and plots contour lines of the function over the specified ``xrange`` and ``yrange`` as demonstrated below. ``contour_plot(f, (xmin, xmax), (ymin, ymax), ...)`` INPUT: - ``f`` -- a 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)`` The following inputs must all be passed in as named parameters: - ``plot_points`` -- integer (default: 100); number of points to plot in each direction of the grid. For old computers, 25 is fine, but should not be used to verify specific intersection points. - ``fill`` -- bool (default: ``True``), whether to color in the area between contour lines - ``cmap`` -- a colormap (default: ``'gray'``), the name of a predefined colormap, a list of colors or an instance of a matplotlib Colormap. Type: ``import matplotlib.cm; matplotlib.cm.datad.keys()`` for available colormap names. - ``contours`` -- integer or list of numbers (default: ``None``): If a list of numbers is given, then this specifies the contour levels to use. If an integer is given, then this many contour lines are used, but the exact levels are determined automatically. If ``None`` is passed (or the option is not given), then the number of contour lines is determined automatically, and is usually about 5. - ``linewidths`` -- integer or list of integer (default: None), if a single integer all levels will be of the width given, otherwise the levels will be plotted with the width in the order given. If the list is shorter than the number of contours, then the widths will be repeated cyclically. - ``linestyles`` -- string or list of strings (default: None), the style of the lines to be plotted, one of: solid, dashed, dashdot, or dotted. If the list is shorter than the number of contours, then the styles will be repeated cyclically. - ``labels`` -- boolean (default: False) Show level labels or not. The following options are to adjust the style and placement of labels, they have no effect if no labels are shown. - ``label_fontsize`` -- integer (default: 9), the font size of the labels. - ``label_colors`` -- string or sequence of colors (default: None) If a string, gives the name of a single color with which to draw all labels. If a sequence, gives the colors of the labels. A color is a string giving the name of one or a 3-tuple of floats. - ``label_inline`` -- boolean (default: False if fill is True, otherwise True), controls whether the underlying contour is removed or not. - ``label_inline_spacing`` -- integer (default: 3), When inline, this is the amount of contour that is removed from each side, in pixels. - ``label_fmt`` -- a format string (default: "%1.2f"), this is used to get the label text from the level. This can also be a dictionary with the contour levels as keys and corresponding text string labels as values. EXAMPLES: Here we plot a simple function of two variables. Note that since the input function is an expression, we need to explicitly declare the variables in 3-tuples for the range:: sage: x,y = var('x,y') sage: contour_plot(cos(x^2+y^2), (x, -4, 4), (y, -4, 4)) Here we change the ranges and add some options:: sage: x,y = var('x,y') sage: contour_plot((x^2)*cos(x*y), (x, -10, 5), (y, -5, 5), fill=False, plot_points=150) An even more complicated plot:: sage: x,y = var('x,y') sage: contour_plot(sin(x^2 + y^2)*cos(x)*sin(y), (x, -4, 4), (y, -4, 4),plot_points=150) Some elliptic curves, but with symbolic endpoints. In the first example, the plot is rotated 90 degrees because we switch the variables x,y:: sage: x,y = var('x,y') sage: contour_plot(y^2 + 1 - x^3 - x, (y,-pi,pi), (x,-pi,pi)) sage: contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi)) We can play with the contour levels:: sage: x,y = var('x,y') sage: f(x,y) = x^2 + y^2 sage: contour_plot(f, (-2, 2), (-2, 2)) sage: contour_plot(f, (-2, 2), (-2, 2), contours=2, cmap=[(1,0,0), (0,1,0), (0,0,1)]) sage: contour_plot(f, (-2, 2), (-2, 2), contours=(0.1, 1.0, 1.2, 1.4), cmap='hsv') sage: contour_plot(f, (-2, 2), (-2, 2), contours=(1.0,), fill=False, aspect_ratio=1) sage: contour_plot(x-y^2,(x,-5,5),(y,-3,3),contours=[-4,0,1]) We can change the style of the lines:: sage: contour_plot(f, (-2,2), (-2,2), fill=False, linewidths=10) sage: contour_plot(f, (-2,2), (-2,2), fill=False, linestyles='dashdot') sage: contour_plot(x^2-y^2,(x,-3,3),(y,-3,3),contours=[0,1,2,3,4],linewidths=[1,5],linestyles=['solid','dashed'],fill=False) sage: contour_plot(x^2-y^2,(x,-3,3),(y,-3,3),contours=[0,1,2,3,4],linewidths=[1,5],linestyles=['solid','dashed']) We can add labels and play with them:: sage: contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), fill=False, cmap='hsv', labels=True) sage: contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), fill=False, cmap='hsv', labels=True, label_fmt="%1.0f", label_colors='black') sage: contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), fill=False, cmap='hsv', labels=True, contours=[-4,0,4], label_fmt={-4:"low", 0:"medium", 4: "hi"}, label_colors='black') sage: contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), fill=False, cmap='hsv', labels=True, label_fontsize=18) sage: contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), fill=False, cmap='hsv', labels=True, label_inline_spacing=1) sage: contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), fill=False, cmap='hsv', labels=True, label_inline=False) If fill is True (the default), then we may have to color the labels so that we can see them:: sage: contour_plot(f, (-2,2), (-2,2), labels=True, label_colors='red') This should plot concentric circles centered at the origin:: sage: x,y = var('x,y') sage: contour_plot(x^2+y^2-2,(x,-1,1), (y,-1,1)).show(aspect_ratio=1) Extra options will get passed on to show(), as long as they are valid:: sage: f(x, y) = cos(x) + sin(y) sage: contour_plot(f, (0, pi), (0, pi), axes=True) sage: contour_plot(f, (0, pi), (0, pi)).show(axes=True) # These are equivalent Note that with ``fill=False`` and grayscale contours, there is the possibility of confusion between the contours and the axes, so use ``fill=False`` together with ``axes=True`` with caution:: sage: contour_plot(f, (-pi, pi), (-pi, pi), fill=False, axes=True) TESTS: To check that ticket 5221 is fixed, note that this has three curves, not two:: sage: x,y = var('x,y') sage: contour_plot(x-y^2,(x,-5,5),(y,-3,3),contours=[-4,-2,0], fill=False) """ from sage.plot.plot import Graphics from sage.plot.misc import setup_for_eval_on_grid g, ranges = setup_for_eval_on_grid([f], [xrange, yrange], options['plot_points']) g = g[0] xrange,yrange=[r[:2] for r in ranges] xy_data_array = [[g(x, y) for x in xsrange(*ranges[0], include_endpoint=True)] for y in xsrange(*ranges[1], include_endpoint=True)] g = Graphics() g._set_extra_kwds(Graphics._extract_kwds_for_show(options, ignore=['xmin', 'xmax'])) g.add_primitive(ContourPlot(xy_data_array, xrange, yrange, options)) return g
1be89942e80d3d044db8b1d126931ba7f5a875fb /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/1be89942e80d3d044db8b1d126931ba7f5a875fb/contour_plot.py
sage: contour_plot(x^2-y^2,(x,-3,3),(y,-3,3),contours=[0,1,2,3,4],linewidths=[1,5],linestyles=['solid','dashed'],fill=False) sage: contour_plot(x^2-y^2,(x,-3,3),(y,-3,3),contours=[0,1,2,3,4],linewidths=[1,5],linestyles=['solid','dashed'])
:: sage: P=contour_plot(x^2-y^2,(x,-3,3),(y,-3,3),contours=[0,1,2,3,4],\ ... linewidths=[1,5],linestyles=['solid','dashed'],fill=False) sage: P :: sage: P=contour_plot(x^2-y^2,(x,-3,3),(y,-3,3),contours=[0,1,2,3,4],\ ... linewidths=[1,5],linestyles=['solid','dashed']) sage: P
def contour_plot(f, xrange, yrange, **options): r""" ``contour_plot`` takes a function of two variables, `f(x,y)` and plots contour lines of the function over the specified ``xrange`` and ``yrange`` as demonstrated below. ``contour_plot(f, (xmin, xmax), (ymin, ymax), ...)`` INPUT: - ``f`` -- a 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)`` The following inputs must all be passed in as named parameters: - ``plot_points`` -- integer (default: 100); number of points to plot in each direction of the grid. For old computers, 25 is fine, but should not be used to verify specific intersection points. - ``fill`` -- bool (default: ``True``), whether to color in the area between contour lines - ``cmap`` -- a colormap (default: ``'gray'``), the name of a predefined colormap, a list of colors or an instance of a matplotlib Colormap. Type: ``import matplotlib.cm; matplotlib.cm.datad.keys()`` for available colormap names. - ``contours`` -- integer or list of numbers (default: ``None``): If a list of numbers is given, then this specifies the contour levels to use. If an integer is given, then this many contour lines are used, but the exact levels are determined automatically. If ``None`` is passed (or the option is not given), then the number of contour lines is determined automatically, and is usually about 5. - ``linewidths`` -- integer or list of integer (default: None), if a single integer all levels will be of the width given, otherwise the levels will be plotted with the width in the order given. If the list is shorter than the number of contours, then the widths will be repeated cyclically. - ``linestyles`` -- string or list of strings (default: None), the style of the lines to be plotted, one of: solid, dashed, dashdot, or dotted. If the list is shorter than the number of contours, then the styles will be repeated cyclically. - ``labels`` -- boolean (default: False) Show level labels or not. The following options are to adjust the style and placement of labels, they have no effect if no labels are shown. - ``label_fontsize`` -- integer (default: 9), the font size of the labels. - ``label_colors`` -- string or sequence of colors (default: None) If a string, gives the name of a single color with which to draw all labels. If a sequence, gives the colors of the labels. A color is a string giving the name of one or a 3-tuple of floats. - ``label_inline`` -- boolean (default: False if fill is True, otherwise True), controls whether the underlying contour is removed or not. - ``label_inline_spacing`` -- integer (default: 3), When inline, this is the amount of contour that is removed from each side, in pixels. - ``label_fmt`` -- a format string (default: "%1.2f"), this is used to get the label text from the level. This can also be a dictionary with the contour levels as keys and corresponding text string labels as values. EXAMPLES: Here we plot a simple function of two variables. Note that since the input function is an expression, we need to explicitly declare the variables in 3-tuples for the range:: sage: x,y = var('x,y') sage: contour_plot(cos(x^2+y^2), (x, -4, 4), (y, -4, 4)) Here we change the ranges and add some options:: sage: x,y = var('x,y') sage: contour_plot((x^2)*cos(x*y), (x, -10, 5), (y, -5, 5), fill=False, plot_points=150) An even more complicated plot:: sage: x,y = var('x,y') sage: contour_plot(sin(x^2 + y^2)*cos(x)*sin(y), (x, -4, 4), (y, -4, 4),plot_points=150) Some elliptic curves, but with symbolic endpoints. In the first example, the plot is rotated 90 degrees because we switch the variables x,y:: sage: x,y = var('x,y') sage: contour_plot(y^2 + 1 - x^3 - x, (y,-pi,pi), (x,-pi,pi)) sage: contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi)) We can play with the contour levels:: sage: x,y = var('x,y') sage: f(x,y) = x^2 + y^2 sage: contour_plot(f, (-2, 2), (-2, 2)) sage: contour_plot(f, (-2, 2), (-2, 2), contours=2, cmap=[(1,0,0), (0,1,0), (0,0,1)]) sage: contour_plot(f, (-2, 2), (-2, 2), contours=(0.1, 1.0, 1.2, 1.4), cmap='hsv') sage: contour_plot(f, (-2, 2), (-2, 2), contours=(1.0,), fill=False, aspect_ratio=1) sage: contour_plot(x-y^2,(x,-5,5),(y,-3,3),contours=[-4,0,1]) We can change the style of the lines:: sage: contour_plot(f, (-2,2), (-2,2), fill=False, linewidths=10) sage: contour_plot(f, (-2,2), (-2,2), fill=False, linestyles='dashdot') sage: contour_plot(x^2-y^2,(x,-3,3),(y,-3,3),contours=[0,1,2,3,4],linewidths=[1,5],linestyles=['solid','dashed'],fill=False) sage: contour_plot(x^2-y^2,(x,-3,3),(y,-3,3),contours=[0,1,2,3,4],linewidths=[1,5],linestyles=['solid','dashed']) We can add labels and play with them:: sage: contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), fill=False, cmap='hsv', labels=True) sage: contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), fill=False, cmap='hsv', labels=True, label_fmt="%1.0f", label_colors='black') sage: contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), fill=False, cmap='hsv', labels=True, contours=[-4,0,4], label_fmt={-4:"low", 0:"medium", 4: "hi"}, label_colors='black') sage: contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), fill=False, cmap='hsv', labels=True, label_fontsize=18) sage: contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), fill=False, cmap='hsv', labels=True, label_inline_spacing=1) sage: contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), fill=False, cmap='hsv', labels=True, label_inline=False) If fill is True (the default), then we may have to color the labels so that we can see them:: sage: contour_plot(f, (-2,2), (-2,2), labels=True, label_colors='red') This should plot concentric circles centered at the origin:: sage: x,y = var('x,y') sage: contour_plot(x^2+y^2-2,(x,-1,1), (y,-1,1)).show(aspect_ratio=1) Extra options will get passed on to show(), as long as they are valid:: sage: f(x, y) = cos(x) + sin(y) sage: contour_plot(f, (0, pi), (0, pi), axes=True) sage: contour_plot(f, (0, pi), (0, pi)).show(axes=True) # These are equivalent Note that with ``fill=False`` and grayscale contours, there is the possibility of confusion between the contours and the axes, so use ``fill=False`` together with ``axes=True`` with caution:: sage: contour_plot(f, (-pi, pi), (-pi, pi), fill=False, axes=True) TESTS: To check that ticket 5221 is fixed, note that this has three curves, not two:: sage: x,y = var('x,y') sage: contour_plot(x-y^2,(x,-5,5),(y,-3,3),contours=[-4,-2,0], fill=False) """ from sage.plot.plot import Graphics from sage.plot.misc import setup_for_eval_on_grid g, ranges = setup_for_eval_on_grid([f], [xrange, yrange], options['plot_points']) g = g[0] xrange,yrange=[r[:2] for r in ranges] xy_data_array = [[g(x, y) for x in xsrange(*ranges[0], include_endpoint=True)] for y in xsrange(*ranges[1], include_endpoint=True)] g = Graphics() g._set_extra_kwds(Graphics._extract_kwds_for_show(options, ignore=['xmin', 'xmax'])) g.add_primitive(ContourPlot(xy_data_array, xrange, yrange, options)) return g
1be89942e80d3d044db8b1d126931ba7f5a875fb /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/1be89942e80d3d044db8b1d126931ba7f5a875fb/contour_plot.py
sage: contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), fill=False, cmap='hsv', labels=True) sage: contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), fill=False, cmap='hsv', labels=True, label_fmt="%1.0f", label_colors='black') sage: contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), fill=False, cmap='hsv', labels=True, contours=[-4,0,4], label_fmt={-4:"low", 0:"medium", 4: "hi"}, label_colors='black') sage: contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), fill=False, cmap='hsv', labels=True, label_fontsize=18) sage: contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), fill=False, cmap='hsv', labels=True, label_inline_spacing=1) sage: contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), fill=False, cmap='hsv', labels=True, label_inline=False)
sage: contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), fill=False, cmap='hsv', labels=True) :: sage: P=contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), fill=False, cmap='hsv',\ ... labels=True, label_fmt="%1.0f", label_colors='black') sage: P :: sage: P=contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), fill=False, cmap='hsv',labels=True,\ ... contours=[-4,0,4], label_fmt={-4:"low", 0:"medium", 4: "hi"}, label_colors='black') sage: P :: sage: P=contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), \ ... fill=False, cmap='hsv', labels=True, label_fontsize=18) sage: P :: sage: P=contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), \ ... fill=False, cmap='hsv', labels=True, label_inline_spacing=1) sage: P :: sage: P= contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), \ ... fill=False, cmap='hsv', labels=True, label_inline=False) sage: P
def contour_plot(f, xrange, yrange, **options): r""" ``contour_plot`` takes a function of two variables, `f(x,y)` and plots contour lines of the function over the specified ``xrange`` and ``yrange`` as demonstrated below. ``contour_plot(f, (xmin, xmax), (ymin, ymax), ...)`` INPUT: - ``f`` -- a 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)`` The following inputs must all be passed in as named parameters: - ``plot_points`` -- integer (default: 100); number of points to plot in each direction of the grid. For old computers, 25 is fine, but should not be used to verify specific intersection points. - ``fill`` -- bool (default: ``True``), whether to color in the area between contour lines - ``cmap`` -- a colormap (default: ``'gray'``), the name of a predefined colormap, a list of colors or an instance of a matplotlib Colormap. Type: ``import matplotlib.cm; matplotlib.cm.datad.keys()`` for available colormap names. - ``contours`` -- integer or list of numbers (default: ``None``): If a list of numbers is given, then this specifies the contour levels to use. If an integer is given, then this many contour lines are used, but the exact levels are determined automatically. If ``None`` is passed (or the option is not given), then the number of contour lines is determined automatically, and is usually about 5. - ``linewidths`` -- integer or list of integer (default: None), if a single integer all levels will be of the width given, otherwise the levels will be plotted with the width in the order given. If the list is shorter than the number of contours, then the widths will be repeated cyclically. - ``linestyles`` -- string or list of strings (default: None), the style of the lines to be plotted, one of: solid, dashed, dashdot, or dotted. If the list is shorter than the number of contours, then the styles will be repeated cyclically. - ``labels`` -- boolean (default: False) Show level labels or not. The following options are to adjust the style and placement of labels, they have no effect if no labels are shown. - ``label_fontsize`` -- integer (default: 9), the font size of the labels. - ``label_colors`` -- string or sequence of colors (default: None) If a string, gives the name of a single color with which to draw all labels. If a sequence, gives the colors of the labels. A color is a string giving the name of one or a 3-tuple of floats. - ``label_inline`` -- boolean (default: False if fill is True, otherwise True), controls whether the underlying contour is removed or not. - ``label_inline_spacing`` -- integer (default: 3), When inline, this is the amount of contour that is removed from each side, in pixels. - ``label_fmt`` -- a format string (default: "%1.2f"), this is used to get the label text from the level. This can also be a dictionary with the contour levels as keys and corresponding text string labels as values. EXAMPLES: Here we plot a simple function of two variables. Note that since the input function is an expression, we need to explicitly declare the variables in 3-tuples for the range:: sage: x,y = var('x,y') sage: contour_plot(cos(x^2+y^2), (x, -4, 4), (y, -4, 4)) Here we change the ranges and add some options:: sage: x,y = var('x,y') sage: contour_plot((x^2)*cos(x*y), (x, -10, 5), (y, -5, 5), fill=False, plot_points=150) An even more complicated plot:: sage: x,y = var('x,y') sage: contour_plot(sin(x^2 + y^2)*cos(x)*sin(y), (x, -4, 4), (y, -4, 4),plot_points=150) Some elliptic curves, but with symbolic endpoints. In the first example, the plot is rotated 90 degrees because we switch the variables x,y:: sage: x,y = var('x,y') sage: contour_plot(y^2 + 1 - x^3 - x, (y,-pi,pi), (x,-pi,pi)) sage: contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi)) We can play with the contour levels:: sage: x,y = var('x,y') sage: f(x,y) = x^2 + y^2 sage: contour_plot(f, (-2, 2), (-2, 2)) sage: contour_plot(f, (-2, 2), (-2, 2), contours=2, cmap=[(1,0,0), (0,1,0), (0,0,1)]) sage: contour_plot(f, (-2, 2), (-2, 2), contours=(0.1, 1.0, 1.2, 1.4), cmap='hsv') sage: contour_plot(f, (-2, 2), (-2, 2), contours=(1.0,), fill=False, aspect_ratio=1) sage: contour_plot(x-y^2,(x,-5,5),(y,-3,3),contours=[-4,0,1]) We can change the style of the lines:: sage: contour_plot(f, (-2,2), (-2,2), fill=False, linewidths=10) sage: contour_plot(f, (-2,2), (-2,2), fill=False, linestyles='dashdot') sage: contour_plot(x^2-y^2,(x,-3,3),(y,-3,3),contours=[0,1,2,3,4],linewidths=[1,5],linestyles=['solid','dashed'],fill=False) sage: contour_plot(x^2-y^2,(x,-3,3),(y,-3,3),contours=[0,1,2,3,4],linewidths=[1,5],linestyles=['solid','dashed']) We can add labels and play with them:: sage: contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), fill=False, cmap='hsv', labels=True) sage: contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), fill=False, cmap='hsv', labels=True, label_fmt="%1.0f", label_colors='black') sage: contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), fill=False, cmap='hsv', labels=True, contours=[-4,0,4], label_fmt={-4:"low", 0:"medium", 4: "hi"}, label_colors='black') sage: contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), fill=False, cmap='hsv', labels=True, label_fontsize=18) sage: contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), fill=False, cmap='hsv', labels=True, label_inline_spacing=1) sage: contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), fill=False, cmap='hsv', labels=True, label_inline=False) If fill is True (the default), then we may have to color the labels so that we can see them:: sage: contour_plot(f, (-2,2), (-2,2), labels=True, label_colors='red') This should plot concentric circles centered at the origin:: sage: x,y = var('x,y') sage: contour_plot(x^2+y^2-2,(x,-1,1), (y,-1,1)).show(aspect_ratio=1) Extra options will get passed on to show(), as long as they are valid:: sage: f(x, y) = cos(x) + sin(y) sage: contour_plot(f, (0, pi), (0, pi), axes=True) sage: contour_plot(f, (0, pi), (0, pi)).show(axes=True) # These are equivalent Note that with ``fill=False`` and grayscale contours, there is the possibility of confusion between the contours and the axes, so use ``fill=False`` together with ``axes=True`` with caution:: sage: contour_plot(f, (-pi, pi), (-pi, pi), fill=False, axes=True) TESTS: To check that ticket 5221 is fixed, note that this has three curves, not two:: sage: x,y = var('x,y') sage: contour_plot(x-y^2,(x,-5,5),(y,-3,3),contours=[-4,-2,0], fill=False) """ from sage.plot.plot import Graphics from sage.plot.misc import setup_for_eval_on_grid g, ranges = setup_for_eval_on_grid([f], [xrange, yrange], options['plot_points']) g = g[0] xrange,yrange=[r[:2] for r in ranges] xy_data_array = [[g(x, y) for x in xsrange(*ranges[0], include_endpoint=True)] for y in xsrange(*ranges[1], include_endpoint=True)] g = Graphics() g._set_extra_kwds(Graphics._extract_kwds_for_show(options, ignore=['xmin', 'xmax'])) g.add_primitive(ContourPlot(xy_data_array, xrange, yrange, options)) return g
1be89942e80d3d044db8b1d126931ba7f5a875fb /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/1be89942e80d3d044db8b1d126931ba7f5a875fb/contour_plot.py
- ``m``, ``n`` - two moduli, or None.
- ``m``, ``n`` - (default: ``None``) two moduli, or ``None``.
def crt(a,b,m=None,n=None): r""" Returns a solution to a Chinese Remainder Theorem problem. INPUT: - ``a``, ``b`` - two residues (elements of some ring for which extended gcd is available), or two lists, one of residues and one of moduli. - ``m``, ``n`` - two moduli, or None. OUTPUT: If ``m``, ``n`` are not None, returns a solution `x` to the simultaneous congruences `x\equiv a \bmod m` and `x\equiv b \bmod n`, if one exists; which is if and only if `a\equiv b\pmod{\gcd(m,n)}` by the Chinese Remainder Theorem. The solution `x` is only well-defined modulo lcm`(m,n)`. If ``a`` and ``b`` are lists, returns a simultaneous solution to the congruences `x\equiv a_i\pmod{b_i}`, if one exists. EXAMPLES:: sage: crt(2, 1, 3, 5) 11 sage: crt(13,20,100,301) 28013 You can also use upper case:: sage: c = CRT(2,3, 3, 5); c 8 sage: c % 3 == 2 True sage: c % 5 == 3 True Note that this also works for polynomial rings:: sage: K.<a> = NumberField(x^3 - 7) sage: R.<y> = K[] sage: f = y^2 + 3 sage: g = y^3 - 5 sage: CRT(1,3,f,g) -3/26*y^4 + 5/26*y^3 + 15/26*y + 53/26 sage: CRT(1,a,f,g) (-3/52*a + 3/52)*y^4 + (5/52*a - 5/52)*y^3 + (15/52*a - 15/52)*y + 27/52*a + 25/52 You can also do this for any number of moduli:: sage: K.<a> = NumberField(x^3 - 7) sage: R.<x> = K[] sage: CRT([], []) 0 sage: CRT([a], [x]) a sage: f = x^2 + 3 sage: g = x^3 - 5 sage: h = x^5 + x^2 - 9 sage: k = CRT([1, a, 3], [f, g, h]); k (127/26988*a - 5807/386828)*x^9 + (45/8996*a - 33677/1160484)*x^8 + (2/173*a - 6/173)*x^7 + (133/6747*a - 5373/96707)*x^6 + (-6/2249*a + 18584/290121)*x^5 + (-277/8996*a + 38847/386828)*x^4 + (-135/4498*a + 42673/193414)*x^3 + (-1005/8996*a + 470245/1160484)*x^2 + (-1215/8996*a + 141165/386828)*x + 621/8996*a + 836445/386828 sage: k.mod(f) 1 sage: k.mod(g) a sage: k.mod(h) 3 If the moduli are not coprime, a solution may not exist:: sage: crt(4,8,8,12) 20 sage: crt(4,6,8,12) Traceback (most recent call last): ... ValueError: No solution to crt problem since gcd(8,12) does not divide 4-6 sage: x = polygen(QQ) sage: crt(2,3,x-1,x+1) -1/2*x + 5/2 sage: crt(2,x,x^2-1,x^2+1) -1/2*x^3 + x^2 + 1/2*x + 1 sage: crt(2,x,x^2-1,x^3-1) Traceback (most recent call last): ... ValueError: No solution to crt problem since gcd(x^2 - 1,x^3 - 1) does not divide 2-x """ if isinstance(a,list): return CRT_list(a,b) g, alpha, beta = XGCD(m,n) q,r = (b-a).quo_rem(g) if r!=0: raise ValueError, "No solution to crt problem since gcd(%s,%s) does not divide %s-%s"%(m,n,a,b) return (a+q*alpha*m) % lcm(m,n)
c4c4857b06059d9fdba46cbaf64ffd83c3f8bac4 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/c4c4857b06059d9fdba46cbaf64ffd83c3f8bac4/arith.py
If ``m``, ``n`` are not None, returns a solution `x` to the
If ``m``, ``n`` are not ``None``, returns a solution `x` to the
def crt(a,b,m=None,n=None): r""" Returns a solution to a Chinese Remainder Theorem problem. INPUT: - ``a``, ``b`` - two residues (elements of some ring for which extended gcd is available), or two lists, one of residues and one of moduli. - ``m``, ``n`` - two moduli, or None. OUTPUT: If ``m``, ``n`` are not None, returns a solution `x` to the simultaneous congruences `x\equiv a \bmod m` and `x\equiv b \bmod n`, if one exists; which is if and only if `a\equiv b\pmod{\gcd(m,n)}` by the Chinese Remainder Theorem. The solution `x` is only well-defined modulo lcm`(m,n)`. If ``a`` and ``b`` are lists, returns a simultaneous solution to the congruences `x\equiv a_i\pmod{b_i}`, if one exists. EXAMPLES:: sage: crt(2, 1, 3, 5) 11 sage: crt(13,20,100,301) 28013 You can also use upper case:: sage: c = CRT(2,3, 3, 5); c 8 sage: c % 3 == 2 True sage: c % 5 == 3 True Note that this also works for polynomial rings:: sage: K.<a> = NumberField(x^3 - 7) sage: R.<y> = K[] sage: f = y^2 + 3 sage: g = y^3 - 5 sage: CRT(1,3,f,g) -3/26*y^4 + 5/26*y^3 + 15/26*y + 53/26 sage: CRT(1,a,f,g) (-3/52*a + 3/52)*y^4 + (5/52*a - 5/52)*y^3 + (15/52*a - 15/52)*y + 27/52*a + 25/52 You can also do this for any number of moduli:: sage: K.<a> = NumberField(x^3 - 7) sage: R.<x> = K[] sage: CRT([], []) 0 sage: CRT([a], [x]) a sage: f = x^2 + 3 sage: g = x^3 - 5 sage: h = x^5 + x^2 - 9 sage: k = CRT([1, a, 3], [f, g, h]); k (127/26988*a - 5807/386828)*x^9 + (45/8996*a - 33677/1160484)*x^8 + (2/173*a - 6/173)*x^7 + (133/6747*a - 5373/96707)*x^6 + (-6/2249*a + 18584/290121)*x^5 + (-277/8996*a + 38847/386828)*x^4 + (-135/4498*a + 42673/193414)*x^3 + (-1005/8996*a + 470245/1160484)*x^2 + (-1215/8996*a + 141165/386828)*x + 621/8996*a + 836445/386828 sage: k.mod(f) 1 sage: k.mod(g) a sage: k.mod(h) 3 If the moduli are not coprime, a solution may not exist:: sage: crt(4,8,8,12) 20 sage: crt(4,6,8,12) Traceback (most recent call last): ... ValueError: No solution to crt problem since gcd(8,12) does not divide 4-6 sage: x = polygen(QQ) sage: crt(2,3,x-1,x+1) -1/2*x + 5/2 sage: crt(2,x,x^2-1,x^2+1) -1/2*x^3 + x^2 + 1/2*x + 1 sage: crt(2,x,x^2-1,x^3-1) Traceback (most recent call last): ... ValueError: No solution to crt problem since gcd(x^2 - 1,x^3 - 1) does not divide 2-x """ if isinstance(a,list): return CRT_list(a,b) g, alpha, beta = XGCD(m,n) q,r = (b-a).quo_rem(g) if r!=0: raise ValueError, "No solution to crt problem since gcd(%s,%s) does not divide %s-%s"%(m,n,a,b) return (a+q*alpha*m) % lcm(m,n)
c4c4857b06059d9fdba46cbaf64ffd83c3f8bac4 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/c4c4857b06059d9fdba46cbaf64ffd83c3f8bac4/arith.py
n`, if one exists; which is if and only if `a\equiv b\pmod{\gcd(m,n)}` by the Chinese Remainder Theorem. The solution `x` is only well-defined modulo lcm`(m,n)`.
n`, if one exists. By the Chinese Remainder Theorem, a solution to the simultaneous congruences exists if and only if `a\equiv b\pmod{\gcd(m,n)}`. The solution `x` is only well-defined modulo `\text{lcm}(m,n)`.
def crt(a,b,m=None,n=None): r""" Returns a solution to a Chinese Remainder Theorem problem. INPUT: - ``a``, ``b`` - two residues (elements of some ring for which extended gcd is available), or two lists, one of residues and one of moduli. - ``m``, ``n`` - two moduli, or None. OUTPUT: If ``m``, ``n`` are not None, returns a solution `x` to the simultaneous congruences `x\equiv a \bmod m` and `x\equiv b \bmod n`, if one exists; which is if and only if `a\equiv b\pmod{\gcd(m,n)}` by the Chinese Remainder Theorem. The solution `x` is only well-defined modulo lcm`(m,n)`. If ``a`` and ``b`` are lists, returns a simultaneous solution to the congruences `x\equiv a_i\pmod{b_i}`, if one exists. EXAMPLES:: sage: crt(2, 1, 3, 5) 11 sage: crt(13,20,100,301) 28013 You can also use upper case:: sage: c = CRT(2,3, 3, 5); c 8 sage: c % 3 == 2 True sage: c % 5 == 3 True Note that this also works for polynomial rings:: sage: K.<a> = NumberField(x^3 - 7) sage: R.<y> = K[] sage: f = y^2 + 3 sage: g = y^3 - 5 sage: CRT(1,3,f,g) -3/26*y^4 + 5/26*y^3 + 15/26*y + 53/26 sage: CRT(1,a,f,g) (-3/52*a + 3/52)*y^4 + (5/52*a - 5/52)*y^3 + (15/52*a - 15/52)*y + 27/52*a + 25/52 You can also do this for any number of moduli:: sage: K.<a> = NumberField(x^3 - 7) sage: R.<x> = K[] sage: CRT([], []) 0 sage: CRT([a], [x]) a sage: f = x^2 + 3 sage: g = x^3 - 5 sage: h = x^5 + x^2 - 9 sage: k = CRT([1, a, 3], [f, g, h]); k (127/26988*a - 5807/386828)*x^9 + (45/8996*a - 33677/1160484)*x^8 + (2/173*a - 6/173)*x^7 + (133/6747*a - 5373/96707)*x^6 + (-6/2249*a + 18584/290121)*x^5 + (-277/8996*a + 38847/386828)*x^4 + (-135/4498*a + 42673/193414)*x^3 + (-1005/8996*a + 470245/1160484)*x^2 + (-1215/8996*a + 141165/386828)*x + 621/8996*a + 836445/386828 sage: k.mod(f) 1 sage: k.mod(g) a sage: k.mod(h) 3 If the moduli are not coprime, a solution may not exist:: sage: crt(4,8,8,12) 20 sage: crt(4,6,8,12) Traceback (most recent call last): ... ValueError: No solution to crt problem since gcd(8,12) does not divide 4-6 sage: x = polygen(QQ) sage: crt(2,3,x-1,x+1) -1/2*x + 5/2 sage: crt(2,x,x^2-1,x^2+1) -1/2*x^3 + x^2 + 1/2*x + 1 sage: crt(2,x,x^2-1,x^3-1) Traceback (most recent call last): ... ValueError: No solution to crt problem since gcd(x^2 - 1,x^3 - 1) does not divide 2-x """ if isinstance(a,list): return CRT_list(a,b) g, alpha, beta = XGCD(m,n) q,r = (b-a).quo_rem(g) if r!=0: raise ValueError, "No solution to crt problem since gcd(%s,%s) does not divide %s-%s"%(m,n,a,b) return (a+q*alpha*m) % lcm(m,n)
c4c4857b06059d9fdba46cbaf64ffd83c3f8bac4 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/c4c4857b06059d9fdba46cbaf64ffd83c3f8bac4/arith.py
EXAMPLES::
.. SEEALSO:: - :func:`CRT_list` EXAMPLES: Using ``crt`` by giving it pairs of residues and moduli::
def crt(a,b,m=None,n=None): r""" Returns a solution to a Chinese Remainder Theorem problem. INPUT: - ``a``, ``b`` - two residues (elements of some ring for which extended gcd is available), or two lists, one of residues and one of moduli. - ``m``, ``n`` - two moduli, or None. OUTPUT: If ``m``, ``n`` are not None, returns a solution `x` to the simultaneous congruences `x\equiv a \bmod m` and `x\equiv b \bmod n`, if one exists; which is if and only if `a\equiv b\pmod{\gcd(m,n)}` by the Chinese Remainder Theorem. The solution `x` is only well-defined modulo lcm`(m,n)`. If ``a`` and ``b`` are lists, returns a simultaneous solution to the congruences `x\equiv a_i\pmod{b_i}`, if one exists. EXAMPLES:: sage: crt(2, 1, 3, 5) 11 sage: crt(13,20,100,301) 28013 You can also use upper case:: sage: c = CRT(2,3, 3, 5); c 8 sage: c % 3 == 2 True sage: c % 5 == 3 True Note that this also works for polynomial rings:: sage: K.<a> = NumberField(x^3 - 7) sage: R.<y> = K[] sage: f = y^2 + 3 sage: g = y^3 - 5 sage: CRT(1,3,f,g) -3/26*y^4 + 5/26*y^3 + 15/26*y + 53/26 sage: CRT(1,a,f,g) (-3/52*a + 3/52)*y^4 + (5/52*a - 5/52)*y^3 + (15/52*a - 15/52)*y + 27/52*a + 25/52 You can also do this for any number of moduli:: sage: K.<a> = NumberField(x^3 - 7) sage: R.<x> = K[] sage: CRT([], []) 0 sage: CRT([a], [x]) a sage: f = x^2 + 3 sage: g = x^3 - 5 sage: h = x^5 + x^2 - 9 sage: k = CRT([1, a, 3], [f, g, h]); k (127/26988*a - 5807/386828)*x^9 + (45/8996*a - 33677/1160484)*x^8 + (2/173*a - 6/173)*x^7 + (133/6747*a - 5373/96707)*x^6 + (-6/2249*a + 18584/290121)*x^5 + (-277/8996*a + 38847/386828)*x^4 + (-135/4498*a + 42673/193414)*x^3 + (-1005/8996*a + 470245/1160484)*x^2 + (-1215/8996*a + 141165/386828)*x + 621/8996*a + 836445/386828 sage: k.mod(f) 1 sage: k.mod(g) a sage: k.mod(h) 3 If the moduli are not coprime, a solution may not exist:: sage: crt(4,8,8,12) 20 sage: crt(4,6,8,12) Traceback (most recent call last): ... ValueError: No solution to crt problem since gcd(8,12) does not divide 4-6 sage: x = polygen(QQ) sage: crt(2,3,x-1,x+1) -1/2*x + 5/2 sage: crt(2,x,x^2-1,x^2+1) -1/2*x^3 + x^2 + 1/2*x + 1 sage: crt(2,x,x^2-1,x^3-1) Traceback (most recent call last): ... ValueError: No solution to crt problem since gcd(x^2 - 1,x^3 - 1) does not divide 2-x """ if isinstance(a,list): return CRT_list(a,b) g, alpha, beta = XGCD(m,n) q,r = (b-a).quo_rem(g) if r!=0: raise ValueError, "No solution to crt problem since gcd(%s,%s) does not divide %s-%s"%(m,n,a,b) return (a+q*alpha*m) % lcm(m,n)
c4c4857b06059d9fdba46cbaf64ffd83c3f8bac4 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/c4c4857b06059d9fdba46cbaf64ffd83c3f8bac4/arith.py
sage: crt(13,20,100,301)
sage: crt(13, 20, 100, 301) 28013 sage: crt([2, 1], [3, 5]) 11 sage: crt([13, 20], [100, 301])
def crt(a,b,m=None,n=None): r""" Returns a solution to a Chinese Remainder Theorem problem. INPUT: - ``a``, ``b`` - two residues (elements of some ring for which extended gcd is available), or two lists, one of residues and one of moduli. - ``m``, ``n`` - two moduli, or None. OUTPUT: If ``m``, ``n`` are not None, returns a solution `x` to the simultaneous congruences `x\equiv a \bmod m` and `x\equiv b \bmod n`, if one exists; which is if and only if `a\equiv b\pmod{\gcd(m,n)}` by the Chinese Remainder Theorem. The solution `x` is only well-defined modulo lcm`(m,n)`. If ``a`` and ``b`` are lists, returns a simultaneous solution to the congruences `x\equiv a_i\pmod{b_i}`, if one exists. EXAMPLES:: sage: crt(2, 1, 3, 5) 11 sage: crt(13,20,100,301) 28013 You can also use upper case:: sage: c = CRT(2,3, 3, 5); c 8 sage: c % 3 == 2 True sage: c % 5 == 3 True Note that this also works for polynomial rings:: sage: K.<a> = NumberField(x^3 - 7) sage: R.<y> = K[] sage: f = y^2 + 3 sage: g = y^3 - 5 sage: CRT(1,3,f,g) -3/26*y^4 + 5/26*y^3 + 15/26*y + 53/26 sage: CRT(1,a,f,g) (-3/52*a + 3/52)*y^4 + (5/52*a - 5/52)*y^3 + (15/52*a - 15/52)*y + 27/52*a + 25/52 You can also do this for any number of moduli:: sage: K.<a> = NumberField(x^3 - 7) sage: R.<x> = K[] sage: CRT([], []) 0 sage: CRT([a], [x]) a sage: f = x^2 + 3 sage: g = x^3 - 5 sage: h = x^5 + x^2 - 9 sage: k = CRT([1, a, 3], [f, g, h]); k (127/26988*a - 5807/386828)*x^9 + (45/8996*a - 33677/1160484)*x^8 + (2/173*a - 6/173)*x^7 + (133/6747*a - 5373/96707)*x^6 + (-6/2249*a + 18584/290121)*x^5 + (-277/8996*a + 38847/386828)*x^4 + (-135/4498*a + 42673/193414)*x^3 + (-1005/8996*a + 470245/1160484)*x^2 + (-1215/8996*a + 141165/386828)*x + 621/8996*a + 836445/386828 sage: k.mod(f) 1 sage: k.mod(g) a sage: k.mod(h) 3 If the moduli are not coprime, a solution may not exist:: sage: crt(4,8,8,12) 20 sage: crt(4,6,8,12) Traceback (most recent call last): ... ValueError: No solution to crt problem since gcd(8,12) does not divide 4-6 sage: x = polygen(QQ) sage: crt(2,3,x-1,x+1) -1/2*x + 5/2 sage: crt(2,x,x^2-1,x^2+1) -1/2*x^3 + x^2 + 1/2*x + 1 sage: crt(2,x,x^2-1,x^3-1) Traceback (most recent call last): ... ValueError: No solution to crt problem since gcd(x^2 - 1,x^3 - 1) does not divide 2-x """ if isinstance(a,list): return CRT_list(a,b) g, alpha, beta = XGCD(m,n) q,r = (b-a).quo_rem(g) if r!=0: raise ValueError, "No solution to crt problem since gcd(%s,%s) does not divide %s-%s"%(m,n,a,b) return (a+q*alpha*m) % lcm(m,n)
c4c4857b06059d9fdba46cbaf64ffd83c3f8bac4 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/c4c4857b06059d9fdba46cbaf64ffd83c3f8bac4/arith.py
if isinstance(a,list): return CRT_list(a,b) g, alpha, beta = XGCD(m,n) q,r = (b-a).quo_rem(g) if r!=0: raise ValueError, "No solution to crt problem since gcd(%s,%s) does not divide %s-%s"%(m,n,a,b) return (a+q*alpha*m) % lcm(m,n)
if isinstance(a, list): return CRT_list(a, b) g, alpha, beta = XGCD(m, n) q, r = (b - a).quo_rem(g) if r != 0: raise ValueError("No solution to crt problem since gcd(%s,%s) does not divide %s-%s" % (m, n, a, b)) return (a + q*alpha*m) % lcm(m, n)
def crt(a,b,m=None,n=None): r""" Returns a solution to a Chinese Remainder Theorem problem. INPUT: - ``a``, ``b`` - two residues (elements of some ring for which extended gcd is available), or two lists, one of residues and one of moduli. - ``m``, ``n`` - two moduli, or None. OUTPUT: If ``m``, ``n`` are not None, returns a solution `x` to the simultaneous congruences `x\equiv a \bmod m` and `x\equiv b \bmod n`, if one exists; which is if and only if `a\equiv b\pmod{\gcd(m,n)}` by the Chinese Remainder Theorem. The solution `x` is only well-defined modulo lcm`(m,n)`. If ``a`` and ``b`` are lists, returns a simultaneous solution to the congruences `x\equiv a_i\pmod{b_i}`, if one exists. EXAMPLES:: sage: crt(2, 1, 3, 5) 11 sage: crt(13,20,100,301) 28013 You can also use upper case:: sage: c = CRT(2,3, 3, 5); c 8 sage: c % 3 == 2 True sage: c % 5 == 3 True Note that this also works for polynomial rings:: sage: K.<a> = NumberField(x^3 - 7) sage: R.<y> = K[] sage: f = y^2 + 3 sage: g = y^3 - 5 sage: CRT(1,3,f,g) -3/26*y^4 + 5/26*y^3 + 15/26*y + 53/26 sage: CRT(1,a,f,g) (-3/52*a + 3/52)*y^4 + (5/52*a - 5/52)*y^3 + (15/52*a - 15/52)*y + 27/52*a + 25/52 You can also do this for any number of moduli:: sage: K.<a> = NumberField(x^3 - 7) sage: R.<x> = K[] sage: CRT([], []) 0 sage: CRT([a], [x]) a sage: f = x^2 + 3 sage: g = x^3 - 5 sage: h = x^5 + x^2 - 9 sage: k = CRT([1, a, 3], [f, g, h]); k (127/26988*a - 5807/386828)*x^9 + (45/8996*a - 33677/1160484)*x^8 + (2/173*a - 6/173)*x^7 + (133/6747*a - 5373/96707)*x^6 + (-6/2249*a + 18584/290121)*x^5 + (-277/8996*a + 38847/386828)*x^4 + (-135/4498*a + 42673/193414)*x^3 + (-1005/8996*a + 470245/1160484)*x^2 + (-1215/8996*a + 141165/386828)*x + 621/8996*a + 836445/386828 sage: k.mod(f) 1 sage: k.mod(g) a sage: k.mod(h) 3 If the moduli are not coprime, a solution may not exist:: sage: crt(4,8,8,12) 20 sage: crt(4,6,8,12) Traceback (most recent call last): ... ValueError: No solution to crt problem since gcd(8,12) does not divide 4-6 sage: x = polygen(QQ) sage: crt(2,3,x-1,x+1) -1/2*x + 5/2 sage: crt(2,x,x^2-1,x^2+1) -1/2*x^3 + x^2 + 1/2*x + 1 sage: crt(2,x,x^2-1,x^3-1) Traceback (most recent call last): ... ValueError: No solution to crt problem since gcd(x^2 - 1,x^3 - 1) does not divide 2-x """ if isinstance(a,list): return CRT_list(a,b) g, alpha, beta = XGCD(m,n) q,r = (b-a).quo_rem(g) if r!=0: raise ValueError, "No solution to crt problem since gcd(%s,%s) does not divide %s-%s"%(m,n,a,b) return (a+q*alpha*m) % lcm(m,n)
c4c4857b06059d9fdba46cbaf64ffd83c3f8bac4 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/c4c4857b06059d9fdba46cbaf64ffd83c3f8bac4/arith.py
and only if `p_2` dominates `p_1`.
and only if the conjugate of `p_2` dominates `p_1`.
def gale_ryser_theorem(p1, p2, algorithm="ryser"): r""" Returns the binary matrix given by the Gale-Ryser theorem. The Gale Ryser theorem asserts that if `p_1,p_2` are two partitions of `n` of respective lengths `k_1,k_2`, then there is a binary `k_1\times k_2` matrix `M` such that `p_1` is the vector of row sums and `p_2` is the vector of column sums of `M`, if and only if `p_2` dominates `p_1`. INPUT: - ``p1`` -- the first partition of `n` (trailing 0's allowed) - ``p2`` -- the second partition of `n` (trailing 0's allowed) - ``algorithm`` -- two possible string values : - ``"ryser"`` (default) implements the construction due to Ryser [Ryser63]_. - ``"gale"`` implements the construction due to Gale [Gale57]_. OUTPUT: - A binary matrix if it exists, ``None`` otherwise. Gale's Algorithm: (Gale [Gale57]_): A matrix satisfying the constraints of its sums can be defined as the solution of the following Linear Program, which Sage knows how to solve (requires packages GLPK or CBC). .. MATH:: \forall i&\sum_{j=1}^{k_2} b_{i,j}=p_{1,j}\\ \forall i&\sum_{j=1}^{k_1} b_{j,i}=p_{2,j}\\ &b_{i,j}\mbox{ is a binary variable} Ryser's Algorithm: (Ryser [Ryser63]_): The construction of an `m\times n` matrix `A=A_{r,s}`, due to Ryser, is described as follows. The construction works if and only if have `s\preceq r^*`. * Construct the `m\times n` matrix `B` from `r` by defining the `i`-th row of `B` to be the vector whose first `r_i` entries are `1`, and the remainder are 0's, `1\leq i\leq m`. This maximal matrix `B` with row sum `r` and ones left justified has column sum `r^{*}`. * Shift the last `1` in certain rows of `B` to column `n` in order to achieve the sum `s_n`. Call this `B` again. * The `1`'s in column n are to appear in those rows in which `A` has the largest row sums, giving preference to the bottom-most positions in case of ties. * Note: When this step automatically "fixes" other columns, one must skip ahead to the first column index with a wrong sum in the step below. * Proceed inductively to construct columns `n-1`, ..., `2`, `1`. * Set `A = B`. Return `A`. EXAMPLES: Computing the matrix for `p_1=p_2=2+2+1` :: sage: from sage.combinat.integer_vector import gale_ryser_theorem sage: p1 = [2,2,1] sage: p2 = [2,2,1] sage: print gale_ryser_theorem(p1, p2, algorithm="gale") # Optional - requires GLPK or CBC [0 1 1] [1 1 0] [1 0 0] Or for a non-square matrix with `p_1=3+3+2+1` and `p_2=3+2+2+1+1` :: sage: from sage.combinat.integer_vector import gale_ryser_theorem sage: p1 = [3,3,1,1] sage: p2 = [3,3,1,1] sage: gale_ryser_theorem(p1, p2) [1 1 1 0] [1 1 0 1] [1 0 0 0] [0 1 0 0] sage: p1 = [4,2,2] sage: p2 = [3,3,1,1] sage: gale_ryser_theorem(p1, p2) [1 1 1 1] [1 1 0 0] [1 1 0 0] sage: p1 = [4,2,2,0] sage: p2 = [3,3,1,1,0,0] sage: gale_ryser_theorem(p1, p2) [1 1 1 1 0 0] [1 1 0 0 0 0] [1 1 0 0 0 0] [0 0 0 0 0 0] sage: p1 = [3,3,2,1] sage: p2 = [3,2,2,1,1] sage: print gale_ryser_theorem(p1, p2, algorithm="gale") # Optional - requires GLPK or CBC [1 0 1 1 0] [1 0 1 0 1] [1 1 0 0 0] [0 1 0 0 0] With `0` in the sequences, and with unordered inputs :: sage: from sage.combinat.integer_vector import gale_ryser_theorem sage: gale_ryser_theorem([3,3,0,1,1,0], [3,1,3,1,0]) [1 1 1 0 0] [1 0 1 1 0] [0 0 0 0 0] [1 0 0 0 0] [0 0 1 0 0] [0 0 0 0 0] REFERENCES: .. [Ryser63] H. J. Ryser, Combinatorial Mathematics, Carus Monographs, MAA, 1963. .. [Gale57] D. Gale, A theorem on flows in networks, Pacific J. Math. 7(1957)1073-1082. """ from sage.combinat.partition import Partition from sage.matrix.constructor import matrix if not(is_gale_ryser(p1,p2)): return False if algorithm=="ryser": # ryser's algorithm from sage.combinat.permutation import Permutation # Sorts the sequences if they are not, and remembers the permutation # applied tmp = sorted(enumerate(p1), reverse=True, key=lambda x:x[1]) r = [x[1] for x in tmp if x[1]>0] r_permutation = [x-1 for x in Permutation([x[0]+1 for x in tmp]).inverse()] m = len(r) tmp = sorted(enumerate(p2), reverse=True, key=lambda x:x[1]) s = [x[1] for x in tmp if x[1]>0] s_permutation = [x-1 for x in Permutation([x[0]+1 for x in tmp]).inverse()] n = len(s) rowsA0 = [[0]*n]*m for j in range(m): if j<m: rowsA0[j] = [1]*r[j]+[0]*(n-r[j]) else: rowsA0[j] = [0]*n A0 = matrix(rowsA0) for j in range(1,n-1): # starts for loop, k = n-1, ..., 1 # which finds the 1st column with # incorrect column sum. For that bad # column index, apply slider again for k in range(1,n): if sum(A0.column(n-k))<>s[n-k]: break A0 = _slider01(A0,s[n-k],n-k) # If we need to add empty rows/columns if len(p1)!=m: A0 = A0.stack(matrix([[0]*n]*(len(p1)-m))) if len(p2)!=n: A0 = A0.transpose().stack(matrix([[0]*len(p1)]*(len(p2)-n))).transpose() # Applying the permutations to get a matrix satisfying the # order given by the input A0 = A0.matrix_from_rows_and_columns(r_permutation, s_permutation) return A0 elif algorithm == "gale": from sage.numerical.mip import MixedIntegerLinearProgram k1, k2=len(p1), len(p2) p = MixedIntegerLinearProgram() b = p.new_variable(dim=2) for (i,c) in enumerate(p1): p.add_constraint(sum([b[i][j] for j in xrange(k2)]),min=c,max=c) for (i,c) in enumerate(p2): p.add_constraint(sum([b[j][i] for j in xrange(k1)]),min=c,max=c) p.set_objective(None) p.set_binary(b) p.solve() b = p.get_values(b) M = [[0]*k2 for i in xrange(k1)] for i in xrange(k1): for j in xrange(k2): M[i][j] = int(b[i][j]) return matrix(M) else: raise ValueError("The only two algorithms available are \"gale\" and \"ryser\"")
cc09b0fb3f408604caeb1f77a7922892fa54ded4 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/cc09b0fb3f408604caeb1f77a7922892fa54ded4/integer_vector.py
- ``p1`` -- the first partition of `n` (trailing 0's allowed) - ``p2`` -- the second partition of `n` (trailing 0's allowed)
- ``p1, p2``-- list of integers representing the vectors of row/column sums
def gale_ryser_theorem(p1, p2, algorithm="ryser"): r""" Returns the binary matrix given by the Gale-Ryser theorem. The Gale Ryser theorem asserts that if `p_1,p_2` are two partitions of `n` of respective lengths `k_1,k_2`, then there is a binary `k_1\times k_2` matrix `M` such that `p_1` is the vector of row sums and `p_2` is the vector of column sums of `M`, if and only if `p_2` dominates `p_1`. INPUT: - ``p1`` -- the first partition of `n` (trailing 0's allowed) - ``p2`` -- the second partition of `n` (trailing 0's allowed) - ``algorithm`` -- two possible string values : - ``"ryser"`` (default) implements the construction due to Ryser [Ryser63]_. - ``"gale"`` implements the construction due to Gale [Gale57]_. OUTPUT: - A binary matrix if it exists, ``None`` otherwise. Gale's Algorithm: (Gale [Gale57]_): A matrix satisfying the constraints of its sums can be defined as the solution of the following Linear Program, which Sage knows how to solve (requires packages GLPK or CBC). .. MATH:: \forall i&\sum_{j=1}^{k_2} b_{i,j}=p_{1,j}\\ \forall i&\sum_{j=1}^{k_1} b_{j,i}=p_{2,j}\\ &b_{i,j}\mbox{ is a binary variable} Ryser's Algorithm: (Ryser [Ryser63]_): The construction of an `m\times n` matrix `A=A_{r,s}`, due to Ryser, is described as follows. The construction works if and only if have `s\preceq r^*`. * Construct the `m\times n` matrix `B` from `r` by defining the `i`-th row of `B` to be the vector whose first `r_i` entries are `1`, and the remainder are 0's, `1\leq i\leq m`. This maximal matrix `B` with row sum `r` and ones left justified has column sum `r^{*}`. * Shift the last `1` in certain rows of `B` to column `n` in order to achieve the sum `s_n`. Call this `B` again. * The `1`'s in column n are to appear in those rows in which `A` has the largest row sums, giving preference to the bottom-most positions in case of ties. * Note: When this step automatically "fixes" other columns, one must skip ahead to the first column index with a wrong sum in the step below. * Proceed inductively to construct columns `n-1`, ..., `2`, `1`. * Set `A = B`. Return `A`. EXAMPLES: Computing the matrix for `p_1=p_2=2+2+1` :: sage: from sage.combinat.integer_vector import gale_ryser_theorem sage: p1 = [2,2,1] sage: p2 = [2,2,1] sage: print gale_ryser_theorem(p1, p2, algorithm="gale") # Optional - requires GLPK or CBC [0 1 1] [1 1 0] [1 0 0] Or for a non-square matrix with `p_1=3+3+2+1` and `p_2=3+2+2+1+1` :: sage: from sage.combinat.integer_vector import gale_ryser_theorem sage: p1 = [3,3,1,1] sage: p2 = [3,3,1,1] sage: gale_ryser_theorem(p1, p2) [1 1 1 0] [1 1 0 1] [1 0 0 0] [0 1 0 0] sage: p1 = [4,2,2] sage: p2 = [3,3,1,1] sage: gale_ryser_theorem(p1, p2) [1 1 1 1] [1 1 0 0] [1 1 0 0] sage: p1 = [4,2,2,0] sage: p2 = [3,3,1,1,0,0] sage: gale_ryser_theorem(p1, p2) [1 1 1 1 0 0] [1 1 0 0 0 0] [1 1 0 0 0 0] [0 0 0 0 0 0] sage: p1 = [3,3,2,1] sage: p2 = [3,2,2,1,1] sage: print gale_ryser_theorem(p1, p2, algorithm="gale") # Optional - requires GLPK or CBC [1 0 1 1 0] [1 0 1 0 1] [1 1 0 0 0] [0 1 0 0 0] With `0` in the sequences, and with unordered inputs :: sage: from sage.combinat.integer_vector import gale_ryser_theorem sage: gale_ryser_theorem([3,3,0,1,1,0], [3,1,3,1,0]) [1 1 1 0 0] [1 0 1 1 0] [0 0 0 0 0] [1 0 0 0 0] [0 0 1 0 0] [0 0 0 0 0] REFERENCES: .. [Ryser63] H. J. Ryser, Combinatorial Mathematics, Carus Monographs, MAA, 1963. .. [Gale57] D. Gale, A theorem on flows in networks, Pacific J. Math. 7(1957)1073-1082. """ from sage.combinat.partition import Partition from sage.matrix.constructor import matrix if not(is_gale_ryser(p1,p2)): return False if algorithm=="ryser": # ryser's algorithm from sage.combinat.permutation import Permutation # Sorts the sequences if they are not, and remembers the permutation # applied tmp = sorted(enumerate(p1), reverse=True, key=lambda x:x[1]) r = [x[1] for x in tmp if x[1]>0] r_permutation = [x-1 for x in Permutation([x[0]+1 for x in tmp]).inverse()] m = len(r) tmp = sorted(enumerate(p2), reverse=True, key=lambda x:x[1]) s = [x[1] for x in tmp if x[1]>0] s_permutation = [x-1 for x in Permutation([x[0]+1 for x in tmp]).inverse()] n = len(s) rowsA0 = [[0]*n]*m for j in range(m): if j<m: rowsA0[j] = [1]*r[j]+[0]*(n-r[j]) else: rowsA0[j] = [0]*n A0 = matrix(rowsA0) for j in range(1,n-1): # starts for loop, k = n-1, ..., 1 # which finds the 1st column with # incorrect column sum. For that bad # column index, apply slider again for k in range(1,n): if sum(A0.column(n-k))<>s[n-k]: break A0 = _slider01(A0,s[n-k],n-k) # If we need to add empty rows/columns if len(p1)!=m: A0 = A0.stack(matrix([[0]*n]*(len(p1)-m))) if len(p2)!=n: A0 = A0.transpose().stack(matrix([[0]*len(p1)]*(len(p2)-n))).transpose() # Applying the permutations to get a matrix satisfying the # order given by the input A0 = A0.matrix_from_rows_and_columns(r_permutation, s_permutation) return A0 elif algorithm == "gale": from sage.numerical.mip import MixedIntegerLinearProgram k1, k2=len(p1), len(p2) p = MixedIntegerLinearProgram() b = p.new_variable(dim=2) for (i,c) in enumerate(p1): p.add_constraint(sum([b[i][j] for j in xrange(k2)]),min=c,max=c) for (i,c) in enumerate(p2): p.add_constraint(sum([b[j][i] for j in xrange(k1)]),min=c,max=c) p.set_objective(None) p.set_binary(b) p.solve() b = p.get_values(b) M = [[0]*k2 for i in xrange(k1)] for i in xrange(k1): for j in xrange(k2): M[i][j] = int(b[i][j]) return matrix(M) else: raise ValueError("The only two algorithms available are \"gale\" and \"ryser\"")
cc09b0fb3f408604caeb1f77a7922892fa54ded4 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/cc09b0fb3f408604caeb1f77a7922892fa54ded4/integer_vector.py
"""
r"""
def selmer_group(self, S, m, proof=True): """ Compute the Selmer group `K(S,m)`, which is defined to be the subgroup of `K^\times/(K^\times)^m` consisting of elements `a` such that `K(\sqrt[m]{a})/K` is unramified at all primes of `K` lying above a place outside of `S`.
5d98cd9b58ad8f7017f5282eda58958e195331b7 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/5d98cd9b58ad8f7017f5282eda58958e195331b7/number_field.py
sage: P1 in G
sage: P1 in G
def _call_(self, x): r""" TEST::
0bd99622f910c5a456ea17a7a8b3975be000dabb /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/0bd99622f910c5a456ea17a7a8b3975be000dabb/additive_abelian_wrapper.py
return u[0]
return u[0].vector()
def _discrete_log(self,x): # EVEN DUMBER IMPLEMENTATION! u = [y for y in self.list() if y.element() == x] if len(u) == 0: raise TypeError, "Not in group" if len(u) > 1: raise NotImplementedError return u[0]
0bd99622f910c5a456ea17a7a8b3975be000dabb /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/0bd99622f910c5a456ea17a7a8b3975be000dabb/additive_abelian_wrapper.py
p.add_constraint(v[x] + b[x][y] - v[y], min=0, max=0)
p.add_constraint(v[x] + b[x][y] - v[y], min=0)
def edge_cut(self, s, t, value_only=True, use_edge_labels=False, vertices=False, solver=None, verbose=0): r""" Returns a minimum edge cut between vertices `s` and `t` represented by a list of edges.
e54fd0c7a4489bf943b961b01f9db55f6922f699 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/e54fd0c7a4489bf943b961b01f9db55f6922f699/generic_graph.py
-95 -1 -2
-95 -1 -2
def _sage_(self, R=None): """ Coerces self to Sage.
c65378511e7fe1a936f41572269504b0ee5226b9 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/c65378511e7fe1a936f41572269504b0ee5226b9/singular.py
(\$) by a dollar sign ($). Don't change a dollar sign preceded or followed by a backtick (`$ or $`), because of strings like
(\\$) by a dollar sign ($). Don't change a dollar sign preceded or followed by a backtick (\`$ or \$`), because of strings like
def process_dollars(s): r"""nodetex Replace dollar signs with backticks. More precisely, do a regular expression search. Replace a plain dollar sign ($) by a backtick (`). Replace an escaped dollar sign (\$) by a dollar sign ($). Don't change a dollar sign preceded or followed by a backtick (`$ or $`), because of strings like "``$HOME``". Don't make any changes on lines starting with more spaces than the first nonempty line in ``s``, because those are indented and hence part of a block of code or examples. This also doesn't replaces dollar signs enclosed in curly braces, to avoid nested math environments. EXAMPLES:: sage: from sage.misc.sagedoc import process_dollars sage: process_dollars('hello') 'hello' sage: process_dollars('some math: $x=y$') 'some math: `x=y`' Replace \$ with $, and don't do anything when backticks are involved:: sage: process_dollars(r'a ``$REAL`` dollar sign: \$') 'a ``$REAL`` dollar sign: $' Don't make any changes on lines indented more than the first nonempty line:: sage: s = '\n first line\n indented $x=y$' sage: s == process_dollars(s) True Don't replace dollar signs enclosed in curly braces:: sage: process_dollars(r'f(n) = 0 \text{ if $n$ is prime}') 'f(n) = 0 \\text{ if $n$ is prime}' This is not perfect: sage: process_dollars(r'$f(n) = 0 \text{ if $n$ is prime}$') '`f(n) = 0 \\text{ if $n$ is prime}$' The regular expression search doesn't find the last $. Fortunately, there don't seem to be any instances of this kind of expression in the Sage library, as of this writing. """ if s.find("$") == -1: return s # find how much leading whitespace s has, for later comparison: # ignore all $ on lines which start with more whitespace. whitespace = re.match(r'\s*\S', s.lstrip('\n')) whitespace = ' ' * (whitespace.end() - 1) # leading whitespace # Indices will be a list of pairs of positions in s, to search between. # If the following search has no matches, then indices will be (0, len(s)). indices = [0] # This searches for "$blah$" inside a pair of curly braces -- # don't change these, since they're probably coming from a nested # math environment. So for each match, search to the left of its # start and to the right of its end, but not in between. for m in re.finditer(r"{[^{}$]*\$([^{}$]*)\$[^{}$]*}", s): indices[-1] = (indices[-1], m.start()) indices.append(m.end()) indices[-1] = (indices[-1], len(s)) # regular expression for $ (not \$, `$, $`, and only on a line # with no extra leading whitespace). # # in detail: # re.compile("^" # beginning of line # + "(%s%)?" % whitespace # + r"""(\S # non whitespace # .*?)? # non-greedy match any non-newline characters # (?<!`|\\)\$(?!`) # $ with negative lookbehind and lookahead # """, re.M | re.X) # # except that this doesn't work, so use the equivalent regular # expression without the 're.X' option. Maybe 'whitespace' gets # eaten up by re.X? regexp = "^" + "(%s)?"%whitespace + r"(\S.*?)?(?<!`|\\)\$(?!`)" dollar = re.compile(regexp, re.M) # regular expression for \$ slashdollar = re.compile(r"\\\$") for start, end in indices: while dollar.search(s, start, end): m = dollar.search(s, start, end) s = s[:m.end()-1] + "`" + s[m.end():] while slashdollar.search(s, start, end): m = slashdollar.search(s, start, end) s = s[:m.start()] + "$" + s[m.end():] return s
645ba13928c1b03876b1efd1df87a08b25f28314 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/645ba13928c1b03876b1efd1df87a08b25f28314/sagedoc.py
Replace \$ with $, and don't do anything when backticks are involved::
Replace \\$ with $, and don't do anything when backticks are involved::
def process_dollars(s): r"""nodetex Replace dollar signs with backticks. More precisely, do a regular expression search. Replace a plain dollar sign ($) by a backtick (`). Replace an escaped dollar sign (\$) by a dollar sign ($). Don't change a dollar sign preceded or followed by a backtick (`$ or $`), because of strings like "``$HOME``". Don't make any changes on lines starting with more spaces than the first nonempty line in ``s``, because those are indented and hence part of a block of code or examples. This also doesn't replaces dollar signs enclosed in curly braces, to avoid nested math environments. EXAMPLES:: sage: from sage.misc.sagedoc import process_dollars sage: process_dollars('hello') 'hello' sage: process_dollars('some math: $x=y$') 'some math: `x=y`' Replace \$ with $, and don't do anything when backticks are involved:: sage: process_dollars(r'a ``$REAL`` dollar sign: \$') 'a ``$REAL`` dollar sign: $' Don't make any changes on lines indented more than the first nonempty line:: sage: s = '\n first line\n indented $x=y$' sage: s == process_dollars(s) True Don't replace dollar signs enclosed in curly braces:: sage: process_dollars(r'f(n) = 0 \text{ if $n$ is prime}') 'f(n) = 0 \\text{ if $n$ is prime}' This is not perfect: sage: process_dollars(r'$f(n) = 0 \text{ if $n$ is prime}$') '`f(n) = 0 \\text{ if $n$ is prime}$' The regular expression search doesn't find the last $. Fortunately, there don't seem to be any instances of this kind of expression in the Sage library, as of this writing. """ if s.find("$") == -1: return s # find how much leading whitespace s has, for later comparison: # ignore all $ on lines which start with more whitespace. whitespace = re.match(r'\s*\S', s.lstrip('\n')) whitespace = ' ' * (whitespace.end() - 1) # leading whitespace # Indices will be a list of pairs of positions in s, to search between. # If the following search has no matches, then indices will be (0, len(s)). indices = [0] # This searches for "$blah$" inside a pair of curly braces -- # don't change these, since they're probably coming from a nested # math environment. So for each match, search to the left of its # start and to the right of its end, but not in between. for m in re.finditer(r"{[^{}$]*\$([^{}$]*)\$[^{}$]*}", s): indices[-1] = (indices[-1], m.start()) indices.append(m.end()) indices[-1] = (indices[-1], len(s)) # regular expression for $ (not \$, `$, $`, and only on a line # with no extra leading whitespace). # # in detail: # re.compile("^" # beginning of line # + "(%s%)?" % whitespace # + r"""(\S # non whitespace # .*?)? # non-greedy match any non-newline characters # (?<!`|\\)\$(?!`) # $ with negative lookbehind and lookahead # """, re.M | re.X) # # except that this doesn't work, so use the equivalent regular # expression without the 're.X' option. Maybe 'whitespace' gets # eaten up by re.X? regexp = "^" + "(%s)?"%whitespace + r"(\S.*?)?(?<!`|\\)\$(?!`)" dollar = re.compile(regexp, re.M) # regular expression for \$ slashdollar = re.compile(r"\\\$") for start, end in indices: while dollar.search(s, start, end): m = dollar.search(s, start, end) s = s[:m.end()-1] + "`" + s[m.end():] while slashdollar.search(s, start, end): m = slashdollar.search(s, start, end) s = s[:m.start()] + "$" + s[m.end():] return s
645ba13928c1b03876b1efd1df87a08b25f28314 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/645ba13928c1b03876b1efd1df87a08b25f28314/sagedoc.py
This is not perfect:
This is not perfect::
def process_dollars(s): r"""nodetex Replace dollar signs with backticks. More precisely, do a regular expression search. Replace a plain dollar sign ($) by a backtick (`). Replace an escaped dollar sign (\$) by a dollar sign ($). Don't change a dollar sign preceded or followed by a backtick (`$ or $`), because of strings like "``$HOME``". Don't make any changes on lines starting with more spaces than the first nonempty line in ``s``, because those are indented and hence part of a block of code or examples. This also doesn't replaces dollar signs enclosed in curly braces, to avoid nested math environments. EXAMPLES:: sage: from sage.misc.sagedoc import process_dollars sage: process_dollars('hello') 'hello' sage: process_dollars('some math: $x=y$') 'some math: `x=y`' Replace \$ with $, and don't do anything when backticks are involved:: sage: process_dollars(r'a ``$REAL`` dollar sign: \$') 'a ``$REAL`` dollar sign: $' Don't make any changes on lines indented more than the first nonempty line:: sage: s = '\n first line\n indented $x=y$' sage: s == process_dollars(s) True Don't replace dollar signs enclosed in curly braces:: sage: process_dollars(r'f(n) = 0 \text{ if $n$ is prime}') 'f(n) = 0 \\text{ if $n$ is prime}' This is not perfect: sage: process_dollars(r'$f(n) = 0 \text{ if $n$ is prime}$') '`f(n) = 0 \\text{ if $n$ is prime}$' The regular expression search doesn't find the last $. Fortunately, there don't seem to be any instances of this kind of expression in the Sage library, as of this writing. """ if s.find("$") == -1: return s # find how much leading whitespace s has, for later comparison: # ignore all $ on lines which start with more whitespace. whitespace = re.match(r'\s*\S', s.lstrip('\n')) whitespace = ' ' * (whitespace.end() - 1) # leading whitespace # Indices will be a list of pairs of positions in s, to search between. # If the following search has no matches, then indices will be (0, len(s)). indices = [0] # This searches for "$blah$" inside a pair of curly braces -- # don't change these, since they're probably coming from a nested # math environment. So for each match, search to the left of its # start and to the right of its end, but not in between. for m in re.finditer(r"{[^{}$]*\$([^{}$]*)\$[^{}$]*}", s): indices[-1] = (indices[-1], m.start()) indices.append(m.end()) indices[-1] = (indices[-1], len(s)) # regular expression for $ (not \$, `$, $`, and only on a line # with no extra leading whitespace). # # in detail: # re.compile("^" # beginning of line # + "(%s%)?" % whitespace # + r"""(\S # non whitespace # .*?)? # non-greedy match any non-newline characters # (?<!`|\\)\$(?!`) # $ with negative lookbehind and lookahead # """, re.M | re.X) # # except that this doesn't work, so use the equivalent regular # expression without the 're.X' option. Maybe 'whitespace' gets # eaten up by re.X? regexp = "^" + "(%s)?"%whitespace + r"(\S.*?)?(?<!`|\\)\$(?!`)" dollar = re.compile(regexp, re.M) # regular expression for \$ slashdollar = re.compile(r"\\\$") for start, end in indices: while dollar.search(s, start, end): m = dollar.search(s, start, end) s = s[:m.end()-1] + "`" + s[m.end():] while slashdollar.search(s, start, end): m = slashdollar.search(s, start, end) s = s[:m.start()] + "$" + s[m.end():] return s
645ba13928c1b03876b1efd1df87a08b25f28314 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/645ba13928c1b03876b1efd1df87a08b25f28314/sagedoc.py
Replace \mathtt{BLAH} with either \verb|BLAH| (in the notebook) or
Replace \\mathtt{BLAH} with either \\verb|BLAH| (in the notebook) or
def process_mathtt(s, embedded=False): r"""nodetex Replace \mathtt{BLAH} with either \verb|BLAH| (in the notebook) or BLAH (from the command line). INPUT: - ``s`` - string, in practice a docstring - ``embedded`` - boolean (optional, default False) This function is called by :func:`format`, and if in the notebook, it sets ``embedded`` to be ``True``, otherwise ``False``. EXAMPLES:: sage: from sage.misc.sagedoc import process_mathtt sage: process_mathtt(r'e^\mathtt{self}') 'e^self' sage: process_mathtt(r'e^\mathtt{self}', embedded=True) 'e^{\\verb|self|}' """ replaced = False while True: start = s.find("\\mathtt{") end = s.find("}", start) if start == -1 or end == -1: break if embedded: left = "{\\verb|" right = "|}" else: left = "" right = "" s = s[:start] + left + s[start+8:end] + right + s[end+1:] return s
645ba13928c1b03876b1efd1df87a08b25f28314 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/645ba13928c1b03876b1efd1df87a08b25f28314/sagedoc.py
- ``category`` - a category; reserved for future use - ``skip`` - a string or list (or iterable) of strings
- ``category`` - a category; reserved for future use - ``skip`` - a string or list (or iterable) of strings
def run(self, category = None, skip = [], catch = True, raise_on_failure = False, **options): """ Run all the tests from this test suite:
b2b6998afb309d52df6e83bf3b9b672c2c6a0e8f /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/b2b6998afb309d52df6e83bf3b9b672c2c6a0e8f/sage_unittest.py
- ``catch` - a boolean (default: True)
- ``catch`` - a boolean (default: True)
def run(self, category = None, skip = [], catch = True, raise_on_failure = False, **options): """ Run all the tests from this test suite:
b2b6998afb309d52df6e83bf3b9b672c2c6a0e8f /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/b2b6998afb309d52df6e83bf3b9b672c2c6a0e8f/sage_unittest.py
sage: ZZ._tester() Testing utilities for Integer Ring
sage: QQ._tester() Testing utilities for Rational Field
def instance_tester(instance, tester = None, **options): """ Returns a gadget attached to ``instance`` providing testing utilities. EXAMPLES:: sage: from sage.misc.sage_unittest import instance_tester sage: tester = instance_tester(ZZ) sage: tester.assert_(1 == 1) sage: tester.assert_(1 == 0) Traceback (most recent call last): ... AssertionError sage: tester.assert_(1 == 0, "this is expected to fail") Traceback (most recent call last): ... AssertionError: this is expected to fail sage: tester.assertEquals(1, 1) sage: tester.assertEquals(1, 0) Traceback (most recent call last): ... AssertionError: 1 != 0 The available assertion testing facilities are the same as in :class:`unittest.TestCase`, which see (actually, by a slight abuse, tester is currently an instance of this class). TESTS:: sage: instance_tester(ZZ, tester = tester) is tester True """ if tester is None: return InstanceTester(instance, **options) else: assert len(options) == 0 assert tester._instance is instance return tester
b2b6998afb309d52df6e83bf3b9b672c2c6a0e8f /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/b2b6998afb309d52df6e83bf3b9b672c2c6a0e8f/sage_unittest.py
sage: ZZ._tester() Testing utilities for Integer Ring
sage: QQ._tester() Testing utilities for Rational Field
def __init__(self, instance, elements = None, verbose = False, prefix = "", **options): """ A gadget attached to an instance providing it with testing utilities.
b2b6998afb309d52df6e83bf3b9b672c2c6a0e8f /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/b2b6998afb309d52df6e83bf3b9b672c2c6a0e8f/sage_unittest.py
sage: m = matrix(3, lambda i,j: i-j)
sage: m = matrix(3, lambda i,j: i-j); m
def matrix(*args, **kwds): """ Create a matrix. INPUT: The matrix command takes the entries of a matrix, optionally preceded by a ring and the dimensions of the matrix, and returns a matrix. The entries of a matrix can be specified as a flat list of elements, a list of lists (i.e., a list of rows), a list of Sage vectors, a callable object, or a dictionary having positions as keys and matrix entries as values (see the examples). If you pass in a callable object, then you must specify the number of rows and columns. You can create a matrix of zeros by passing an empty list or the integer zero for the entries. To construct a multiple of the identity (`cI`), you can specify square dimensions and pass in `c`. Calling matrix() with a Sage object may return something that makes sense. Calling matrix() with a NumPy array will convert the array to a matrix. The ring, number of rows, and number of columns of the matrix can be specified by setting the ring, nrows, or ncols parameters or by passing them as the first arguments to the function in the order ring, nrows, ncols. The ring defaults to ZZ if it is not specified or cannot be determined from the entries. If the numbers of rows and columns are not specified and cannot be determined, then an empty 0x0 matrix is returned. - ``ring`` - the base ring for the entries of the matrix. - ``nrows`` - the number of rows in the matrix. - ``ncols`` - the number of columns in the matrix. - ``sparse`` - create a sparse matrix. This defaults to True when the entries are given as a dictionary, otherwise defaults to False. OUTPUT: a matrix EXAMPLES:: sage: m=matrix(2); m; m.parent() [0 0] [0 0] Full MatrixSpace of 2 by 2 dense matrices over Integer Ring :: sage: m=matrix(2,3); m; m.parent() [0 0 0] [0 0 0] Full MatrixSpace of 2 by 3 dense matrices over Integer Ring :: sage: m=matrix(QQ,[[1,2,3],[4,5,6]]); m; m.parent() [1 2 3] [4 5 6] Full MatrixSpace of 2 by 3 dense matrices over Rational Field :: sage: m = matrix(QQ, 3, 3, lambda i, j: i+j); m [0 1 2] [1 2 3] [2 3 4] sage: m = matrix(3, lambda i,j: i-j) [ 0 -1 -2] [ 1 0 -1] [ 2 1 0] :: sage: v1=vector((1,2,3)) sage: v2=vector((4,5,6)) sage: m=matrix([v1,v2]); m; m.parent() [1 2 3] [4 5 6] Full MatrixSpace of 2 by 3 dense matrices over Integer Ring :: sage: m=matrix(QQ,2,[1,2,3,4,5,6]); m; m.parent() [1 2 3] [4 5 6] Full MatrixSpace of 2 by 3 dense matrices over Rational Field :: sage: m=matrix(QQ,2,3,[1,2,3,4,5,6]); m; m.parent() [1 2 3] [4 5 6] Full MatrixSpace of 2 by 3 dense matrices over Rational Field :: sage: m=matrix({(0,1): 2, (1,1):2/5}); m; m.parent() [ 0 2] [ 0 2/5] Full MatrixSpace of 2 by 2 sparse matrices over Rational Field :: sage: m=matrix(QQ,2,3,{(1,1): 2}); m; m.parent() [0 0 0] [0 2 0] Full MatrixSpace of 2 by 3 sparse matrices over Rational Field :: sage: import numpy sage: n=numpy.array([[1,2],[3,4]],float) sage: m=matrix(n); m; m.parent() [1.0 2.0] [3.0 4.0] Full MatrixSpace of 2 by 2 dense matrices over Real Double Field :: sage: v = vector(ZZ, [1, 10, 100]) sage: m=matrix(v); m; m.parent() [ 1 10 100] Full MatrixSpace of 1 by 3 dense matrices over Integer Ring sage: m=matrix(GF(7), v); m; m.parent() [1 3 2] Full MatrixSpace of 1 by 3 dense matrices over Finite Field of size 7 :: sage: g = graphs.PetersenGraph() sage: m = matrix(g); m; m.parent() [0 1 0 0 1 1 0 0 0 0] [1 0 1 0 0 0 1 0 0 0] [0 1 0 1 0 0 0 1 0 0] [0 0 1 0 1 0 0 0 1 0] [1 0 0 1 0 0 0 0 0 1] [1 0 0 0 0 0 0 1 1 0] [0 1 0 0 0 0 0 0 1 1] [0 0 1 0 0 1 0 0 0 1] [0 0 0 1 0 1 1 0 0 0] [0 0 0 0 1 0 1 1 0 0] Full MatrixSpace of 10 by 10 dense matrices over Integer Ring :: sage: matrix(ZZ, 10, 10, range(100), sparse=True).parent() Full MatrixSpace of 10 by 10 sparse matrices over Integer Ring :: sage: R = PolynomialRing(QQ, 9, 'x') sage: A = matrix(R, 3, 3, R.gens()); A [x0 x1 x2] [x3 x4 x5] [x6 x7 x8] sage: det(A) -x2*x4*x6 + x1*x5*x6 + x2*x3*x7 - x0*x5*x7 - x1*x3*x8 + x0*x4*x8 TESTS:: sage: m=matrix(); m; m.parent() [] Full MatrixSpace of 0 by 0 dense matrices over Integer Ring sage: m=matrix(QQ); m; m.parent() [] Full MatrixSpace of 0 by 0 dense matrices over Rational Field sage: m=matrix(QQ,2); m; m.parent() [0 0] [0 0] Full MatrixSpace of 2 by 2 dense matrices over Rational Field sage: m=matrix(QQ,2,3); m; m.parent() [0 0 0] [0 0 0] Full MatrixSpace of 2 by 3 dense matrices over Rational Field sage: m=matrix([]); m; m.parent() [] Full MatrixSpace of 0 by 0 dense matrices over Integer Ring sage: m=matrix(QQ,[]); m; m.parent() [] Full MatrixSpace of 0 by 0 dense matrices over Rational Field sage: m=matrix(2,2,1); m; m.parent() [1 0] [0 1] Full MatrixSpace of 2 by 2 dense matrices over Integer Ring sage: m=matrix(QQ,2,2,1); m; m.parent() [1 0] [0 1] Full MatrixSpace of 2 by 2 dense matrices over Rational Field sage: m=matrix(2,3,0); m; m.parent() [0 0 0] [0 0 0] Full MatrixSpace of 2 by 3 dense matrices over Integer Ring sage: m=matrix(QQ,2,3,0); m; m.parent() [0 0 0] [0 0 0] Full MatrixSpace of 2 by 3 dense matrices over Rational Field sage: m=matrix([[1,2,3],[4,5,6]]); m; m.parent() [1 2 3] [4 5 6] Full MatrixSpace of 2 by 3 dense matrices over Integer Ring sage: m=matrix(QQ,2,[[1,2,3],[4,5,6]]); m; m.parent() [1 2 3] [4 5 6] Full MatrixSpace of 2 by 3 dense matrices over Rational Field sage: m=matrix(QQ,3,[[1,2,3],[4,5,6]]); m; m.parent() Traceback (most recent call last): ... ValueError: Number of rows does not match up with specified number. sage: m=matrix(QQ,2,3,[[1,2,3],[4,5,6]]); m; m.parent() [1 2 3] [4 5 6] Full MatrixSpace of 2 by 3 dense matrices over Rational Field sage: m=matrix(QQ,2,4,[[1,2,3],[4,5,6]]); m; m.parent() Traceback (most recent call last): ... ValueError: Number of columns does not match up with specified number. sage: m=matrix([(1,2,3),(4,5,6)]); m; m.parent() [1 2 3] [4 5 6] Full MatrixSpace of 2 by 3 dense matrices over Integer Ring sage: m=matrix([1,2,3,4,5,6]); m; m.parent() [1 2 3 4 5 6] Full MatrixSpace of 1 by 6 dense matrices over Integer Ring sage: m=matrix((1,2,3,4,5,6)); m; m.parent() [1 2 3 4 5 6] Full MatrixSpace of 1 by 6 dense matrices over Integer Ring sage: m=matrix(QQ,[1,2,3,4,5,6]); m; m.parent() [1 2 3 4 5 6] Full MatrixSpace of 1 by 6 dense matrices over Rational Field sage: m=matrix(QQ,3,2,[1,2,3,4,5,6]); m; m.parent() [1 2] [3 4] [5 6] Full MatrixSpace of 3 by 2 dense matrices over Rational Field sage: m=matrix(QQ,2,4,[1,2,3,4,5,6]); m; m.parent() Traceback (most recent call last): ... ValueError: entries has the wrong length sage: m=matrix(QQ,5,[1,2,3,4,5,6]); m; m.parent() Traceback (most recent call last): ... TypeError: entries has the wrong length sage: m=matrix({(1,1): 2}); m; m.parent() [0 0] [0 2] Full MatrixSpace of 2 by 2 sparse matrices over Integer Ring sage: m=matrix(QQ,{(1,1): 2}); m; m.parent() [0 0] [0 2] Full MatrixSpace of 2 by 2 sparse matrices over Rational Field sage: m=matrix(QQ,3,{(1,1): 2}); m; m.parent() [0 0 0] [0 2 0] [0 0 0] Full MatrixSpace of 3 by 3 sparse matrices over Rational Field sage: m=matrix(QQ,3,4,{(1,1): 2}); m; m.parent() [0 0 0 0] [0 2 0 0] [0 0 0 0] Full MatrixSpace of 3 by 4 sparse matrices over Rational Field sage: m=matrix(QQ,2,{(1,1): 2}); m; m.parent() [0 0] [0 2] Full MatrixSpace of 2 by 2 sparse matrices over Rational Field sage: m=matrix(QQ,1,{(1,1): 2}); m; m.parent() Traceback (most recent call last): ... IndexError: invalid entries list sage: m=matrix({}); m; m.parent() [] Full MatrixSpace of 0 by 0 sparse matrices over Integer Ring sage: m=matrix(QQ,{}); m; m.parent() [] Full MatrixSpace of 0 by 0 sparse matrices over Rational Field sage: m=matrix(QQ,2,{}); m; m.parent() [0 0] [0 0] Full MatrixSpace of 2 by 2 sparse matrices over Rational Field sage: m=matrix(QQ,2,3,{}); m; m.parent() [0 0 0] [0 0 0] Full MatrixSpace of 2 by 3 sparse matrices over Rational Field sage: m=matrix(2,{}); m; m.parent() [0 0] [0 0] Full MatrixSpace of 2 by 2 sparse matrices over Integer Ring sage: m=matrix(2,3,{}); m; m.parent() [0 0 0] [0 0 0] Full MatrixSpace of 2 by 3 sparse matrices over Integer Ring sage: m=matrix(0); m; m.parent() [] Full MatrixSpace of 0 by 0 dense matrices over Integer Ring sage: m=matrix(0,2); m; m.parent() [] Full MatrixSpace of 0 by 2 dense matrices over Integer Ring sage: m=matrix(2,0); m; m.parent() [] Full MatrixSpace of 2 by 0 dense matrices over Integer Ring sage: m=matrix(0,[1]); m; m.parent() Traceback (most recent call last): ... ValueError: entries has the wrong length sage: m=matrix(1,0,[]); m; m.parent() [] Full MatrixSpace of 1 by 0 dense matrices over Integer Ring sage: m=matrix(0,1,[]); m; m.parent() [] Full MatrixSpace of 0 by 1 dense matrices over Integer Ring sage: m=matrix(0,[]); m; m.parent() [] Full MatrixSpace of 0 by 0 dense matrices over Integer Ring sage: m=matrix(0,{}); m; m.parent() [] Full MatrixSpace of 0 by 0 sparse matrices over Integer Ring sage: m=matrix(0,{(1,1):2}); m; m.parent() Traceback (most recent call last): ... IndexError: invalid entries list sage: m=matrix(2,0,{(1,1):2}); m; m.parent() Traceback (most recent call last): ... IndexError: invalid entries list sage: import numpy sage: n=numpy.array([[numpy.complex(0,1),numpy.complex(0,2)],[3,4]],complex) sage: m=matrix(n); m; m.parent() [1.0*I 2.0*I] [ 3.0 4.0] Full MatrixSpace of 2 by 2 dense matrices over Complex Double Field sage: n=numpy.array([[1,2],[3,4]],'int32') sage: m=matrix(n); m; m.parent() [1 2] [3 4] Full MatrixSpace of 2 by 2 dense matrices over Integer Ring sage: n = numpy.array([[1,2,3],[4,5,6],[7,8,9]],'float32') sage: m=matrix(n); m; m.parent() [1.0 2.0 3.0] [4.0 5.0 6.0] [7.0 8.0 9.0] Full MatrixSpace of 3 by 3 dense matrices over Real Double Field sage: n=numpy.array([[1,2,3],[4,5,6],[7,8,9]],'float64') sage: m=matrix(n); m; m.parent() [1.0 2.0 3.0] [4.0 5.0 6.0] [7.0 8.0 9.0] Full MatrixSpace of 3 by 3 dense matrices over Real Double Field sage: n=numpy.array([[1,2,3],[4,5,6],[7,8,9]],'complex64') sage: m=matrix(n); m; m.parent() [1.0 2.0 3.0] [4.0 5.0 6.0] [7.0 8.0 9.0] Full MatrixSpace of 3 by 3 dense matrices over Complex Double Field sage: n=numpy.array([[1,2,3],[4,5,6],[7,8,9]],'complex128') sage: m=matrix(n); m; m.parent() [1.0 2.0 3.0] [4.0 5.0 6.0] [7.0 8.0 9.0] Full MatrixSpace of 3 by 3 dense matrices over Complex Double Field sage: a = matrix([[1,2],[3,4]]) sage: b = matrix(a.numpy()); b [1 2] [3 4] sage: a == b True sage: c = matrix(a.numpy('float32')); c [1.0 2.0] [3.0 4.0] sage: matrix(numpy.array([[5]])) [5] sage: v = vector(ZZ, [1, 10, 100]) sage: m=matrix(ZZ['x'], v); m; m.parent() [ 1 10 100] Full MatrixSpace of 1 by 3 dense matrices over Univariate Polynomial Ring in x over Integer Ring sage: matrix(ZZ, 10, 10, range(100)).parent() Full MatrixSpace of 10 by 10 dense matrices over Integer Ring sage: m = matrix(GF(7), [[1/3,2/3,1/2], [3/4,4/5,7]]); m; m.parent() [5 3 4] [6 5 0] Full MatrixSpace of 2 by 3 dense matrices over Finite Field of size 7 sage: m = matrix([[1,2,3], [RDF(2), CDF(1,2), 3]]); m; m.parent() [ 1.0 2.0 3.0] [ 2.0 1.0 + 2.0*I 3.0] Full MatrixSpace of 2 by 3 dense matrices over Complex Double Field sage: m=matrix(3,3,1/2); m; m.parent() [1/2 0 0] [ 0 1/2 0] [ 0 0 1/2] Full MatrixSpace of 3 by 3 dense matrices over Rational Field sage: matrix([[1],[2,3]]) Traceback (most recent call last): ... ValueError: List of rows is not valid (rows are wrong types or lengths) sage: matrix([[1],2]) Traceback (most recent call last): ... ValueError: List of rows is not valid (rows are wrong types or lengths) sage: matrix(vector(RR,[1,2,3])).parent() Full MatrixSpace of 1 by 3 dense matrices over Real Field with 53 bits of precision AUTHORS: - ??: Initial implementation - Jason Grout (2008-03): almost a complete rewrite, with bits and pieces from the original implementation """ args = list(args) sparse = kwds.get('sparse',False) # if the first object already knows how to make itself into a # matrix, try that, defaulting to a matrix over the integers. if len(args) == 1 and hasattr(args[0], '_matrix_'): try: return args[0]._matrix_(sparse=sparse) except TypeError: return args[0]._matrix_() elif len(args) == 2: if hasattr(args[0], '_matrix_'): try: return args[0]._matrix_(args[1], sparse=sparse) except TypeError: return args[0]._matrix_(args[1]) elif hasattr(args[1], '_matrix_'): try: return args[1]._matrix_(args[0], sparse=sparse) except TypeError: return args[1]._matrix_(args[0]) if len(args) == 0: # if nothing was passed return the empty matrix over the # integer ring. return matrix_space.MatrixSpace(rings.ZZ, 0, 0, sparse=sparse)([]) if len(args) >= 1 and rings.is_Ring(args[0]): # A ring is specified if kwds.get('ring', args[0]) != args[0]: raise ValueError, "Specified rings are not the same" else: ring = args[0] args.pop(0) else: ring = kwds.get('ring', None) if len(args) >= 1: # check to see if the number of rows is specified try: import numpy if isinstance(args[0], numpy.ndarray): raise TypeError nrows = int(args[0]) args.pop(0) if kwds.get('nrows', nrows) != nrows: raise ValueError, "Number of rows specified in two places and they are not the same" except TypeError: nrows = kwds.get('nrows', None) else: nrows = kwds.get('nrows', None) if len(args) >= 1: # check to see if additionally, the number of columns is specified try: import numpy if isinstance(args[0], numpy.ndarray): raise TypeError ncols = int(args[0]) args.pop(0) if kwds.get('ncols', ncols) != ncols: raise ValueError, "Number of columns specified in two places and they are not the same" except TypeError: ncols = kwds.get('ncols', None) else: ncols = kwds.get('ncols', None) # Now we've taken care of initial ring, nrows, and ncols arguments. # We've also taken care of the Sage object case. # Now the rest of the arguments are a list of rows, a flat list of # entries, a callable, a dict, a numpy array, or a single value. if len(args) == 0: # If no entries are specified, pass back a zero matrix entries = 0 entry_ring = rings.ZZ elif len(args) == 1: if isinstance(args[0], (types.FunctionType, types.LambdaType, types.MethodType)): if ncols is None and nrows is None: raise ValueError, "When passing in a callable, the dimensions of the matrix must be specified" if ncols is None: ncols = nrows else: nrows = ncols f = args[0] args[0] = [[f(i,j) for j in range(ncols)] for i in range(nrows)] if isinstance(args[0], (list, tuple)): if len(args[0]) == 0: # no entries are specified, pass back the zero matrix entries = 0 entry_ring = rings.ZZ elif isinstance(args[0][0], (list, tuple)) or is_Vector(args[0][0]): # Ensure we have a list of lists, each inner list having the same number of elements first_len = len(args[0][0]) if not all( (isinstance(v, (list, tuple)) or is_Vector(v)) and len(v) == first_len for v in args[0]): raise ValueError, "List of rows is not valid (rows are wrong types or lengths)" # We have a list of rows or vectors if nrows is None: nrows = len(args[0]) elif nrows != len(args[0]): raise ValueError, "Number of rows does not match up with specified number." if ncols is None: ncols = len(args[0][0]) elif ncols != len(args[0][0]): raise ValueError, "Number of columns does not match up with specified number." entries = sum([list(v) for v in args[0]], []) else: # We have a flat list; figure out nrows and ncols if nrows is None: nrows = 1 if nrows > 0: if ncols is None: ncols = len(args[0]) // nrows elif ncols != len(args[0]) // nrows: raise ValueError, "entries has the wrong length" elif len(args[0]) > 0: raise ValueError, "entries has the wrong length" entries = args[0] if nrows > 0 and ncols > 0 and ring is None: entries, ring = prepare(entries) elif isinstance(args[0], dict): # We have a dictionary # default to sparse sparse = kwds.get('sparse', True) if len(args[0]) == 0: # no entries are specified, pass back the zero matrix entries = 0 else: entries, entry_ring = prepare_dict(args[0]) if nrows is None: nrows = nrows_from_dict(entries) ncols = ncols_from_dict(entries) # note that ncols can still be None if nrows is set -- # it will be assigned nrows down below. # See the construction after the numpy case below. else: import numpy if isinstance(args[0], numpy.ndarray): num_array = args[0] str_dtype = str(num_array.dtype) if not( num_array.flags.c_contiguous is True or num_array.flags.f_contiguous is True): raise TypeError('numpy matrix must be either c_contiguous or f_contiguous') if str_dtype.count('float32')==1: m=matrix(RDF,num_array.shape[0],num_array.shape[1],0) m._replace_self_with_numpy32(num_array) elif str_dtype.count('float64')==1: m=matrix(RDF,num_array.shape[0],num_array.shape[1],0) m._replace_self_with_numpy(num_array) elif str_dtype.count('complex64')==1: m=matrix(CDF,num_array.shape[0],num_array.shape[1],0) m._replace_self_with_numpy32(num_array) elif str_dtype.count('complex128')==1: m=matrix(CDF,num_array.shape[0],num_array.shape[1],0) m._replace_self_with_numpy(num_array) elif str_dtype.count('int') == 1: m = matrix(ZZ, [list(row) for row in list(num_array)]) elif str_dtype.count('object') == 1: #Get the raw nested list from the numpy array #and feed it back into matrix try: return matrix( [list(row) for row in list(num_array)]) except TypeError: raise TypeError("cannot convert NumPy matrix to Sage matrix") else: raise TypeError("cannot convert NumPy matrix to Sage matrix") return m elif nrows is not None and ncols is not None: # assume that we should just pass the thing into the # MatrixSpace constructor and hope for the best # This is not documented, but it is doctested if ring is None: entry_ring = args[0].parent() entries = args[0] else: raise ValueError, "Invalid matrix constructor. Type matrix? for help" else: raise ValueError, "Invalid matrix constructor. Type matrix? for help" if nrows is None: nrows = 0 if ncols is None: ncols = nrows if ring is None: try: ring = entry_ring except NameError: ring = rings.ZZ return matrix_space.MatrixSpace(ring, nrows, ncols, sparse=sparse)(entries)
8e568895f17b6ba26e53cc5640add7f2b3281139 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/8e568895f17b6ba26e53cc5640add7f2b3281139/constructor.py
out = copy.deepcopy(_pik.loads(self._check_types)) return out def check_ieee_macros(self, *a, **kw): if self._check_ieee_macros is None: out = check_ieee_macros(*a, **kw) self._check_ieee_macros = _pik.dumps(out)
body.append(" %s;" % func) body.append(" return 0;") body.append("}") body = '\n'.join(body) + "\n" return self.try_link(body, headers, include_dirs, libraries, library_dirs) def check_funcs_once(self, funcs, headers=None, include_dirs=None, libraries=None, library_dirs=None, decl=False, call=False, call_args=None): """Check a list of functions at once. This is useful to speed up things, since all the functions in the funcs list will be put in one compilation unit. Arguments --------- funcs: seq list of functions to test include_dirs : seq list of header paths libraries : seq list of libraries to link the code snippet to libraru_dirs : seq list of library paths decl : dict for every (key, value), the declaration in the value will be used for function in key. If a function is not in the dictionay, no declaration will be used. call : dict for every item (f, value), if the value is True, a call will be done to the function f. """ self._check_compiler() body = [] if decl: for f, v in decl.items(): if v: body.append("int %s (void);" % f) body.append(" for func in funcs: body.append(" body.append(" body.append("int main (void) {") if call: for f in funcs: if f in call and call[f]: if not (call_args and f in call_args and call_args[f]): args = '' else: args = call_args[f] body.append(" %s(%s);" % (f, args)) else: body.append(" %s;" % f)
def check_types(self, *a, **kw): if self._check_types is None: out = check_types(*a, **kw) self._check_types = _pik.dumps(out) else: out = copy.deepcopy(_pik.loads(self._check_types)) return out
37a71c453b67f06646e51013b2c929ce8b65459c /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/37a71c453b67f06646e51013b2c929ce8b65459c/config.py
out = copy.deepcopy(_pik.loads(self._check_ieee_macros)) return out def check_complex(self, *a, **kw): if self._check_complex is None: out = check_complex(*a, **kw) self._check_complex = _pik.dumps(out) else: out = copy.deepcopy(_pik.loads(self._check_complex)) return out PYTHON_HAS_UNICODE_WIDE = True def pythonlib_dir(): """return path where libpython* is.""" if sys.platform == 'win32': return os.path.join(sys.prefix, "libs") else: return get_config_var('LIBDIR') def is_npy_no_signal(): """Return True if the NPY_NO_SIGNAL symbol must be defined in configuration header.""" return sys.platform == 'win32' def is_npy_no_smp(): """Return True if the NPY_NO_SMP symbol must be defined in public header (when SMP support cannot be reliably enabled).""" if sys.version[:5] < '2.4.2': nosmp = 1 else:
for f in funcs: body.append(" %s;" % f) body.append(" return 0;") body.append("}") body = '\n'.join(body) + "\n" return self.try_link(body, headers, include_dirs, libraries, library_dirs) def check_inline(self): """Return the inline keyword recognized by the compiler, empty string otherwise.""" return check_inline(self) def check_compiler_gcc4(self): """Return True if the C compiler is gcc >= 4.""" return check_compiler_gcc4(self) def get_output(self, body, headers=None, include_dirs=None, libraries=None, library_dirs=None, lang="c"): """Try to compile, link to an executable, and run a program built from 'body' and 'headers'. Returns the exit status code of the program and its output. """ warnings.warn("\n+++++++++++++++++++++++++++++++++++++++++++++++++\n" \ "Usage of get_output is deprecated: please do not \n" \ "use it anymore, and avoid configuration checks \n" \ "involving running executable on the target machine.\n" \ "+++++++++++++++++++++++++++++++++++++++++++++++++\n", DeprecationWarning) from distutils.ccompiler import CompileError, LinkError self._check_compiler() exitcode, output = 255, ''
def check_ieee_macros(self, *a, **kw): if self._check_ieee_macros is None: out = check_ieee_macros(*a, **kw) self._check_ieee_macros = _pik.dumps(out) else: out = copy.deepcopy(_pik.loads(self._check_ieee_macros)) return out
37a71c453b67f06646e51013b2c929ce8b65459c /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/37a71c453b67f06646e51013b2c929ce8b65459c/config.py
nosmp = os.environ['NPY_NOSMP'] nosmp = 1 except KeyError: nosmp = 0 return nosmp == 1 def win32_checks(deflist): from numpy.distutils.misc_util import get_build_architecture a = get_build_architecture() print('BUILD_ARCHITECTURE: %r, os.name=%r, sys.platform=%r' % \ (a, os.name, sys.platform)) if a == 'AMD64': deflist.append('DISTUTILS_USE_SDK') if a == "Intel" or a == "AMD64": deflist.append('FORCE_NO_LONG_DOUBLE_FORMATTING') def check_math_capabilities(config, moredefs, mathlibs): def check_func(func_name): return config.check_func(func_name, libraries=mathlibs, decl=True, call=True) def check_funcs_once(funcs_name): decl = dict([(f, True) for f in funcs_name]) st = config.check_funcs_once(funcs_name, libraries=mathlibs, decl=decl, call=decl) if st: moredefs.extend([fname2def(f) for f in funcs_name]) return st def check_funcs(funcs_name): if not check_funcs_once(funcs_name): for f in funcs_name: if check_func(f): moredefs.append(fname2def(f)) return 0 else: return 1 if not check_funcs_once(MANDATORY_FUNCS): raise SystemError("One of the required function to build numpy is not" " available (the list is %s)." % str(MANDATORY_FUNCS)) if sys.version_info[:2] >= (2, 5): for f in OPTIONAL_STDFUNCS_MAYBE: if config.check_decl(fname2def(f), headers=["Python.h", "math.h"]): OPTIONAL_STDFUNCS.remove(f) check_funcs(OPTIONAL_STDFUNCS) check_funcs(C99_FUNCS_SINGLE) check_funcs(C99_FUNCS_EXTENDED) def check_complex(config, mathlibs): priv = [] pub = [] st = config.check_header('complex.h') if st: priv.append('HAVE_COMPLEX_H') pub.append('NPY_USE_C99_COMPLEX') for t in C99_COMPLEX_TYPES: st = config.check_type(t, headers=["complex.h"]) if st: pub.append(('NPY_HAVE_%s' % type2def(t), 1)) def check_prec(prec): flist = [f + prec for f in C99_COMPLEX_FUNCS] decl = dict([(f, True) for f in flist]) if not config.check_funcs_once(flist, call=decl, decl=decl, libraries=mathlibs): for f in flist: if config.check_func(f, call=True, decl=True, libraries=mathlibs): priv.append(fname2def(f))
src, obj, exe = self._link(body, headers, include_dirs, libraries, library_dirs, lang) exe = os.path.join('.', exe) exitstatus, output = exec_command(exe, execute_in='.') if hasattr(os, 'WEXITSTATUS'): exitcode = os.WEXITSTATUS(exitstatus) if os.WIFSIGNALED(exitstatus): sig = os.WTERMSIG(exitstatus) log.error('subprocess exited with signal %d' % (sig,)) if sig == signal.SIGINT: raise KeyboardInterrupt
def is_npy_no_smp(): """Return True if the NPY_NO_SMP symbol must be defined in public header (when SMP support cannot be reliably enabled).""" # Python 2.3 causes a segfault when # trying to re-acquire the thread-state # which is done in error-handling # ufunc code. NPY_ALLOW_C_API and friends # cause the segfault. So, we disable threading # for now. if sys.version[:5] < '2.4.2': nosmp = 1 else: # Perhaps a fancier check is in order here. # so that threads are only enabled if there # are actually multiple CPUS? -- but # threaded code can be nice even on a single # CPU so that long-calculating code doesn't # block. try: nosmp = os.environ['NPY_NOSMP'] nosmp = 1 except KeyError: nosmp = 0 return nosmp == 1
37a71c453b67f06646e51013b2c929ce8b65459c /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/37a71c453b67f06646e51013b2c929ce8b65459c/config.py
priv.extend([fname2def(f) for f in flist]) check_prec('') check_prec('f') check_prec('l') return priv, pub def check_ieee_macros(config): priv = [] pub = [] macros = [] def _add_decl(f): priv.append(fname2def("decl_%s" % f)) pub.append('NPY_%s' % fname2def("decl_%s" % f)) _macros = ["isnan", "isinf", "signbit", "isfinite"] if sys.version_info[:2] >= (2, 6): for f in _macros: py_symbol = fname2def("decl_%s" % f) already_declared = config.check_decl(py_symbol, headers=["Python.h", "math.h"]) if already_declared: if config.check_macro_true(py_symbol, headers=["Python.h", "math.h"]): pub.append('NPY_%s' % fname2def("decl_%s" % f)) else: macros.append(f) else: macros = _macros[:] for f in macros: st = config.check_decl(f, headers = ["Python.h", "math.h"]) if st: _add_decl(f) return priv, pub def check_types(config_cmd, ext, build_dir): private_defines = [] public_defines = [] expected = {} expected['short'] = [2] expected['int'] = [4] expected['long'] = [8, 4] expected['float'] = [4] expected['double'] = [8] expected['long double'] = [8, 12, 16] expected['Py_intptr_t'] = [4, 8] expected['PY_LONG_LONG'] = [8] expected['long long'] = [8] result = config_cmd.check_header('Python.h') if not result: raise SystemError( "Cannot compile 'Python.h'. Perhaps you need to "\ "install python-dev|python-devel.") res = config_cmd.check_header("endian.h") if res: private_defines.append(('HAVE_ENDIAN_H', 1)) public_defines.append(('NPY_HAVE_ENDIAN_H', 1)) for type in ('short', 'int', 'long'): res = config_cmd.check_decl("SIZEOF_%s" % sym2def(type), headers = ["Python.h"]) if res: public_defines.append(('NPY_SIZEOF_%s' % sym2def(type), "SIZEOF_%s" % sym2def(type))) else: res = config_cmd.check_type_size(type, expected=expected[type]) if res >= 0: public_defines.append(('NPY_SIZEOF_%s' % sym2def(type), '%d' % res)) else: raise SystemError("Checking sizeof (%s) failed !" % type) for type in ('float', 'double', 'long double'): already_declared = config_cmd.check_decl("SIZEOF_%s" % sym2def(type), headers = ["Python.h"]) res = config_cmd.check_type_size(type, expected=expected[type]) if res >= 0: public_defines.append(('NPY_SIZEOF_%s' % sym2def(type), '%d' % res)) if not already_declared and not type == 'long double': private_defines.append(('SIZEOF_%s' % sym2def(type), '%d' % res)) else: raise SystemError("Checking sizeof (%s) failed !" % type) complex_def = "struct {%s __x; %s __y;}" % (type, type) res = config_cmd.check_type_size(complex_def, expected=2*expected[type]) if res >= 0: public_defines.append(('NPY_SIZEOF_COMPLEX_%s' % sym2def(type), '%d' % res)) else: raise SystemError("Checking sizeof (%s) failed !" % complex_def) for type in ('Py_intptr_t',): res = config_cmd.check_type_size(type, headers=["Python.h"], library_dirs=[pythonlib_dir()], expected=expected[type]) if res >= 0: private_defines.append(('SIZEOF_%s' % sym2def(type), '%d' % res)) public_defines.append(('NPY_SIZEOF_%s' % sym2def(type), '%d' % res)) else: raise SystemError("Checking sizeof (%s) failed !" % type) if config_cmd.check_decl('PY_LONG_LONG', headers=['Python.h']): res = config_cmd.check_type_size('PY_LONG_LONG', headers=['Python.h'], library_dirs=[pythonlib_dir()], expected=expected['PY_LONG_LONG']) if res >= 0: private_defines.append(('SIZEOF_%s' % sym2def('PY_LONG_LONG'), '%d' % res)) public_defines.append(('NPY_SIZEOF_%s' % sym2def('PY_LONG_LONG'), '%d' % res)) else: raise SystemError("Checking sizeof (%s) failed !" % 'PY_LONG_LONG') res = config_cmd.check_type_size('long long', expected=expected['long long']) if res >= 0: public_defines.append(('NPY_SIZEOF_%s' % sym2def('long long'), '%d' % res)) else: raise SystemError("Checking sizeof (%s) failed !" % 'long long') if not config_cmd.check_decl('CHAR_BIT', headers=['Python.h']): raise RuntimeError( "Config wo CHAR_BIT is not supported"\ ", please contact the maintainers") return private_defines, public_defines def check_mathlib(config_cmd): mathlibs = [] mathlibs_choices = [[],['m'],['cpml']] mathlib = os.environ.get('MATHLIB') if mathlib: mathlibs_choices.insert(0,mathlib.split(',')) for libs in mathlibs_choices: if config_cmd.check_func("exp", libraries=libs, decl=True, call=True): mathlibs = libs break else: raise EnvironmentError("math library missing; rerun " "setup.py after setting the " "MATHLIB env variable") return mathlibs def visibility_define(config): """Return the define value to use for NPY_VISIBILITY_HIDDEN (may be empty string).""" if config.check_compiler_gcc4(): return '__attribute__((visibility("hidden")))' else: return '' def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration,dot_join from numpy.distutils.system_info import get_info, default_lib_dirs config = Configuration('core',parent_package,top_path) local_dir = config.local_path codegen_dir = join(local_dir,'code_generators') if is_released(config): warnings.simplefilter('error', MismatchCAPIWarning) check_api_version(C_API_VERSION, codegen_dir) generate_umath_py = join(codegen_dir,'generate_umath.py') n = dot_join(config.name,'generate_umath') generate_umath = imp.load_module('_'.join(n.split('.')), open(generate_umath_py,'U'),generate_umath_py, ('.py','U',1)) header_dir = 'include/numpy' cocache = CallOnceOnly() def generate_config_h(ext, build_dir): target = join(build_dir,header_dir,'config.h') d = os.path.dirname(target) if not os.path.exists(d): os.makedirs(d) if newer(__file__,target): config_cmd = config.get_config_cmd() log.info('Generating %s',target) moredefs, ignored = cocache.check_types(config_cmd, ext, build_dir) mathlibs = check_mathlib(config_cmd) moredefs.append(('MATHLIB',','.join(mathlibs))) check_math_capabilities(config_cmd, moredefs, mathlibs) moredefs.extend(cocache.check_ieee_macros(config_cmd)[0]) moredefs.extend(cocache.check_complex(config_cmd, mathlibs)[0]) if is_npy_no_signal(): moredefs.append('__NPY_PRIVATE_NO_SIGNAL') if sys.platform=='win32' or os.name=='nt': win32_checks(moredefs) inline = config_cmd.check_inline() if not config_cmd.check_decl('Py_UNICODE_WIDE', headers=['Python.h']): PYTHON_HAS_UNICODE_WIDE = True else: PYTHON_HAS_UNICODE_WIDE = False if ENABLE_SEPARATE_COMPILATION: moredefs.append(('ENABLE_SEPARATE_COMPILATION', 1)) if sys.platform != 'darwin': rep = check_long_double_representation(config_cmd) if rep in ['INTEL_EXTENDED_12_BYTES_LE', 'INTEL_EXTENDED_16_BYTES_LE', 'IEEE_QUAD_LE', 'IEEE_QUAD_BE', 'IEEE_DOUBLE_LE', 'IEEE_DOUBLE_BE', 'DOUBLE_DOUBLE_BE']: moredefs.append(('HAVE_LDOUBLE_%s' % rep, 1)) else: raise ValueError("Unrecognized long double format: %s" % rep) if sys.version_info[0] == 3: moredefs.append(('NPY_PY3K', 1)) target_f = open(target, 'w') for d in moredefs: if isinstance(d,str): target_f.write(' else: target_f.write(' target_f.write(' if inline == 'inline': target_f.write('/* else: target_f.write(' target_f.write(' target_f.write(""" """) target_f.close() print('File:',target) target_f = open(target) print(target_f.read()) target_f.close() print('EOF') else: mathlibs = [] target_f = open(target) for line in target_f.readlines(): s = ' if line.startswith(s): value = line[len(s):].strip() if value: mathlibs.extend(value.split(',')) target_f.close() if hasattr(ext, 'libraries'): ext.libraries.extend(mathlibs) incl_dir = os.path.dirname(target) if incl_dir not in config.numpy_include_dirs: config.numpy_include_dirs.append(incl_dir) return target def generate_numpyconfig_h(ext, build_dir): """Depends on config.h: generate_config_h has to be called before !""" target = join(build_dir,header_dir,'_numpyconfig.h') d = os.path.dirname(target) if not os.path.exists(d): os.makedirs(d) if newer(__file__,target): config_cmd = config.get_config_cmd() log.info('Generating %s',target) ignored, moredefs = cocache.check_types(config_cmd, ext, build_dir) if is_npy_no_signal(): moredefs.append(('NPY_NO_SIGNAL', 1)) if is_npy_no_smp(): moredefs.append(('NPY_NO_SMP', 1)) else: moredefs.append(('NPY_NO_SMP', 0)) mathlibs = check_mathlib(config_cmd) moredefs.extend(cocache.check_ieee_macros(config_cmd)[1]) moredefs.extend(cocache.check_complex(config_cmd, mathlibs)[1]) if ENABLE_SEPARATE_COMPILATION: moredefs.append(('NPY_ENABLE_SEPARATE_COMPILATION', 1)) if config_cmd.check_decl('PRIdPTR', headers = ['inttypes.h']): moredefs.append(('NPY_USE_C99_FORMATS', 1)) hidden_visibility = visibility_define(config_cmd) moredefs.append(('NPY_VISIBILITY_HIDDEN', hidden_visibility)) moredefs.append(('NPY_ABI_VERSION', '0x%.8X' % C_ABI_VERSION)) moredefs.append(('NPY_API_VERSION', '0x%.8X' % C_API_VERSION)) target_f = open(target, 'w') for d in moredefs: if isinstance(d,str): target_f.write(' else: target_f.write(' target_f.write(""" """) target_f.close() print('File: %s' % target) target_f = open(target) print(target_f.read()) target_f.close() print('EOF') config.add_data_files((header_dir, target)) return target def generate_api_func(module_name): def generate_api(ext, build_dir): script = join(codegen_dir, module_name + '.py') sys.path.insert(0, codegen_dir) try: m = __import__(module_name) log.info('executing %s', script) h_file, c_file, doc_file = m.generate_api(os.path.join(build_dir, header_dir)) finally: del sys.path[0] config.add_data_files((header_dir, h_file), (header_dir, doc_file)) return (h_file,) return generate_api generate_numpy_api = generate_api_func('generate_numpy_api') generate_ufunc_api = generate_api_func('generate_ufunc_api') config.add_include_dirs(join(local_dir, "src", "private")) config.add_include_dirs(join(local_dir, "src")) config.add_include_dirs(join(local_dir)) def generate_multiarray_templated_sources(ext, build_dir): from numpy.distutils.misc_util import get_cmd subpath = join('src', 'multiarray') sources = [join(local_dir, subpath, 'scalartypes.c.src'), join(local_dir, subpath, 'arraytypes.c.src')] config.add_include_dirs(join(build_dir, subpath)) cmd = get_cmd('build_src') cmd.ensure_finalized() cmd.template_sources(sources, ext) def generate_umath_templated_sources(ext, build_dir): from numpy.distutils.misc_util import get_cmd subpath = join('src', 'umath') sources = [join(local_dir, subpath, 'loops.c.src'), join(local_dir, subpath, 'umathmodule.c.src')] config.add_include_dirs(join(build_dir, subpath)) cmd = get_cmd('build_src') cmd.ensure_finalized() cmd.template_sources(sources, ext) def generate_umath_c(ext,build_dir): target = join(build_dir,header_dir,'__umath_generated.c') dir = os.path.dirname(target) if not os.path.exists(dir): os.makedirs(dir) script = generate_umath_py if newer(script,target): f = open(target,'w') f.write(generate_umath.make_code(generate_umath.defdict, generate_umath.__file__)) f.close() return [] config.add_data_files('include/numpy/*.h') config.add_include_dirs(join('src', 'npymath')) config.add_include_dirs(join('src', 'multiarray')) config.add_include_dirs(join('src', 'umath')) config.numpy_include_dirs.extend(config.paths('include')) deps = [join('src','npymath','_signbit.c'), join('include','numpy','*object.h'), 'include/numpy/fenv/fenv.c', 'include/numpy/fenv/fenv.h', join(codegen_dir,'genapi.py'), ] if sys.platform == 'cygwin': config.add_data_dir('include/numpy/fenv') config.add_extension('_sort', sources=[join('src','_sortmodule.c.src'), generate_config_h, generate_numpyconfig_h, generate_numpy_api, ], ) subst_dict = dict([("sep", os.path.sep), ("pkgname", "numpy.core")]) def get_mathlib_info(*args): config_cmd = config.get_config_cmd() st = config_cmd.try_link('int main(void) { return 0;}') if not st: raise RuntimeError("Broken toolchain: cannot link a simple C program") mlibs = check_mathlib(config_cmd) posix_mlib = ' '.join(['-l%s' % l for l in mlibs]) msvc_mlib = ' '.join(['%s.lib' % l for l in mlibs]) subst_dict["posix_mathlib"] = posix_mlib subst_dict["msvc_mathlib"] = msvc_mlib config.add_installed_library('npymath', sources=[join('src', 'npymath', 'npy_math.c.src'), join('src', 'npymath', 'ieee754.c.src'), join('src', 'npymath', 'npy_math_complex.c.src'), get_mathlib_info], install_dir='lib') config.add_npy_pkg_config("npymath.ini.in", "lib/npy-pkg-config", subst_dict) config.add_npy_pkg_config("mlib.ini.in", "lib/npy-pkg-config", subst_dict) multiarray_deps = [ join('src', 'multiarray', 'arrayobject.h'), join('src', 'multiarray', 'arraytypes.h'), join('src', 'multiarray', 'buffer.h'), join('src', 'multiarray', 'calculation.h'), join('src', 'multiarray', 'common.h'), join('src', 'multiarray', 'convert_datatype.h'), join('src', 'multiarray', 'convert.h'), join('src', 'multiarray', 'conversion_utils.h'), join('src', 'multiarray', 'ctors.h'), join('src', 'multiarray', 'descriptor.h'), join('src', 'multiarray', 'getset.h'), join('src', 'multiarray', 'hashdescr.h'), join('src', 'multiarray', 'iterators.h'), join('src', 'multiarray', 'mapping.h'), join('src', 'multiarray', 'methods.h'), join('src', 'multiarray', 'multiarraymodule.h'), join('src', 'multiarray', 'numpymemoryview.h'), join('src', 'multiarray', 'number.h'), join('src', 'multiarray', 'numpyos.h'), join('src', 'multiarray', 'refcount.h'), join('src', 'multiarray', 'scalartypes.h'), join('src', 'multiarray', 'sequence.h'), join('src', 'multiarray', 'shape.h'), join('src', 'multiarray', 'ucsnarrow.h'), join('src', 'multiarray', 'usertypes.h')] multiarray_src = [join('src', 'multiarray', 'multiarraymodule.c'), join('src', 'multiarray', 'hashdescr.c'), join('src', 'multiarray', 'arrayobject.c'), join('src', 'multiarray', 'numpymemoryview.c'), join('src', 'multiarray', 'buffer.c'), join('src', 'multiarray', 'numpyos.c'), join('src', 'multiarray', 'conversion_utils.c'), join('src', 'multiarray', 'flagsobject.c'), join('src', 'multiarray', 'descriptor.c'), join('src', 'multiarray', 'iterators.c'), join('src', 'multiarray', 'mapping.c'), join('src', 'multiarray', 'number.c'), join('src', 'multiarray', 'getset.c'), join('src', 'multiarray', 'sequence.c'), join('src', 'multiarray', 'methods.c'), join('src', 'multiarray', 'ctors.c'), join('src', 'multiarray', 'convert_datatype.c'), join('src', 'multiarray', 'convert.c'), join('src', 'multiarray', 'shape.c'), join('src', 'multiarray', 'item_selection.c'), join('src', 'multiarray', 'calculation.c'), join('src', 'multiarray', 'common.c'), join('src', 'multiarray', 'usertypes.c'), join('src', 'multiarray', 'scalarapi.c'), join('src', 'multiarray', 'refcount.c'), join('src', 'multiarray', 'arraytypes.c.src'), join('src', 'multiarray', 'scalartypes.c.src')] if PYTHON_HAS_UNICODE_WIDE: multiarray_src.append(join('src', 'multiarray', 'ucsnarrow.c')) umath_src = [join('src', 'umath', 'umathmodule.c.src'), join('src', 'umath', 'funcs.inc.src'), join('src', 'umath', 'loops.c.src'), join('src', 'umath', 'ufunc_object.c')] umath_deps = [generate_umath_py, join(codegen_dir,'generate_ufunc_api.py')] if not ENABLE_SEPARATE_COMPILATION: multiarray_deps.extend(multiarray_src) multiarray_src = [join('src', 'multiarray', 'multiarraymodule_onefile.c')] multiarray_src.append(generate_multiarray_templated_sources) umath_deps.extend(umath_src) umath_src = [join('src', 'umath', 'umathmodule_onefile.c')] umath_src.append(generate_umath_templated_sources) umath_src.append(join('src', 'umath', 'funcs.inc.src')) config.add_extension('multiarray', sources = multiarray_src + [generate_config_h, generate_numpyconfig_h, generate_numpy_api, join(codegen_dir,'generate_numpy_api.py'), join('*.py')], depends = deps + multiarray_deps, libraries=['npymath']) config.add_extension('umath', sources = [generate_config_h, generate_numpyconfig_h, generate_umath_c, generate_ufunc_api, ] + umath_src, depends = deps + umath_deps, libraries=['npymath'], ) config.add_extension('scalarmath', sources=[join('src','scalarmathmodule.c.src'), generate_config_h, generate_numpyconfig_h, generate_numpy_api, generate_ufunc_api], ) blas_info = get_info('blas_opt',0) def get_dotblas_sources(ext, build_dir): if blas_info: if ('NO_ATLAS_INFO',1) in blas_info.get('define_macros',[]): return None return ext.depends[:1] return None config.add_extension('_dotblas', sources = [get_dotblas_sources], depends=[join('blasdot','_dotblas.c'), join('blasdot','cblas.h'), ], include_dirs = ['blasdot'], extra_info = blas_info ) config.add_extension('umath_tests', sources = [join('src','umath', 'umath_tests.c.src')]) config.add_extension('multiarray_tests', sources = [join('src', 'multiarray', 'multiarray_tests.c.src')]) config.add_data_dir('tests') config.add_data_dir('tests/data') config.make_svn_version_py() return config if __name__=='__main__': from numpy.distutils.core import setup setup(configuration=configuration)
exitcode = exitstatus log.info("success!") except (CompileError, LinkError): log.info("failure.") self._clean() return exitcode, output
def check_prec(prec): flist = [f + prec for f in C99_COMPLEX_FUNCS] decl = dict([(f, True) for f in flist]) if not config.check_funcs_once(flist, call=decl, decl=decl, libraries=mathlibs): for f in flist: if config.check_func(f, call=True, decl=True, libraries=mathlibs): priv.append(fname2def(f)) else: priv.extend([fname2def(f) for f in flist])
37a71c453b67f06646e51013b2c929ce8b65459c /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/37a71c453b67f06646e51013b2c929ce8b65459c/config.py
Check if a sage object belongs to self. This methods is a helper for
Check if a Sage object belongs to self. This methods is a helper for
def _is_a(self, x): """ Check if a sage object belongs to self. This methods is a helper for :meth:`__contains__` and the constructor :meth:`_element_constructor_`.
62c8437e005a688e712c36d6d3897153c0c6da68 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/62c8437e005a688e712c36d6d3897153c0c6da68/disjoint_union_enumerated_sets.py
self._error_re = re.compile('(Principal Value|debugmode|Incorrect syntax|Maxima encountered a Lisp error)')
self._error_re = re.compile('(Principal Value|debugmode|incorrect syntax|Maxima encountered a Lisp error)')
def __init__(self, script_subdirectory=None, logfile=None, server=None, init_code = None): """ Create an instance of the Maxima interpreter.
0b796a5c0ac8e667cd5ef6b96db8e7e2b5b339c0 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/0b796a5c0ac8e667cd5ef6b96db8e7e2b5b339c0/maxima.py
sage: maxima.eval('sage0: x == x;')
sage: maxima._eval_line('sage0: x == x;')
def _eval_line(self, line, allow_use_file=False, wait_for_prompt=True, reformat=True, error_check=True): """ EXAMPLES:
0b796a5c0ac8e667cd5ef6b96db8e7e2b5b339c0 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/0b796a5c0ac8e667cd5ef6b96db8e7e2b5b339c0/maxima.py
TypeError: error evaluating "sage0: x == x;":...
TypeError: Error executing code in Maxima...
def _eval_line(self, line, allow_use_file=False, wait_for_prompt=True, reformat=True, error_check=True): """ EXAMPLES:
0b796a5c0ac8e667cd5ef6b96db8e7e2b5b339c0 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/0b796a5c0ac8e667cd5ef6b96db8e7e2b5b339c0/maxima.py
pre_out = self._before() self._expect_expr() out = self._before()
out = self._before()
def _eval_line(self, line, allow_use_file=False, wait_for_prompt=True, reformat=True, error_check=True): """ EXAMPLES:
0b796a5c0ac8e667cd5ef6b96db8e7e2b5b339c0 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/0b796a5c0ac8e667cd5ef6b96db8e7e2b5b339c0/maxima.py
self._error_check(line, pre_out)
def _eval_line(self, line, allow_use_file=False, wait_for_prompt=True, reformat=True, error_check=True): """ EXAMPLES:
0b796a5c0ac8e667cd5ef6b96db8e7e2b5b339c0 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/0b796a5c0ac8e667cd5ef6b96db8e7e2b5b339c0/maxima.py
i = o.rfind('(%o') return o[:i]
def _eval_line(self, line, allow_use_file=False, wait_for_prompt=True, reformat=True, error_check=True): """ EXAMPLES:
0b796a5c0ac8e667cd5ef6b96db8e7e2b5b339c0 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/0b796a5c0ac8e667cd5ef6b96db8e7e2b5b339c0/maxima.py
def _command_runner(self, command, s, redirect=True): """ Run ``command`` in a new Maxima session and return its output as an ``AsciiArtString``.
0b796a5c0ac8e667cd5ef6b96db8e7e2b5b339c0 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/0b796a5c0ac8e667cd5ef6b96db8e7e2b5b339c0/maxima.py
for _ in range(3):
for _ in range(5):
def _command_runner(self, command, s, redirect=True): """ Run ``command`` in a new Maxima session and return its output as an ``AsciiArtString``.
0b796a5c0ac8e667cd5ef6b96db8e7e2b5b339c0 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/0b796a5c0ac8e667cd5ef6b96db8e7e2b5b339c0/maxima.py
'5.20.1'
'5.22.1'
def version(self): """ Return the version of Maxima that Sage includes.
0b796a5c0ac8e667cd5ef6b96db8e7e2b5b339c0 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/0b796a5c0ac8e667cd5ef6b96db8e7e2b5b339c0/maxima.py