Thursday, February 21, 2019

Sage 50 Accounting Software Tutorial

discerning tutorial come forth 5. 3 The sharp t to each oneing Team September 10, 2012 CONTENTS 1 Introduction 1. 1 instalment 1. 2 Ways to Use sharp-witted . . 1. 3 Longterm Goals for acute . . 3 4 4 4 7 7 9 10 13 18 21 24 26 29 33 38 39 41 51 51 53 54 54 55 56 57 58 60 61 62 65 65 66 67 68 2 A Guided Tour 2. 1 As compressment, Equality, and Arithmetic 2. acquiring sponsor . 2. 3 Functions, Indentation, and Counting 2. 4 Basic Algebra and Calculus . . 2. 5 Plotting . 2. 6 Some Common Issues with Functions 2. 7 Basic Rings . . 2. 8 Linear Algebra 2. 9 Polynomials . 2. 10 P arnts, Conversion and Coercion . . 2. 11 bounded Groups, Abelian Groups . 2. 12 Number Theory . . 2. 13 Some More modernistic math 3 The synergistic case 3. 1 Your sharp school term . . 3. 2 Logging gossip and Output . 3. 3 Paste Ignores Prompts 3. 4 Timing Commands . . 3. 5 Other IPython tricks . 3. 6 Errors and Exceptions 3. 7 Reverse appear and lozenge Completion . . 3. 8 Integrated armed ser vice dodge . 3. 9 deliver and fill Individual Objects 3. 10 saving and laden pulsate it on Sessions 3. 11 The occupationbook Interface . . 4 Interfaces 4. 1 GP/PARI 4. 2 rupture . . 4. 3 Singular . 4. 4 Maxima i 5 able, rubber- cup of tea paint and Fri poles 5. 1 Overview . . 5. 2 Basic Use . . 5. 3 Customizing LaTeX coevals . . 5. 4 Customizing LaTeX Proces repulsivenessg . . 5. 5 An Example Combinatorial Graphs with tkz-graph . 5. 6 A Fully Capable TeX Inst in any(a)ation . 5. 7 External Programs . 71 71 72 73 75 76 77 77 79 79 80 81 81 82 84 85 86 86 88 91 93 93 94 95 97 97 99 101 103 hotshotness hundred five 6 Programming 6. 1 Loading and Atta ching discerning ? les 6. 2 Creating Compiled mandate . 6. 3 Standalone Python/ judicious Scripts . 6. 4 Data vitrines 6. 5 Lists, Tuples, and Sequences 6. 6 Dictionaries 6. 7 Sets . 6. 8 Iterators . . 6. 9 Loops, Functions, Control Statements, and Comparisons 6. 10 Pro? ling . 7 Using quick-scentedTeX 8 . . Afterword 8 . 1 Why Python? . . 8. I would the likes of to lend whateverhow. How dis breakful I? . 8. 3 How do I reference able? . 9 Appendix 9. 1 Arithmetical double star operator precession . . 10 Bibliography 11 Indices and haltles Bibliography Index ii shrewd Tutorial, throw everywhereboard 5. 3 apt is free, open- obtain math softw ar that births re assay and teaching in algebra, geome effort, chip theory, cryptography, numeric thinkr science, and related atomic number 18as.Both the quick-scented development mock up and the technology in sensible itself atomic number 18 distinguished by an passing strong emphasis on openness, community, cooperation, and collaboration we are building the car, non reinventing the wheel. The overall goal of shrewd is to create a viable, free, open- witness admition to Maple, Mathematica, Magma, and MATLAB. This tutorial is the best way to become familiar with apt in only a few hours. You great deal read it in hypertext mark-up la ngu era or PDF versions, or from the judicious nonebook data processor (click Help, consequently click Tutorial to synergisticly take on through the tutorial from within sensible).This acidify is licensed beneath a Creative Commons Attri to a greater extentoverion-Share Alike 3. 0 License. CONTENTS 1 judicious Tutorial, loss 5. 3 2 CONTENTS CHAPTER ONE intro This tutorial should take at nigh 3-4 hours to bounteousy work through. You stick out read it in HTML or PDF versions, or from the sharp-witted nonebook click Help, and then click Tutorial to inter progressively work through the tutorial from within acute. Though frequently of keen-sighted is implemented exploitation Python, no Python emphasize is engageed to read this tutorial. You bequeath hope to learn Python (a very(prenominal) fun language ) at some(a) point, and t here(predicate) are mevery a(prenominal) excellent free resources for doing so including PyT and Dive.If you undecomposed want to qu ickly try out Sage, this tutorial is the place to blow up. For warning keen-sighted 2 + 2 4 keen-witted factor(-2007) -1 * 32 * 223 perspicacious A = intercellular substance(4,4, stray(16)) A 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 keen-green factor(A. charpoly()) x2 * (x2 30*x 80) keen m = hyaloplasm(ZZ,2, range(4)) shrewd m0,0 = m0,0 3 apt m -3 1 2 3 keen E = Elliptic meander(1,2,3,4,5) acute E Elliptic Curve define by y2 + x*y + 3*y = x3 + 2*x2 + 4*x + 5 over coherent depicted object judicious E. an joust(10) 0, 1, 1, 0, -1, -3, 0, -1, -3, -3, -3 perspicacious E. ank() 1 keen-sighted k = 1/(sqrt(3)*I + 3/4 + sqrt(73)*5/9) k 1/(I*sqrt(3) + 5/9*sqrt(73) + 3/4) shrewd N(k) 0. 165495678130644 0. 0521492082074256*I wise N(k,30) 30 bits 0. 16549568 0. 052149208*I sharp-witted latex(k) frac1i , sqrt3 + frac59 , sqrt73 + frac34 3 Sage Tutorial, drop off 5. 3 1. 1 Installation If you do non endure Sage installed on a in kneadation processing system and j ust want to try some sees, economic consumption online at http//www. keen-sightednb. org. collide with the Sage Installation Guide in the livelihood section of the primary(prenominal) Sage sack up paginate SA for instructions on installing Sage on your figurer. here(predicate) we merely make a few comments. 1. The Sage down essence ? le comes with batteries include. In unalike words, although Sage commits Python, IPython, PARI, GAP, Singular, Maxima, NTL, GMP, and so on, you do non need to install them separately as they are included with the Sage distri composeion. However, to intake certain Sage features, e. g. , Macaulay or KASH, you mustiness install the applicable optional package or at least have the relevant programs installed on your castr already. Macaulay and KASH are Sage packages (for a list of ready(prenominal) optional packages, graphic symbol sharp -optional, or browse the Down incumbrance page on the Sage webwebsite). . The pre-compiled binary vers ion of Sage (found on the Sage web site) may be easier and quicker to install than the source autograph version. Just unpack the ? le and affiliate perspicacious. 3. If youd like to habit the SageTeX package (which allows you to embed the results of Sage computations into a LaTeX ? le), you will need to make SageTeX know to your TeX distri just nowion. To do this, see the section represent SageTeX known to TeX in the Sage installation impart (this link should take you to a local model of the installation guide). Its quite easy you just need to mend an environment variable or copy a single ? e to a directory that TeX will search. The documentation for victimization SageTeX is laid in $ sagacious-green_ROOT/local/share/texmf/tex/generic/ acutetex/, where $SAGE_ROOT refers to the directory where you installed Sage for example, /opt/ keen-witted-4. 2. 1. 1. 2 Ways to Use Sage You rearful part Sage in several ways. occupationbook graphical port see the section on the No tebook in the reference manual and The Notebook Interface on a lower floor, moveive pedagogy line see The Interactive reprimand, Programs By paper taken and compiled programs in Sage (see Loading and Attaching Sage ? es and Creating Compiled Code), and Scripts by writing stand-alone Python scripts that use the Sage program library (see Standalone Python/Sage Scripts). 1. 3 Longterm Goals for Sage Useful Sages int finish audience is mathematics students (from senior high school school to graduate school), teachers, and research mathematicians. The aim is to provide software that stop be utilise to explore and experiment with numerical constructions in algebra, geometry, hail theory, calculus, numerical computation, etc. Sage champions make it easier to synergeticly experiment with mathematical objects. Ef? cient Be spry. Sage uses highly-optimized mature software like GMP, PARI, GAP, and NTL, and so is very fast at certain trading operations. Free and open source Th e source edict must be freely available and readable, so drug exploiters fundament represent what the system is really doing and more(prenominal) easily extend it. Just as mathematicians gain a deeper mind of a theorem by carefully learning or at least skimming the proof, people who do computations should be able to understand how the calculations work by reading documented source code. If you use Sage to do computations 4Chapter 1. Introduction Sage Tutorial, beat 5. 3 in a paper you publish, you stinker break guarantee that your readers will always have free entry to Sage and all its source code, and you are even out allowed to archive and re-distribute the version of Sage you used. lightheaded to compile Sage should be easy to compile from source for Linux, OS X and Windows drug users. This provides more ? exibility for users to modify the system. Cooperation Provide robust portholes to intimately new(prenominal) computer algebra systems, including PARI, GAP , Singular, Maxima, KASH, Magma, Maple, and Mathematica.Sage is meant to unify and extend existing math software. come up(p) documented Tutorial, programing guide, reference manual, and how-to, with numerous examples and discussion of background mathematics. protrusile Be able to de? ne new data types or take off from built-in types, and use code written in a range of languages. User friendly It should be easy to understand what consumptionality is provided for a disposed object and to view documentation and source code. Also attain a high level of user support. 1. 3. Longterm Goals for Sage 5Sage Tutorial, bring out 5. 3 6 Chapter 1. Introduction CHAPTER TWO A GUIDED fling This section is a guided tour of some of what is available in Sage. For m whatsoever more examples, see Sage Constructions, which is intended to answer the prevalent question How do I construct ? . See likewise the Sage Reference Manual, which has thousands more examples. Also note that you layabou t interactively work through this tour in the Sage notebook by clicking the Help link. (If you are viewing the tutorial in the Sage notebook, press shift-enter to valuate each input cell.You flowerpot even cut off the input forwards pressing shift-enter. On some Macs you might have to press shift- damages rather than shift-enter. ) 2. 1 Assignment, Equality, and Arithmetic With some minor ejections, Sage uses the Python programming language, so most(prenominal) introductory books on Python will athletic supporter you to learn Sage. Sage uses = for assignment. It uses ==, =, and for comparison acute sharp-witted 5 keen-sighted True quick of scent-green sullen acute True clear-sighted True a = 5 a 2 == 2 2 == 3 2 3 a == 5 Sage provides all of the basic mathematical operations age 8 clear-sighted 8 apt 1 shrewd 5/2 sharp-witted 2 sensible True 2**3 23 10 % 3 10/4 10//4 for integer arguments, // elapses the integer quotient ** means exponent is a synonym f or ** (unlike in Python) for integer arguments, % means mod, i. e. , remainder 4 * (10 // 4) + 10 % 4 == 10 7 Sage Tutorial, Release 5. 3 sharp 32*4 + 2%5 38 The computation of an expression like 32*4 + 2%5 depends on the stage in which the operations are applied this is speci? ed in the operator precedence table in Arithmetical binary operator precedence. Sage excessively provides many familiar mathematical brings here are just a few examples keen sqrt(3. ) 1. 84390889145858 discerning sin(5. 135) -0. 912021158525540 shrewd sin(pi/3) 1/2*sqrt(3) As the last example shows, some mathematical expressions return exact values, rather than numerical approximations. To get a numerical approximation, use either the business office n or the method n (and both of these have a eagle-eyeder relieve oneself, numerical_approx, and the function N is the comparable as n)). These take optional arguments prec, which is the requested number of bits of precision, and digits, which is the re quested number of decimal digits of precision the nonpayment is 53 bits of precision. keen exp(2) e2 judicious n(exp(2)) 7. 8905609893065 keen sqrt(pi). numerical_approx() 1. 77245385090552 acute sin(10). n(digits=5) -0. 54402 sensible N(sin(10),digits=10) -0. 5440211109 discerning numerical_approx(pi, prec=200) 3. 1415926535897932384626433832795028841971693993751058209749 Python is dynami confabulatey typed, so the value referred to by each variable has a type associated with it, but a tending(p)(p) variable may h aging values of any Python type within a given scope shrewd-green quick of scent The C programming language, which is statically typed, is much contrary a variable enjoin to hold an int shadower only hold an int in its scope.A probable source of confusion in Python is that an integer literal that begins with a zero is treated as an octal number, i. e. , a number in base 8. sage 9 sage 9 sage sage 11 011 8 + 1 n = 011 n. str(8) tie bureau of n in base 8 8 Chapter 2. A Guided Tour Sage Tutorial, Release 5. 3 This is consistent with the C programming language. 2. 2 acquiring Help Sage has extensive built-in documentation, accessible by typewrite the report of a function or a constant (for example), followed by a question mark sage tan? fiber rendering Docstring tan( noargspec ) The tangent function EXAMPLES sage tan(pi) 0 sage tan(3. 1415) -0. 0000926535900581913 sage tan(3. 1415/4) 0. 999953674278156 sage tan(pi/4) 1 sage tan(1/2) tan(1/2) sage RR(tan(1/2)) 0. 546302489843790 sage log2? quality Definition log2( noargspec ) Docstring The ingrained logarithm of the real number 2. EXAMPLES sage log2 log2 sage float(log2) 0. 69314718055994529 sage RR(log2) 0. 693147180559945 sage R = Real range(200) R Real house with 200 bits of precision sage R(log2) 0. 9314718055994530941723212145817656807550013436025525412068 sage l = (1-log2)/(1+log2) l (1 log(2))/(log(2) + 1) sage R(l) 0. 1812322182992824994876138186465031142333060977477601 3488056 sage maxima(log2) log(2) sage maxima(log2). float() . 6931471805599453 sage gp(log2) 0. 6931471805599453094172321215 32-bit 0. 69314718055994530941723212145817656807 64-bit sage sudoku? 2. 2. Getting Help 9 Sage Tutorial, Release 5. 3 commove Type Definition Docstring sage/local/lib/python2. 5/site-packages/sage/games/sudoku. py sudoku(A) Solve the 99 Sudoku puzzle delimit by the matrix A.EXAMPLE sage A = matrix(ZZ,9,5,0,0, 0,8,0, 0,4,9, 0,0,0, 5,0,0, 0,3,0, 0,6,7, 3,0,0, 0,0,1, 1,5,0, 0,0,0, 0,0,0, 0,0,0, 2,0,8, 0,0,0, 0,0,0, 0,0,0, 0,1,8, 7,0,0, 0,0,4, 1,5,0, 0,3,0, 0,0,2, 0,0,0, 4,9,0, 0,5,0, 0,0,3) sage A 5 0 0 0 8 0 0 4 9 0 0 0 5 0 0 0 3 0 0 6 7 3 0 0 0 0 1 1 5 0 0 0 0 0 0 0 0 0 0 2 0 8 0 0 0 0 0 0 0 0 0 0 1 8 7 0 0 0 0 4 1 5 0 0 3 0 0 0 2 0 0 0 4 9 0 0 5 0 0 0 3 sage sudoku(A) 5 1 3 6 8 7 2 4 9 8 4 9 5 2 1 6 3 7 2 6 7 3 4 9 5 8 1 1 5 8 4 6 3 9 7 2 9 7 4 2 1 8 3 6 5 3 2 6 7 9 5 4 1 8 7 8 2 9 3 4 1 5 6 6 3 5 1 7 2 8 9 4 4 9 1 8 5 6 7 2 3Sage as well as provides Tab completion type the ? rst few letters of a function and then hit the tab mark. For example, if you type ta followed by TAB, Sage will scratch tachyon, tan, tanh, taylor. This provides a good way to ? nd the names of functions and other structures in Sage. 2. 3 Functions, Indentation, and Counting To de? ne a new function in Sage, use the def need and a colon after(prenominal) the list of variable names. For example sage def is_even(n) return n%2 == 0 sage is_even(2) True sage is_even(3) False Note Depending on which version of the tutorial you are viewing, you may see terzetto dots n the second line of this example. Do not type them they are just to emphasize that the code is indented. Whenever this is the case, press Return/Enter once at the end of the block to insert a blank line and conclude the function de? nition. You do not set forth the types of any of the input arguments. You dissolve asseverate multiple inputs, each of which may have an optional failure value. For example, the function below defaults to divisor=2 if divisor is not speci? ed. 10 Chapter 2. A Guided Tour Sage Tutorial, Release 5. 3 sage sage True sage True sage False ef is_divisible_by(number, divisor=2) return number%divisor == 0 is_divisible_by(6,2) is_divisible_by(6) is_divisible_by(6, 5) You fanny excessively explicitly specify one or either of the inputs when calling the function if you specify the inputs explicitly, you can buoy give them in any order sage is_divisible_by(6, divisor=5) False sage is_divisible_by(divisor=2, number=6) True In Python, blocks of code are not indicated by curly braces or begin and end blocks as in many other languages. Instead, blocks of code are indicated by indentation, which must match up scarce.For example, the following is a syntax error because the return statement is not indented the same amount as the other lines preceding(prenominal) it. sage def even(n) v = for i in range(3,n) if i % 2 == 0 v. append(i) return v Syntax Error ret urn v If you ? x the indentation, the function working sage def even(n) v = for i in range(3,n) if i % 2 == 0 v. append(i) return v sage even(10) 4, 6, 8 Semicolons are not needed at the ends of lines a line is in most cases ended by a newline. However, you can put multiple statements on one line, separated by semicolons sage a = 5 b = a + 3 c = b2 c 64If you would like a single line of code to span multiple lines, use a terminating backslash sage 2 + 3 5 In Sage, you count by iterating over a range of integers. For example, the ? rst line below is exactly like for(i=0 i x2 sage g(3) 9 sage Dg = g. derivative() Dg x 2*x sage Dg(3) 6 sage type(g) sage plot(g, 0, 2) Note that bit g is a callable exemplary expression, g(x) is a related, but different sort of object, which can also be plotted, differentated, etc. , albeit with some issues see item 5 below for an illustration. sage x2 sage g(x). derivative() plot(g(x), 0, 2) 3. Use a pre-de? ed Sage calculus function. These can be p lotted, and with a little help, differentiated, and integrated. sage type(sin) sage plot(sin, 0, 2) sage type(sin(x)) sage plot(sin(x), 0, 2) By itself, sin cannot be differentiated, at least not to produce cos. sage f = sin sage f. derivative() Traceback (most recent call last) AttributeError Using f = sin(x) sooner of sin works, but it is probably even better to use f(x) = sin(x) to de? ne a callable symbolic expression. sage S(x) = sin(x) sage S. derivative() x cos(x) here(predicate) are some common problems, with explanations 4. Accidental evaluation. sage def h(x) f x 1 to 0. sage G = DirichletGroup(12) sage G. list() Dirichlet typesetters case modulo 12 of manager 1 social occasion 7 1, 5 1, Dirichlet character modulo 12 of theater director 4 mapping 7 -1, 5 1, Dirichlet character modulo 12 of theatre director 3 mapping 7 1, 5 -1, Dirichlet character modulo 12 of manager 12 mapping 7 -1, 5 -1 sage G. gens() (Dirichlet character modulo 12 of film director 4 ma pping 7 -1, 5 1, Dirichlet character modulo 12 of theatre director 3 mapping 7 1, 5 -1) sage len(G) 4 Having created the group, we succeeding(prenominal) create an element and compute with it. age G = DirichletGroup(21) sage chi = G. 1 chi Dirichlet character modulo 21 of conductor 7 mapping 8 1, 10 zeta6 sage chi. values() 0, 1, zeta6 1, 0, -zeta6, -zeta6 + 1, 0, 0, 1, 0, zeta6, -zeta6, 0, -1, 0, 0, zeta6 1, zeta6, 0, -zeta6 + 1, -1 sage chi. conductor() 7 sage chi. modulus() 21 sage chi. order() 6 sage chi(19) -zeta6 + 1 sage chi(40) -zeta6 + 1 It is also possible to compute the action of the Galois group Gal(Q(? N )/Q) on these characters, as well as the direct product decomposition equal to the factorization of the modulus. sage chi. alois_ theater of operations() Dirichlet character modulo 21 of conductor 7 mapping 8 1, 10 zeta6, 2. 13. Some More move on Mathematics 45 Sage Tutorial, Release 5. 3 Dirichlet character modulo 21 of conductor 7 mapping 8 1, 10 -zeta 6 + 1 sage go = G. galois_orbits() sage len(orbit) for orbit in go 1, 2, 2, 1, 1, 2, 2, 1 sage Group 6 and Group 6 and G. decomposition() of Dirichlet characters of modulus 3 over Cyclotomic compass of order degree 2, of Dirichlet characters of modulus 7 over Cyclotomic bowl of order degree 2 Next, we construct the group of Dirichlet characters mod 20, but with values n Q(i) sage sage sage Group K. = NumberField(x2+1) G = DirichletGroup(20,K) G of Dirichlet characters of modulus 20 over Number Field in i with defining multinomial x2 + 1 We contiguous compute several invariants of G sage G. gens() (Dirichlet character modulo 20 of conductor 4 mapping 11 -1, 17 1, Dirichlet character modulo 20 of conductor 5 mapping 11 1, 17 i) sage G. unit_gens() 11, 17 sage G. zeta() i sage G. zeta_order() 4 In this example we create a Dirichlet character with values in a number ? eld. We explicitly specify the election of root of unity by the third argument to DirichletGroup below. age x = polygen(QQ, x) sage K = NumberField(x4 + 1, a) a = K. 0 sage b = K. gen() a == b True sage K Number Field in a with defining polynomial x4 + 1 sage G = DirichletGroup(5, K, a) G Group of Dirichlet characters of modulus 5 over Number Field in a with defining polynomial x4 + 1 sage chi = G. 0 chi Dirichlet character modulo 5 of conductor 5 mapping 2 a2 sage (chii)(2) for i in range(4) 1, a2, -1, -a2 present NumberField(x4 + 1, a) tells Sage to use the symbol a in depression what K is (a Number Field in a with de? ning polynomial x4 + 1). The name a is undeclared at this point.Once a = K. 0 (or equivalently a = K. gen()) is pronounced, the symbol a represents a root of the generating polynomial x4 + 1. 46 Chapter 2. A Guided Tour Sage Tutorial, Release 5. 3 2. 13. 4 standard Forms Sage can do some computations related to standard forms, including propertys, cipher billets of modular symbols, Hecke operators, and decompositions. There are several functions available for comp uting symmetrys of distances of modular forms. For example, sage ratio_cusp_forms(Gamma0(11),2) 1 sage dimension_cusp_forms(Gamma0(1),12) 1 sage dimension_cusp_forms(Gamma1(389),2) 6112Next we bedeck computation of Hecke operators on a space of modular symbols of level 1 and free weight 12. sage M = modularSymbols(1,12) sage M. basis() (X8*Y2,(0,0), X9*Y,(0,0), X10,(0,0)) sage t2 = M. T(2) sage t2 Hecke operator T_2 on standard Symbols space of dimension 3 for Gamma_0(1) of weight 12 with sign 0 over sensible Field sage t2. matrix() -24 0 0 0 -24 0 4860 0 2049 sage f = t2. charpoly(x) f x3 2001*x2 97776*x 1180224 sage factor(f) (x 2049) * (x + 24)2 sage M. T(11). charpoly(x). factor() (x 285311670612) * (x 534612)2We can also create spaces for ? 0 (N ) and ? 1 (N ). sage ModularSymbols(11,2) Modular Symbols space of dimension 3 for Gamma_0(11) of weight 2 with sign 0 over demythologised Field sage ModularSymbols(Gamma1(11),2) Modular Symbols space of dimension 11 fo r Gamma_1(11) of weight 2 with sign 0 and over cerebral Field permits compute some characteristic polynomials and q-expansions. sage M = ModularSymbols(Gamma1(11),2) sage M. T(2). charpoly(x) x11 8*x10 + 20*x9 + 10*x8 145*x7 + 229*x6 + 58*x5 360*x4 + 70*x3 515*x2 + 1804*x 1452 sage M. T(2). charpoly(x). actor() (x 3) * (x + 2)2 * (x4 7*x3 + 19*x2 23*x + 11) * (x4 2*x3 + 4*x2 + 2*x + 11) sage S = M. cuspidal_submodule() sage S. T(2). matrix() -2 0 0 -2 sage S. q_expansion_basis(10) q 2*q2 q3 + 2*q4 + q5 + 2*q6 2*q7 2*q9 + O(q10) 2. 13. Some More Advanced Mathematics 47 Sage Tutorial, Release 5. 3 We can even compute spaces of modular symbols with character. sage G = DirichletGroup(13) sage e = G. 02 sage M = ModularSymbols(e,2) M Modular Symbols space of dimension 4 and level 13, weight 2, character zeta6, sign 0, over Cyclotomic Field of order 6 and degree 2 sage M.T(2). charpoly(x). factor() (x 2*zeta6 1) * (x zeta6 2) * (x + zeta6 + 1)2 sage S = M. cuspidal_s ubmodule() S Modular Symbols subspace of dimension 2 of Modular Symbols space of dimension 4 and level 13, weight 2, character zeta6, sign 0, over Cyclotomic Field of order 6 and degree 2 sage S. T(2). charpoly(x). factor() (x + zeta6 + 1)2 sage S. q_expansion_basis(10) q + (-zeta6 1)*q2 + (2*zeta6 2)*q3 + zeta6*q4 + (-2*zeta6 + 1)*q5 + (-2*zeta6 + 4)*q6 + (2*zeta6 1)*q8 zeta6*q9 + O(q10) Here is some other example of how Sage can compute the action of Hecke operators on a space of modular forms. sage T = ModularForms(Gamma0(11),2) sage T Modular Forms space of dimension 2 for Congruence Subgroup Gamma0(11) of weight 2 over Rational Field sage T. degree() 2 sage T. level() 11 sage T. group() Congruence Subgroup Gamma0(11) sage T. dimension() 2 sage T. cuspidal_subspace() Cuspidal subspace of dimension 1 of Modular Forms space of dimension 2 for Congruence Subgroup Gamma0(11) of weight 2 over Rational Field sage T. isenstein_subspace() Eisenstein subspace of dimension 1 of Modu lar Forms space of dimension 2 for Congruence Subgroup Gamma0(11) of weight 2 over Rational Field sage M = ModularSymbols(11) M Modular Symbols space of dimension 3 for Gamma_0(11) of weight 2 with sign 0 over Rational Field sage M. weight() 2 sage M. basis() ((1,0), (1,8), (1,9)) sage M. sign() 0 Let Tp announce the prevalent Hecke operators (p prime). How do the Hecke operators T2 , T3 , T5 act on the space of modular symbols? sage M. T(2). matrix() 3 0 -1 0 -2 0 0 0 -2 sage M. T(3). matrix() 4 0 -1 8 Chapter 2. A Guided Tour Sage Tutorial, Release 5. 3 0 -1 0 0 0 -1 sage M. T(5). matrix() 6 0 -1 0 1 0 0 0 1 2. 13. Some More Advanced Mathematics 49 Sage Tutorial, Release 5. 3 50 Chapter 2. A Guided Tour CHAPTER THREE THE INTERACTIVE SHELL In most of this tutorial, we assume you start the Sage interpreter using the sage ascendance. This starts a customized version of the IPython shell, and imports many functions and classes, so they are ready to use from the command prom pt. Further customization is possible by editing the $SAGE_ROOT/ipythonrc ? le.Upon starting Sage, you get outturn similar to the following SAGE Version 3. 1. 1, Release Date 2008-05-24 Type notebook() for the GUI, and license() for information. - sage To quit Sage either press Ctrl-D or type quit or exit. sage quit Exiting SAGE ( processor sequence 0m0. 00s, border eon 0m0. 89s) The wall measure is the era that elapsed on the measure hanging from your wall. This is relevant, since processor sentence does not track time used by subprocesses like GAP or Singular. Avoid killing a Sage process with kill -9 from a terminal, since Sage might not kill child processes, e. g. , Maple processes, or cleanup temporary ? les from $HOME/. sage/tmp. ) 3. 1 Your Sage Session The seance is the sequence of input and yield from when you start Sage until you quit. Sage logs all Sage input, via IPython. In fact, if youre using the interactive shell (not the notebook interface), then at a ny point you may type % bill (or %hist) to get a leaning of all input lines typed so far. You can type ? at the Sage prompt to ? nd out more about IPython, e. g. IPython offers numbered prompts with input and create caching. wholly input is rescue and can be retrieved as variables (besides the vulgar pointer key recall). The following GLOBAL variables always exist (so presumet overwrite them ) _ introductory input (interactive shell and notebook) __ next previous input (interactive shell only) _oh list of all inputs (interactive shell only) Here is an example sage factor(100) _1 = 22 * 52 sage kronecker_symbol(3,5) 51 Sage Tutorial, Release 5. 3 _2 = -1 sage %hist This only works from the interactive shell, not the notebook. factor(100) 2 kronecker_symbol(3,5) 3 %hist sage _oh _4 = 1 22 * 52, 2 -1 sage _i1 _5 = factor(ZZ(100)) sage eval(_i1) _6 = 22 * 52 sage %hist 1 factor(100) 2 kronecker_symbol(3,5) 3 %hist 4 _oh 5 _i1 6 eval(_i1) 7 %hist We omit the output numbering in the rest of this tutorial and the other Sage documentation. You can also store a list of input from academic session in a macro for that session. sage E = EllipticCurve(1,2,3,4,5) sage M = ModularSymbols(37) sage %hist 1 E = EllipticCurve(1,2,3,4,5) 2 M = ModularSymbols(37) 3 %hist sage %macro em 1-2 large em created.To execute, type its name (without quotes). sage E Elliptic Curve defined by y2 + x*y + 3*y = x3 + 2*x2 + 4*x + 5 over Rational Field sage E = 5 sage M = None sage em Executing Macro sage E Elliptic Curve defined by y2 + x*y + 3*y = x3 + 2*x2 + 4*x + 5 over Rational Field When using the interactive shell, any UNIX shell command can be executed from Sage by prefacing it by an exclamation point . For example, sage ls auto example. sage glossary. tex t tmp tut. log tut. tex returns the leaning of the current directory. The PATH has the Sage bin directory at the front, so if you run gp, gap, unmated, maxima, etc. you get the versions included with Sage. sage gp Re ading GPRC /etc/gprc Done. GP/PARI CALCULATOR Version 2. 2. 11 (alpha) i686 running linux (ix86/GMP-4. 1. 4 kernel) 32-bit version 52 Chapter 3. The Interactive Shell Sage Tutorial, Release 5. 3 sage singular SINGULAR A Computer Algebra System for Polynomial Computations 0 by G. -M. Greuel, G. Pfister, H. Schoenemann FB Mathematik der Universitaet, D-67653 Kaiserslautern October 2005 / / Development version 3-0-1 3. 2 Logging Input and Output Logging your Sage session is not the same as conservation it (see Saving and Loading Complete Sessions for that).To log input (and optionally output) use the logstart command. Type logstart? for more details. You can use this command to log all input you type, all output, and even play back that input in a hereafter session (by simply re essence the log ? le). emailprotected$ sage SAGE Version 3. 0. 2, Release Date 2008-05-24 Type notebook() for the GUI, and license() for information. sage logstart setup Activating auto-logging. Current session state plus future input saved.Filename setup musical mode backup Output logging False Timestamping False State active sage E = EllipticCurve(1,2,3,4,5). minimal_model() sage F = QQ3 sage x,y = QQx,y. gens() sage G = E. gens() sage Exiting SAGE ( mainframe computer time 0m0. 61s, debate time 0m50. 39s). emailprotected$ sage SAGE Version 3. 0. 2, Release Date 2008-05-24 Type notebook() for the GUI, and license() for information. sage load setup Loading log file one line at a timeFinished replaying log file sage E Elliptic Curve defined by y2 + x*y = x3 x2 + 4*x + 3 over Rational Field sage x*y x*y sage G (2 3 1) If you use Sage in the Linux KDE terminal konsole then you can save your session as follows after starting Sage in konsole, select settings, then history , then set unlimited. When you are ready to save your session, select edit then save history as and type in a name to save the text of your session to your computer. After saving(a) this ? le, you coul d then load it into an editor, such as xemacs, and print it. 3. 2. Logging Input and Output 53 Sage Tutorial, Release 5. 3 3. Paste Ignores Prompts think over you are reading a session of Sage or Python computations and want to copy them into Sage. But there are annoying or sage prompts to worry about. In fact, you can copy and paste an example, including the prompts if you want, into Sage. In other words, by default the Sage parser strips any leading or sage prompt before passing it to Python. For example, sage 210 1024 sage sage sage 210 1024 sage 210 1024 3. 4 Timing Commands If you place the %time command at the runner of an input line, the time the command takes to run will be displayed after the output.For example, we can compare the running time for a certain involvement operation in several ways. The timings below will probably be much different on your computer, or even between different versions of Sage. First, primordial Python sage %time a = int(1938)int(99484) CPU measure user 0. 66 s, sys 0. 00 s, total 0. 66 s breakwater time 0. 66 This means that 0. 66 seconds total were taken, and the Wall time, i. e. , the amount of time that elapsed on your wall clock, is also 0. 66 seconds. If your computer is heavy load up with other programs, the wall time may be much larger than the CPU time.Next we time exponentiation using the native Sage Integer type, which is implemented (in Cython) using the GMP library sage %time a = 193899484 CPU times user 0. 04 s, sys 0. 00 s, total 0. 04 s Wall time 0. 04 Using the PARI C-library interface sage %time a = pari(1938)pari(99484) CPU times user 0. 05 s, sys 0. 00 s, total 0. 05 s Wall time 0. 05 GMP is better, but only slightly (as expected, since the version of PARI built for Sage uses GMP for integer arithmetic). You can also time a block of commands using the cputime command, as illustrated below sage sage sage sage sage 0. 4 t = cputime() a = int(1938)int(99484) b = 193899484 c = pari(1938)pari(994 84) cputime(t) somewhat random output sage cputime? Return the time in CPU second since SAGE started, or with optional argument t, return the time since time t. 54 Chapter 3. The Interactive Shell Sage Tutorial, Release 5. 3 INPUT t (optional) float, time in CPU seconds OUTPUT float time in CPU seconds The walltime command brooks just like the cputime command, except that it measures wall time. We can also compute the supra power in some of the computer algebra systems that Sage includes.In each case we execute a trivial command in the system, in order to start up the server for that program. The most relevant time is the wall time. However, if there is a signi? cant loss between the wall time and the CPU time then this may indicate a performance issue worth looking into. sage time 193899484 CPU times user 0. 01 s, sys 0. 00 s, total Wall time 0. 01 sage gp(0) 0 sage time g = gp(193899484) CPU times user 0. 00 s, sys 0. 00 s, total Wall time 0. 04 sage maxima(0) 0 sage time g = maxima(193899484) CPU times user 0. 00 s, sys 0. 00 s, total Wall time 0. 0 sage kash(0) 0 sage time g = kash(193899484) CPU times user 0. 00 s, sys 0. 00 s, total Wall time 0. 04 sage mathematica(0) 0 sage time g = mathematica(193899484) CPU times user 0. 00 s, sys 0. 00 s, total Wall time 0. 03 sage maple(0) 0 sage time g = maple(193899484) CPU times user 0. 00 s, sys 0. 00 s, total Wall time 0. 11 sage gap(0) 0 sage time g = gap. eval(193899484) CPU times user 0. 00 s, sys 0. 00 s, total Wall time 1. 02 0. 01 s 0. 00 s 0. 00 s 0. 00 s 0. 00 s 0. 00 s 0. 00 s Note that GAP and Maxima are the slowest in this test (this was run on the work sage. ath. washington. edu). Because of the pexpect interface overhead, it is perhaps unfair to compare these to Sage, which is the fastest. 3. 5 Other IPython tricks As noted above, Sage uses IPython as its front end, and so you can use any of IPythons commands and features. You can read the full IPython documentation. Meanwhile, here are some fun tricks these are called Magic commands in IPython You can use %bg to run a command in the background, and then use jobs to access the results, as follows. 3. 5. Other IPython tricks 55 Sage Tutorial, Release 5. 3 The comments not tested are here because the %bg syntax doesnt work well with Sages automatic testing facility. If you type this in yourself, it should work as written. This is of course most multipurpose with commands which take a while to complete. ) sage def quick(m) return 2*m sage %bg quick(20) not tested Starting job 0 in a separate thread. sage jobs. status() not tested Completed jobs 0 quick(20) sage jobs0. result the developed answer, not tested 40 Note that jobs run in the background fathert use the Sage preparser see The Pre-Parser Differences between Sage and Python for more information.One (perhaps awkward) way to get around this would be to run sage %bg eval(preparse(quick(20))) not tested It is safer and easier, though, to just use %bg on comma nds which dont require the preparser. You can use %edit (or %ed or ed) to open an editor, if you want to type in some complex code. in the lead you start Sage, make sure that the EDITOR environment variable is set to your favorite editor (by putting export EDITOR=/usr/bin/emacs or export EDITOR=/usr/bin/vim or something similar in the appropriate place, like a . profile ? le). From the Sage prompt, executing %edit will open up the named editor. Then within the editor you can de? e a function def some_function(n) return n**2 + 3*n + 2 Save and quit from the editor. For the rest of your Sage session, you can then use some_function. If you want to modify it, type %edit some_function from the Sage prompt. If you have a computation and you want to modify its output for another use, perform the computation and type %rep this will place the output from the previous command at the Sage prompt, ready for you to edit it. sage f(x) = cos(x) sage f(x). derivative(x) -sin(x) At this point, if you type %rep at the Sage prompt, you will get a new Sage prompt, followed by -sin(x), with the cursor at the end of the line.For more, type %quickref to get a quick reference guide to IPython. As of this writing (April 2011), Sage uses version 0. 9. 1 of IPython, and the documentation for its conjuration commands is available online. 3. 6 Errors and Exceptions When something goes wrong, you will usually see a Python exception. Python even tries to suggest what raised the exception. Often you see the name of the exception, e. g. , NameError or ValueError (see the Python Reference Manual Py for a complete list of exceptions). For example, sage 3_2 File , line 1 ZZ(3)_2 SyntaxError incapacitate syntax 6 Chapter 3. The Interactive Shell Sage Tutorial, Release 5. 3 sage EllipticCurve(0,infinity) Traceback (most recent call last) TypeError inefficient to coerce Infinity () to Rational The interactive debugger is sometimes useful for understanding what went wrong. You can toggle it o n or off using %pdb (the default is off). The prompt ipdb appears if an exception is raised and the debugger is on. From within the debugger, you can print the state of any local variable, and move up and down the execution muckle.For example, sage %pdb Automatic pdb calling has been turned ON sage EllipticCurve(1,infinity) Traceback (most recent call last) ipdb For a list of commands in the debugger, type ? at the ipdb prompt ipdb ? authenticated commands (type help ) ======================================== EOF break commands debug h a bt condition hamper help alias c cont down ignore args cl hold open enable j b clear d exit skip whatis where Miscellaneous help topics ========================== exec pdb Undocumented commands ====================== retval rv list n next p pdef pdoc pinfo pp q quit r return s step tbreak u unalias up w Type Ctrl-D or quit to return to Sage. 3. 7 Reverse Search and Tab Completion Reverse search Type the beginning of a command, then Ctrl-p (or just hit the up arrow key) to go back to each line you have entered that begins in that way. This works even if you completely exit Sage and restart later. You can also do a reverse search through the history using Ctrl-r. All these features use the readline package, which is available on most ? avors of Linux. To illustrate tab completion, ? st create the three dimensional vector space V = Q3 as follows sage V = vectorSpace(QQ,3) sage V Vector space of dimension 3 over Rational Field You can also use the following more concise notation 3. 7. Reverse Search and Tab Completion 57 Sage Tutorial, Release 5. 3 sage V = QQ3 Then it is easy to list all member functions for V using tab completion. Just type V. , then type the tab key key on your keyboard sage V. tab key V. _VectorSpace_generic__base_field V. ambient_space V. base_field V. base_ring V. basis V. coordinates V. zero_vector If you type the ? st few letters of a function, then tab key, you get only functions that begin as indi cated. sage V. itab key V. is_ambient V. is_dense V. is_full V. is_sparse If you marvel what a particular function does, e. g. , the coordinates function, type V. coordinates? for help or V. coordinates for the source code, as ex unequivocaled in the next section. 3. 8 Integrated Help System Sage features an integrated help facility. Type a function name followed by ? for the documentation for that function. sage V = QQ3 sage V. coordinates? Type instancemethod Base Class String Form Namespace Interactive File / interior(a)/was/s/local/lib/python2. /site-packages/sage/modules/f ree_module. py Definition V. coordinates(self, v) Docstring Write v in call of the basis for self. Returns a list c such that if B is the basis for self, then sum c_i B_i = v. If v is not in self, raises an ArithmeticError exception. EXAMPLES sage M = FreeModule(IntegerRing(), 2) M0,M1=M. gens() sage W = M. submodule(M0 + M1, M0 2*M1) sage W. coordinates(2*M0-M1) 2, -1 As shown above, the output tells you the type of the object, the ? le in which it is de? ned, and a useful explanation of the function with examples that you can paste into your current session. about all of these examples are regularly automatically tested to make sure they work and behave exactly as claimed. 58 Chapter 3. The Interactive Shell Sage Tutorial, Release 5. 3 Another feature that is very much in the expression of the open source nature of Sage is that if f is a Python function, then type f displays the source code that de? nes f. For example, sage V = QQ3 sage V. coordinates Type instancemethod Source def coordinates(self, v) Write $v$ in terms of the basis for self. return self. coordinate_vector(v). list()This tells us that all the coordinates function does is call the coordinate_vector function and change the result into a list. What does the coordinate_vector function do? sage V = QQ3 sage V. coordinate_vector def coordinate_vector(self, v) return self. ambient_vector_space()(v) The coordinate_ve ctor function coerces its input into the ambient space, which has the offspring of computing the vector of coef? cients of v in terms of V . The space V is already ambient since its just Q3 . There is also a coordinate_vector function for subspaces, and its different.We create a subspace and see sage V = QQ3 W = V. span_of_basis(V. 0, V. 1) sage W. coordinate_vector def coordinate_vector(self, v) First find the coordinates of v wrt echelon basis. w = self. echelon_coordinate_vector(v) Next use transformation matrix from echelon basis to user basis. T = self. echelon_to_user_matrix() return T. linear_combination_of_rows(w) (If you think the implementation is inef? cient, please sign up to help optimize linear algebra. ) You may also type help(command_name) or help(class) for a manpage-like help ? le about a given class. age help(VectorSpace) Help on class VectorSpace class VectorSpace(__builtin__. object) Create a Vector Space. To create an ambient space over a field with gi ven dimension using the calling syntax When you type q to exit the help system, your session appears just as it was. The help listing does not welter up your session, unlike the output of function_name? sometimes does. Its particularly instrumental to type 3. 8. Integrated Help System 59 Sage Tutorial, Release 5. 3 help(module_name). For example, vector spaces are de? ned in sage. modules. free_module, so type help(sage. modules. ree_module) for documentation about that whole module. When viewing documentation using help, you can search by typing / and in reverse by typing ?. 3. 9 Saving and Loading Individual Objects Suppose you compute a matrix or worse, a complicated space of modular symbols, and would like to save it for later use. What can you do? There are several approaches that computer algebra systems take to saving individual objects. 1. Save your Game Only support saving and loading of complete sessions (e. g. , GAP, Magma). 2. Uni? ed Input/Output Make every object print in a way that can be read back in (GP/PARI). 3.Eval Make it easy to evaluate arbitrary code in the interpreter (e. g. , Singular, PARI). Because Sage uses Python, it takes a different approach, which is that every object can be serialized, i. e. , turned into a string from which that object can be recovered. This is in spirit similar to the uni? ed I/O approach of PARI, except it doesnt have the drawback that objects print to screen in too complicated of a way. Also, support for saving and loading is (in most cases) completely automatic, requiring no extra programming its simply a feature of Python that was designed into the language from the ground up.Almost all Sage objects x can be saved in compressed form to disk using save(x, filename) (or in many cases x. save(filename)). To load the object back in, use load(filename). sage sage 15 42 69 sage A = MatrixSpace(QQ,3)(range(9))2 A 18 21 54 66 90 111 save(A, A) You should now quit Sage and restart. Then you can get A back sage sage 15 42 69 A = load(A) A 18 21 54 66 90 111 You can do the same with more complicated objects, e. g. , elliptic curves. All data about the object that is cached is stored with the object. For example, sage sage sage sage E = EllipticCurve(11a) v = E. nlist(100000) save(E, E) quit takes a while The saved version of E takes 153 kilobytes, since it stores the ? rst 100000 an with it. /tmp$ ls -l E. sobj -rw-rr 1 was was 153500 2006-01-28 1923 E. sobj /tmp$ sage sage E = load(E) sage v = E. anlist(100000) present moment (In Python, saving and loading is accomplished using the cPickle module. In particular, a Sage object x can be saved via cPickle. dumps(x, 2). Note the 2 ) 60 Chapter 3. The Interactive Shell Sage Tutorial, Release 5. 3 Sage cannot save and load individual objects created in some other computer algebra systems, e. . , GAP, Singular, Maxima, etc. They reload in a state marked invalid. In GAP, though many objects print in a form from which they can be reco nstructed, many dont, so reconstructing from their print office is purposely not allowed. sage a = gap(2) sage a. save(a) sage load(a) Traceback (most recent call last) ValueError The session in which this object was defined is no womb-to-tomb running. GP/PARI objects can be saved and loaded since their print representation is enough to reconstruct them. sage a = gp(2) sage a. save(a) sage load(a) 2Saved objects can be re-loaded later on computers with different architectures or operating systems, e. g. , you could save a huge matrix on 32-bit OS X and reload it on 64-bit Linux, ? nd the echelon form, then move it back. Also, in many cases you can even load objects into versions of Sage that are different than the versions they were saved in, as long as the code for that object isnt too different. All the attributes of the objects are saved, along with the class (but not source code) that de? nes the object. If that class no longer exists in a new version of Sage, then the object cant be reloaded in that newer version.But you could load it in an old version, get the objects dictionary (with x. __dict__), and save the dictionary, and load that into the newer version. 3. 9. 1 Saving as Text You can also save the ASCII text representation of objects to a plain text ? le by simply opening a ? le in write mode and writing the string representation of the object (you can write many objects this way as well). When youre done writing objects, close the ? le. sage sage sage sage sage R. = PolynomialRing(QQ,2) f = (x+y)7 o = open(file. txt,w) o. write(str(f)) o. close() 3. 10 Saving and Loading Complete Sessions Sage has very ? xible support for saving and loading complete sessions. The command save_session(sessionname) saves all the variables youve de? ned in the current session as a dictionary in the given sessionname. (In the rare case when a variable does not support saving, it is simply not saved to the dictionary. ) The resulting ? le is an . sobj ? le and can be loaded just like any other object that was saved. When you load the objects saved in a session, you get a dictionary whose keys are the variables names and whose values are the objects. You can use the load_session(sessionname) command to load the variables de? ed in sessionname into the current session. Note that this does not wipe out variables youve already de? ned in your current session instead, the twain sessions are merged. First we start Sage and de? ne some variables. 3. 10. Saving and Loading Complete Sessions 61 Sage Tutorial, Release 5. 3 sage sage sage sage _4 = E = EllipticCurve(11a) M = ModularSymbols(37) a = 389 t = M. T(2003). matrix() t. charpoly(). factor() (x 2004) * (x 12)2 * (x + 54)2 Next we save our session, which saves each of the above variables into a ? le. Then we view the ? le, which is about 3K in size. age save_session(misc) Saving a Saving M Saving t Saving E sage quit emailprotected/tmp$ ls -l misc. sobj -rw-rr 1 was was 2979 2006-01-28 1947 mi sc. sobj last we restart Sage, de? ne an extra variable, and load our saved session. sage b = 19 sage load_session(misc) Loading a Loading M Loading E Loading t Each saved variable is once more available. Moreover, the variable b was not overwritten. sage M Full Modular Symbols space for Gamma_0(37) of weight 2 with sign 0 and dimension 5 over Rational Field sage E Elliptic Curve defined by y2 + y = x3 x2 10*x 20 over Rational Field sage b 19 sage a 389 3. 1 The Notebook Interface The Sage notebook is run by typing sage notebook() on the command line of Sage. This starts the Sage notebook and opens your default web browser to view it. The servers state ? les are stored in $HOME/. sage/sage_notebook. Other options include sage notebook(directory) which starts a new notebook server using ? les in the given directory, instead of the default directory $HOME/. sage/sage_notebook. This can be useful if you want to have a collection of worksheets associated with a speci? c project, or run several separate notebook servers at the same time. When you start the notebook, it ? st creates the following ? les in $HOME/. sage/sage_notebook 62 Chapter 3. The Interactive Shell Sage Tutorial, Release 5. 3 nb. sobj objects/ worksheets/ (the notebook SAGE object file) (a directory containing SAGE objects) (a directory containing SAGE worksheets). After creating the above ? les, the notebook starts a web server. A notebook is a collection of user accounts, each of which can have any number of worksheets. When you create a new worksheet, the data that de? nes it is stored in the worksheets/username/number directories. In each such directory there is a plain text ? le worksheet. xt if anything ever happens to your worksheets, or Sage, or whatever, that human-readable ? le contains everything needed to reconstruct your worksheet. From within Sage, type notebook? for much more about how to start a notebook server. The following diagram illustrates the architecture of the Sage No tebook firefox/safari javascript program AJAX V sage web server pexpect - SAGE process 1 SAGE process 2 SAGE process 3 (Python processes)For help on a Sage command, cmd, in the notebook browser box, type cmd? ). and now hit (not For help on the keyboard shortcuts available in the notebook interface, click on the Help link. 3. 11. The Notebook Interface 63 Sage Tutorial, Release 5. 3 64 Chapter 3. The Interactive Shell CHAPTER FOUR INTERFACES A central facet of Sage is that it supports computation with objects in many different computer algebra systems under one roof using a common interface and clean programming language. The console and interact methods of an interface do very different things. For example, using GAP as an example 1. gap. onsole() This opens the GAP console it transfers control to GAP. Here Sage is serving as nothing more than a well-provided program launcher, similar to the Linux bash shell. 2. gap. interact() This is a convenie nt way to interact with a running GAP instance that may be full of Sage objects. You can import Sage objects into this GAP session (even from the interactive interface), etc. 4. 1 GP/PARI PARI is a compact, very mature, highly optimized C program whose primary focus is number theory. There are ii very distinct interfaces that you can use in Sage gp the G o P ARI interpreter, and pari the PARI C libraxry.For example, the following are two ways of doing the same thing. They look identical, but the output is actually different, and what happens fag the scenes is drastically different. sage gp(znprimroot(10007)) Mod(5, 10007) sage pari(znprimroot(10007)) Mod(5, 10007) In the ? rst case, a separate copy of the GP interpreter is started as a server, and the string znprimroot(10007) is sent to it, evaluated by GP, and the result is assigned to a variable in GP (which takes up space in the child GP processes memory that wont be freed). Then the value of that variable is displayed.In t he second case, no separate program is started, and the string znprimroot(10007) is evaluated by a certain PARI C library function. The result is stored in a piece of memory on the Python heap, which is freed when the variable is no longer referenced. The objects have different types sage type(gp(znprimroot(10007))) sage type(pari(znprimroot(10007))) So which should you use? It depends on what youre doing. The GP interface can do absolutely anything you could do in the usual GP/PARI command line program, since it is running that program. In particular, you can load complicated PARI programs and run them.In contrast, the PARI interface (via the C library) is much more restrictive. First, not all 65 Sage Tutorial, Release 5. 3 member functions have been implemented. Second, a lot of code, e. g. , involving numerical integration, wont work via the PARI interface. That said, the PARI interface can be signi? cantly faster and more robust than the GP one. (If the GP interface runs out of memory evaluating a given input line, it will wordlessly and automatically double the stack size and retry that input line. thusly your computation wont crash if you didnt correctly yell the amount of memory that would be needed.This is a nice trick the usual GP interpreter doesnt seem to provide. Regarding the PARI C library interface, it promptly copies each created object off of the PARI stack, hence the stack never grows. However, each object must not exceed 100MB in size, or the stack will over? ow when the object is being created. This extra copying does inflict a slight performance penalty. ) In summary, Sage uses the PARI C library to provide functionality similar to that provided by the GP/PARI interpreter, except with different school memory management and the Python programming language. First we create a PARI list from a Python list. age v = pari(1,2,3,4,5) sage v 1, 2, 3, 4, 5 sage type(v) all PARI object is of type py_pari. gen. The PARI type of the underlying o bject can be obtained using the type member function. sage v. type() t_VEC In PARI, to create an elliptic curve we enter ellinit(1,2,3,4,5). Sage is similar, except that ellinit is a method that can be called on any PARI object, e. g. , our t_VEC v. sage e = v. ellinit() sage e. type() t_VEC sage pari(e)13 1, 2, 3, 4, 5, 9, 11, 29, 35, -183, -3429, -10351, 6128487/10351 Now that we have an elliptic curve object, we can compute some things about it. age e. elltors() 1, , sage e. ellglobalred() 10351, 1, -1, 0, -1, 1 sage f = e. ellchangecurve(1,-1,0,-1) sage f5 1, -1, 0, 4, 3 4. 2 GAP Sage comes with GAP 4. 4. 10 for computational separate mathematics, especially group theory. Heres an example of GAPs IdGroup function, which uses the optional small groups database that has to be installed separately, as explained below. sage G = gap(Group((1,2,3)(4,5), (3,4))) sage G Group( (1,2,3)(4,5), (3,4) ) sage G. Center() Group( () ) 66 Chapter 4. Interfaces Sage Tutorial, Release 5. 3 sag e G.IdGroup() 120, 34 sage G. Order() 120 requires optional database_gap package We can do the same computation in Sage without explicitly invoking the GAP interface as follows sage G = PermutationGroup((1,2,3),(4,5),(3,4)) sage G. center() Subgroup of (Permutation Group with generators (3,4), (1,2,3)(4,5)) generated by () sage G. group_id() requires optional database_gap package 120, 34 sage n = G. order() n 120 (For some GAP functionality, you should install two optional Sage packages. Type sage -optional for a list and choose the one that looks like gap_packages-x. . z, then type sage -i gap_packages-x. y. z. Do the same for database_gap-x. y. z. Some non-GPLd GAP packages may be installed by downloading them from the GAP web site GAPkg, and unpacking them in $SAGE_ROOT/local/lib/gap-4. 4. 10/pkg. ) 4. 3 Singular Singular provides a massive and mature library for Grobner bases, multivariate polynomial gcds, bases of RiemannRoch spaces of a flavourless curve, and factorizatio ns, among other things. We illustrate multivariate polynomial factorization using the Sage interface to Singular (do not type the ) sage R1 = singular. ing(0, (x,y), dp) sage R1 // characteristic 0 // number of vars 2 // block 1 guild dp // names x y // block 2 club C sage f = singular(9*y8 9*x2*y7 18*x3*y6 18*x5*y6 + 9*x6*y4 + 18*x7*y5 + 36*x8*y4 + 9*x10*y4 18*x11*y2 9*x12*y3 18*x13*y2 + 9*x16) Now that we have de? ned f , we print it and factor. sage f 9*x16-18*x13*y2-9*x12*y3+9*x10*y4-18*x11*y2+36*x8*y4+18*x7*y5-18*x5*y6+9*x6*y4-18*x sage f. parent() Singular sage F = f. factorize() F 1 _1=9 _2=x6-2*x3*y2-x2*y3+y4 _3=-x5+y2 2 1,1,2 sage F12 x6-2*x3*y2-x2*y3+y4As with the GAP example in GAP, we can compute the above factorization without explicitly using the Singular interface (however, behind the scenes Sage uses the Singular interface for the actual computation). Do not type the 4. 3. Singular 67 Sage Tutorial, Release 5. 3 sage sage sage (9) * x, y = QQx, y. gens( ) f = 9*y8 9*x2*y7 18*x3*y6 18*x5*y6 + 9*x6*y4 + 18*x7*y5 + 36*x8*y4 + 9*x10*y4 18*x11*y2 9*x12*y3 18*x13*y2 + 9*x16 factor(f) (-x5 + y2)2 * (x6 2*x3*y2 x2*y3 + y4) 4. 4 Maxima Maxima is included with Sage, as well as a Lisp implementation.The gnuplot package (which Maxima uses by default for plotting) is distributed as a Sage optional package. Among other things, Maxima does symbolic manipulation. Maxima can integrate and differentiate functions symbolically, solve 1st order ODEs, most linear 2nd order ODEs, and has implemented the Laplace tr

No comments:

Post a Comment