Ticket #839: sage839referee1.patch
File sage839referee1.patch, 44.9 KB (added by , 13 years ago) 


sage/interfaces/expect.py
# HG changeset patch # User William Stein <wstein@gmail.com> # Date 1208668384 25200 # Node ID e53b80ecaab12380cd2055a5600cf4ccce8c40e1 # Parent dff3e5df5ef8ff029535a01cc30ef1f2e45dd6f0 Refereeing trac #839  made a ton of little changes polishing up the documentation and hopefully increasing robustness. diff r dff3e5df5ef8 r e53b80ecaab1 sage/interfaces/expect.py
a b class Expect(ParentWithBase): 283 283 # os.makedirs(T) 284 284 # return T + str(x) 285 285 286 def name(self ):286 def name(self, new_name=None): 287 287 return self.__name 288 288 289 289 def path(self): 
sage/interfaces/r.py
diff r dff3e5df5ef8 r e53b80ecaab1 sage/interfaces/r.py
a b AUTHORS: 204 204 205 205 from keyword import iskeyword 206 206 from expect import Expect, ExpectElement, ExpectFunction, FunctionElement 207 from sage.misc.misc import DOT_SAGE 207 from sage.misc.misc import DOT_SAGE, UNAME 208 from sage.misc.latex import LatexExpr 208 209 import pexpect 209 210 from random import randrange 210 211 import re 211 212 import sage.rings.integer 212 213 213 214 COMMANDS_CACHE = '%s/r_commandlist.sobj'%DOT_SAGE 214 PROMPT = ' ObFuSc4t3dpR0mp7> '215 PROMPT = '__SAGE__R__PROMPT__> ' 215 216 prompt_re = re.compile("^>", re.M) 216 217 217 218 #there is a mirror network, but lets take #1 for now … … RBaseCommands = ['c', "NULL", "NA", "Tru 223 224 RBaseCommands = ['c', "NULL", "NA", "True", "False", "Inf", "NaN"] 224 225 225 226 class R(Expect): 226 """227 R is a comprehensive collection of methods for statistics,228 modelling, bioinformatics, data analysis and much more.229 Coninues here: http://www.rproject.org/about.html230 231 Resources:232 * http://rproject.org/ provides more information about R.233 * http://rseek.org/ R's own search engine.234 235 EXAMPLES:236 sage: r.summary(r.c(1,2,3,111,2,3,2,3,2,5,4))237 Min. 1st Qu. Median Mean 3rd Qu. Max.238 1.00 2.00 3.00 12.55 3.50 111.00239 240 """241 227 def __init__(self, 242 228 maxread=100000, script_subdirectory=None, 243 229 server_tmpdir = None, … … class R(Expect): 245 231 server=None, 246 232 init_list_length=1024): 247 233 """ 234 An interface to the R interpreter. 235 236 R is a comprehensive collection of methods for statistics, 237 modelling, bioinformatics, data analysis and much more. 238 For more details, see http://www.rproject.org/about.html 239 240 Resources: 241 * http://rproject.org/ provides more information about R. 242 * http://rseek.org/ R's own search engine. 243 244 EXAMPLES: 245 sage: r.summary(r.c(1,2,3,111,2,3,2,3,2,5,4)) 246 Min. 1st Qu. Median Mean 3rd Qu. Max. 247 1.00 2.00 3.00 12.55 3.50 111.00 248 248 249 TESTS: 249 250 sage: r == loads(dumps(r)) 250 251 True 251 252 252 """ 253 253 Expect.__init__(self, 254 254 … … class R(Expect): 294 294 def _start(self): 295 295 """ 296 296 Start up the R interpreter and sets the initial prompt and options. 297 298 This is called the first time the R interface is actually used. 299 300 EXAMPLES: 301 sage: r = R() 302 sage: r._start() 297 303 """ 298 304 Expect._start(self) 299 305 … … class R(Expect): 318 324 to call r.dev_off() in the same cell as you opened the device on in order 319 325 to get the plot to appear. 320 326 321 322 327 EXAMPLES: 323 328 sage: filename = tmp_filename() + '.png' 324 329 sage: r.png(file='"%s"'%filename) … … class R(Expect): 331 336 null device 332 337 1 333 338 sage: import os; os.unlink(filename) 334 335 339 """ 336 340 from sage.server.support import EMBEDDED_MODE 337 341 if EMBEDDED_MODE: … … class R(Expect): 354 358 'package:methods', 355 359 'Autoloads', 356 360 'package:base'] 357 358 361 """ 359 362 pl = [] 360 363 l = "".join(l.split("\n")) … … class R(Expect): 365 368 366 369 def install_packages(self, package_name): 367 370 """ 368 Returns help on how to install R packages inSage's R installation.371 Install an R package into Sage's R installation. 369 372 370 373 EXAMPLES: 371 sage: r.install_packages('Hmisc') #optional requires internet random 372 ... 374 sage: r.install_package('Hmisc') # optional requires internet 375 [1] 4 5 6 376 """ 377 if UNAME == "Darwin": 378 warn = "** You are using OS X. Unfortunately, the R optional package system currently doesn't support OS X very well. We are working on this. **" 379 else: 380 warn = None 381 if warn is not None: print warn 373 382 374 """ 375 s = r.eval('install.packages("%s")'%package_name) 376 print s 383 cmd = """options(repos="%s"); install.packages("%s")"""%(RRepositoryURL, package_name) 384 os.system("time echo '%s'  R vanilla"%cmd) 385 print "Please restart Sage or restart the the R interface (via r.restart()) in order to use '%s'."%package_name 386 387 if warn is not None: print warn 388 #s = r.eval('install.packages("%s")'%package_name) 389 #print s 377 390 378 391 def __repr__(self): 379 392 """ 393 Return string representation of this R interface. 394 380 395 EXAMPLES: 381 396 sage: r.__repr__() 382 397 'R Interpreter' … … class R(Expect): 385 400 386 401 def __reduce__(self): 387 402 """ 403 Used in serializing an R interface. 404 388 405 EXAMPLES: 389 406 sage: rlr, t = r.__reduce__() 390 407 sage: rlr(*t) … … class R(Expect): 394 411 395 412 def __getattr__(self, attrname): 396 413 """ 414 Called when you get an attribute of the R interface. This 415 manufactures an R function, which is a Python function that 416 can then be called with various inputs. 417 397 418 EXAMPLES: 398 419 sage: c = r.c; c 399 420 c … … class R(Expect): 407 428 408 429 def _quit_string(self): 409 430 """ 431 Return the string that when typed into R causes the R 432 interpreter to exit. 433 410 434 EXMAPLES: 411 435 sage: r._quit_string() 412 436 'quit(save="no")' … … class R(Expect): 444 468 """ 445 469 EXAMPLES: 446 470 sage: print r._install_hints() 447 R is currently installed with Sage. 448 471 R is currently installed with Sage. 449 472 """ 450 473 return "R is currently installed with Sage.\n" 451 474 452 475 def _source(self, s): 453 476 """ 454 Returns the source code of a R function as a string.477 Returns the source code of an R function as a string. 455 478 456 479 INPUT: 457 480 s  the name of the function as a string … … class R(Expect): 460 483 sage: print r._source("print.anova") 461 484 function (x, digits = max(getOption("digits")  2, 3), signif.stars = getOption("show.signif.stars"), 462 485 ... 463 464 486 """ 465 487 if s[2:] == "()": 466 488 s = s[2:] … … class R(Expect): 468 490 469 491 def source(self, s): 470 492 """ 471 Display the R source (if possible) about s.493 Display the R source (if possible) about the function named s. 472 494 495 INPUT: 496 s  a string representing the function whose source code you want to see 497 OUTPUT: 498 string  source code 499 473 500 EXAMPLES: 474 501 sage: print r.source("print.anova") 475 502 function (x, digits = max(getOption("digits")  2, 3), signif.stars = getOption("show.signif.stars"), 476 503 ... 477 478 INPUT:479 s  a string representing the function whose source code you480 want481 504 """ 482 505 return self._source(s) 483 506 484 507 def version(self): 485 508 """ 486 509 Returns the version of R currently running. 510 511 OUTPUT: 512 tuple of ints; string 487 513 488 514 EXAMPLES: 489 515 sage: r.version() … … class R(Expect): 501 527 502 528 return ( (major,) + minor, version_string ) 503 529 504 def library(self, l):530 def library(self, library_name): 505 531 """ 506 Loads a library into the R interpreter. 532 Load the library library_name into the R interpreter. 533 534 This function raises an ImportError if the given library 535 is not known. 536 537 INPUT: 538 library_name  string 507 539 508 540 EXAMPLES: 509 541 sage: r.library('grid') 510 542 sage: 'grid' in r.eval('(.packages())') 511 543 True 544 sage: r.library('foobar') 545 Traceback (most recent call last): 546 ... 547 ImportError: there is no package called 'foobar' 512 548 """ 513 success = self.eval('require("%s")'%l)514 if not success:515 print "Could not load library %s"%l549 ret = self.eval('require("%s")'%library_name) 550 if 'there is no package' in ret: 551 raise ImportError, "there is no package called '%s'"%library_name 516 552 else: 517 553 try: 518 # we need to rebuild keywords!554 # We need to rebuild keywords! 519 555 del self.__trait_names 520 556 except AttributeError: 521 557 pass 522 self.trait_names(verbose=False )558 self.trait_names(verbose=False, use_disk_cache=False) 523 559 524 560 require = library #overwrites require 525 561 526 562 def available_packages(self): 527 563 """ 528 Returns a list of available packages where each entry in the list is of 529 the form ["package name", "version"]. 564 Returns a list of all available R package names. 565 566 This list is not necessarily sorted. 567 568 OUTPUT: 569 list of strings 530 570 531 571 NOTE: 532 572 This requires an internet connection. The CRAN server is 533 573 that is checked is defined at the top of sage/interfaces/r.py. 534 574 535 575 EXAMPLES: 536 sage: ap = r.available_packages() #optional requires internet connection 537 sage: ap[:3] #optional 538 [['ADaCGH', '1.0'], ['AIS', '0.211'], ['AMORE', '1.23']] 539 576 sage: ap = r.available_packages() # optional requires internet connection 577 sage: ap[:3] # optional 578 ['aaMI', 'abind', 'AcceptanceSampling'] 540 579 """ 541 580 p = self.new('available.packages("%s/src/contrib")'%RRepositoryURL) 542 if p: 543 p = p._sage_() 544 s = p['_Dim'][0] 545 l = [[p['DATA'][i],p['DATA'][s+1+i]] for i in xrange(0,s)] 546 return l 547 else: 548 return [] 581 s = str(p).splitlines()[1:] 582 v = [x.split()[0].strip("'") for x in s] 583 return v 584 # The following was more structural, but breaks on my machine. (stein) 585 ## p = p._sage_() 586 ## s = p['_Dim'][0] 587 ## l = [[p['DATA'][i],p['DATA'][s+1+i]] for i in xrange(0,s)] 588 ## return l 549 589 550 590 def _object_class(self): 551 591 """ 592 Return the underlying class of elements of the R interface object. 593 594 OUTPUT: 595 a Python class 596 552 597 EXAMPLES: 553 598 sage: r._object_class() 554 599 <class 'sage.interfaces.r.RElement'> … … class R(Expect): 557 602 558 603 def _true_symbol(self): 559 604 """ 605 Return the symbol that represents True in R. 606 607 OUTPUT: 608 string 609 560 610 EXAMPLES: 561 611 sage: r._true_symbol() 562 612 '[1] TRUE' 613 614 This is used behinds the scenes to implement comparison: 615 sage: r('1') == r('1') 616 [1] TRUE 617 sage: r('1') == r('2') 618 [1] FALSE 563 619 """ 564 620 # return the string rep of truth, i.e., what the system outputs 565 621 # when you type 1==1. … … class R(Expect): 567 623 568 624 def _false_symbol(self): 569 625 """ 626 Return the symbol that represents True in R. 627 628 OUTPUT: 629 string 630 570 631 EXAMPLES: 571 632 sage: r._false_symbol() 572 633 '[1] FALSE' 573 634 """ 574 # return the string rep of truth, i.e., what the system outputs635 # return the string rep of false, i.e., what the system outputs 575 636 # when you type 1==2. 576 637 return "[1] FALSE" 577 638 … … class R(Expect): 586 647 587 648 def help(self, command): 588 649 """ 589 Returns help on for a given command. 650 Returns help string for a given command. 651 652 INPUT: 653 command  a string 654 655 OUTPUT: 656 HelpExpression  a subclass of string whose __repr__ 657 method is __str__, so it prints nicely 590 658 591 659 EXAMPLES: 592 sage: s = r.help('print.anova').split("\n") 593 sage: print "\n".join(s[:8]) 660 sage: r.help('print.anova') 594 661 anova package:stats R Documentation 595 662 ... 596 Compute analysis of variance (or deviance) tables for one or more 597 fitted model objects. 663 'coefficients', 'effects', 'fitted.values', 'residuals', 664 'summary', 'drop1', 'add1'. 665 666 NOTE: 667 This is similar to typing r.command?. 598 668 """ 599 return self.eval('help("%s")'%command) #?cmd is only an unsafe shortcut 669 s = self.eval('help("%s")'%command) # ?cmd is only an unsafe shortcut 670 return HelpExpression(s.strip()) 600 671 601 672 def _assign_symbol(self): 602 673 """ 674 Return the symbol used in R for assignment, which is ' < '. 675 676 OUTPUT: 677 string 678 603 679 EXAMPLES: 604 680 sage: r._assign_symbol() 605 681 ' < ' … … class R(Expect): 608 684 609 685 def _left_list_delim(self): 610 686 """ 687 Return the left delimiter for lists in R, which is 'c(' 688 689 OUTPUT: 690 string 691 611 692 EXAMPLES: 612 693 sage: r._left_list_delim() 613 694 'c(' … … class R(Expect): 616 697 617 698 def _right_list_delim(self): 618 699 """ 700 Return the right delimiter for lists in R, which is 'c(' 701 702 OUTPUT: 703 string 704 619 705 EXAMPLES: 620 706 sage: r._right_list_delim() 621 707 ')' … … class R(Expect): 624 710 625 711 def console(self): 626 712 """ 627 Runs the R console. 713 Runs the R console as a separate new R process. 714 715 sage: r.console() # not tested 716 R version 2.6.1 (20071126) 717 Copyright (C) 2007 The R Foundation for Statistical Computing 718 ISBN 3900051070 719 ... 628 720 """ 629 721 r_console() 630 722 631 723 def function_call(self, function, args=None, kwargs=None): 632 724 """ 725 Return the result of calling an R function, with given args and keyword args. 726 727 OUTPUT: 728 RElement  an object in R 729 633 730 EXAMPLES: 634 731 sage: r.function_call('length', args=[ [1,2,3] ]) 635 732 [1] 3 636 637 733 """ 638 734 if args is None: 639 735 args = [] … … class R(Expect): 659 755 return self.new("%s(%s)"%(function, ",".join([s.name() for s in args] + [self._sage_to_r_name(key)+'='+kwargs[key].name() for key in kwargs ] ))) 660 756 661 757 def call(self, function_name, *args, **kwargs): 662 """ 758 r""" 759 This is an alias for \code{self.function_call}. 760 663 761 EXAMPLES: 664 762 sage: r.call('length', [1,2,3]) 665 763 [1] 3 … … class R(Expect): 671 769 Returns an element belonging to the R interpreter. This is used 672 770 behind the scenes when doing things like comparisons, etc. 673 771 772 OUTPUT: 773 RElement  an R element. 774 674 775 EXAMPLES: 675 776 sage: r._an_element_impl() 676 777 [1] 0 … … class R(Expect): 681 782 682 783 def set(self, var, value): 683 784 """ 684 Set the variable var to the given value. 785 Set the variable var in R to what the string value evaluates to in R. 786 787 INPUT: 788 var  a string 789 value  a string 685 790 686 791 EXAMPLES: 687 sage: r.set('a', 2)792 sage: r.set('a', '2 + 3') 688 793 sage: r.get('a') 689 '[1] 2'794 '[1] 5' 690 795 """ 691 796 cmd = '%s < %s'%(var,value) 692 797 out = self.eval(cmd) … … class R(Expect): 695 800 696 801 def get(self, var): 697 802 """ 698 Returns the value of the variable var. 803 Returns the string representation of the variable var. 804 805 INPUT: 806 var  a string 807 808 OUTPUT: 809 string 699 810 700 811 EXAMPLES: 701 812 sage: r.set('a', 2) … … class R(Expect): 710 821 """ 711 822 Returns the NA in R. 712 823 824 OUTPUT: 825 RElement  an element of R 826 713 827 EXAMPLES: 714 828 sage: r.na() 715 829 [1] NA … … class R(Expect): 718 832 719 833 def completions(self, s): 720 834 """ 721 Return all commands that complete the command starting with the835 Return all commands names that complete the command starting with the 722 836 string s. This is like typing s[CtrlT] in the R interpreter. 837 838 INPUT: 839 s  string 840 841 OUTPUT: 842 list  a list of strings 723 843 724 844 EXAMPLES: 725 845 sage: r.completions('tes') … … class R(Expect): 730 850 def _commands(self): 731 851 """ 732 852 Return list of all commands defined in R. 853 854 OUTPUT: 855 list  a sorted list of strings 733 856 734 857 EXAMPLES: 735 858 sage: l = r._commands() … … class R(Expect): 772 895 773 896 def trait_names(self, verbose=True, use_disk_cache=True): 774 897 """ 898 Return list of all R functions. 899 900 INPUT: 901 verbose  bool (default: True); if True, display debugging information 902 use_disk_cache  bool (default: True); if True, use the disk cache of 903 trait names to save time. 904 OUTPUT: 905 list  list of string 906 775 907 EXAMPLES: 776 908 sage: t = r.trait_names(verbose=False) 777 909 sage: len(t) > 200 … … class R(Expect): 787 919 return self.__trait_names 788 920 except IOError: 789 921 pass 790 if verbose :922 if verbose and use_disk_cache: 791 923 print "\nBuilding R command completion list (this takes" 792 924 print "a few seconds only the first time you do it)." 793 925 print "To force rebuild later, delete %s."%COMMANDS_CACHE 794 926 v = self._commands() 795 927 self.__trait_names = v 796 if len(v) > 200 :928 if len(v) > 200 and use_disk_cache: 797 929 sage.misc.persist.save(v, COMMANDS_CACHE) 798 930 return v 799 931 800 932 def _sendstr(self, str): 933 """ 934 Send a string to the pexpect R interface, autorestarting the 935 expect interface if anything goes wrong. 936 937 INPUT: 938 str  a string 939 940 EXAMPLES: 941 sage: r._sendstr('a < 10;\n') 942 sage: r.eval('a') 943 '[1] 10' 944 """ 801 945 if self._expect is None: 802 946 self._start() 803 947 try: … … class R(Expect): 818 962 819 963 This way, even if you somehow left R in a busy state 820 964 computing, calling _synchronize gets everything fixed. 965 966 EXAMPLES: 967 We observe nothing, just as it should be: 968 sage: r._synchronize() 821 969 """ 822 970 if self._expect is None: 823 971 return … … class R(Expect): 837 985 self.quit() 838 986 839 987 def _expect_expr(self, expr=None, timeout=None): 988 r""" 989 Wait for a given expression expr (which could be a regular 990 expression or list of regular expressions) to appear in the 991 output for at most timeout seconds. 992 993 Use \code{r._expect.before} to see what was put in the output 994 stream before the expression. 995 996 INPUT: 997 expr  None or a string or list of strings (default: None) 998 timeout  None or a number (default: None) 999 1000 EXAMPLES: 1001 sage: r._sendstr('abc < 10 +15;\n') 1002 1003 Here an exception is raised because 25 hasn't appeared yet in the 1004 output stream. The key thing is that this doesn't lock, but instead 1005 quickly raises an exception. 1006 sage: t = walltime() 1007 sage: try: r._expect_expr('25', timeout=0.5) 1008 ... except: print "Didn't get expression" 1009 Didn't get expression 1010 1011 A quick consistency check on the time that the above took: 1012 sage: w = walltime(t); w > 0.4 and w < 10 1013 True 1014 1015 We tell R to print abc, which equals 25. 1016 sage: r._sendstr('abc;\n') 1017 1018 Now 25 is in the output stream, so we can wait for it. 1019 sage: r._expect_expr('25') 1020 1021 This gives us everything before the 25. 1022 sage: r._expect.before 1023 'abc;\r\n[1] ' 1024 """ 840 1025 if expr is None: 841 1026 expr = self._prompt_wait 842 1027 if self._expect is None: … … class R(Expect): 870 1055 871 1056 def plot(self, *args, **kwargs): 872 1057 """ 873 R's plot function. 874 875 We have to define this to override the plot function defined in the 876 superclass. 1058 The R plot function. Type r.help('plot') for much more extensive 1059 documentatin about this function. See the examples below for how 1060 to use it to write output to a FILE. 877 1061 878 1062 EXAMPLES: 879 1063 sage: filename = tmp_filename() + '.png' … … class R(Expect): 888 1072 1 889 1073 sage: import os; os.unlink(filename) 890 1074 """ 1075 # We have to define this to override the plot function defined in the 1076 # superclass. 891 1077 return RFunction(self, 'plot')(*args, **kwargs) 892 1078 893 1079 def _strip_prompt(self, code): 894 1080 """ 895 1081 Remove the standard R prompt from the beginning of lines in code. 1082 1083 INPUT: 1084 code  a string 1085 OUTPUT: 1086 a string 896 1087 897 1088 EXAMPLES: 898 1089 sage: s = '> a < 2\n> b < 3' … … class R(Expect): 909 1100 EXAMPLES: 910 1101 sage: r.eval('1+1') 911 1102 '[1] 2' 1103 1104 You must give r.eval at least one input: 1105 sage: r.eval() 1106 Traceback (most recent call last): 1107 ... 1108 TypeError: R eval takes at least one argument 912 1109 """ 913 1110 # TODO split code at ";" outside of quotes and send them as individual 914 # lines without h";".1111 # lines without ";". 915 1112 if len(args) == 0: 916 r eturn "You called R with no arguments! e.g. try eval('1+1') or eval('matrix(seq(1,9),3)')."1113 raise TypeError, "R eval takes at least one argument" 917 1114 else: 918 1115 code = args[0] 919 1116 ret = Expect.eval(self, code, synchronize=True, *args,**kwargs) 920 1117 return ret 921 1118 922 923 #####################924 1119 def _r_to_sage_name(self, s): 925 1120 """ 926 1121 Returns a Sage/Python identifier from an R one. This involves 927 1122 replacing periods with underscores, < with __, and prepending 928 1123 _ in front of Python keywords. 1124 1125 INPUT: 1126 s  a string 1127 OUTPUT: 1128 a string 929 1129 930 1130 EXAMPLES: 931 1131 sage: f = r._r_to_sage_name … … class R(Expect): 945 1145 return s 946 1146 947 1147 def _sage_to_r_name(self, s): 948 """ 1148 r""" 1149 The reverse of \code{_r_to_sage_name}. See the docs for that method. 1150 949 1151 EXAMPLES: 950 1152 sage: f = r._sage_to_r_name 951 1153 sage: f('t_test') … … class R(Expect): 954 1156 'attr<' 955 1157 sage: f('parent_env__') 956 1158 'parent.env<' 1159 sage: r._r_to_sage_name(f('parent_env__')) 1160 'parent_env__' 957 1161 sage: f('class_') 958 1162 'class' 959 1163 """ … … class R(Expect): 966 1170 967 1171 def __getitem__(self, s): 968 1172 """ 969 Returns the RFunction s. 1173 Returns the RFunction with name s. 1174 1175 INPUT: 1176 s  a string 1177 OUTPUT: 1178 RFunction  the R function that in R has name s 970 1179 971 1180 EXAMPLES: 972 1181 sage: r['as.data.frame'] … … rel_re_integer = re.compile('([^\d])([\d 983 1192 rel_re_integer = re.compile('([^\d])([\d]+)L') 984 1193 rel_re_terms = re.compile('terms\s*=\s*(.*?),') 985 1194 rel_re_call = re.compile('call\s*=\s*(.*?)\),') 986 987 988 1195 989 1196 class RElement(ExpectElement): 1197 def __reduce__(self): 1198 """ 1199 EXAMPLES: 1200 sage: a = r([1,2,3]) 1201 sage: dumps(a) 1202 Traceback (most recent call last): 1203 ... 1204 NotImplementedError: pickling of R elements is not yet supported 1205 """ 1206 raise NotImplementedError, "pickling of R elements is not yet supported" 1207 990 1208 def trait_names(self): 991 1209 """ 1210 Return a list of all methods of this object. 1211 1212 NOTE: Current returns all R commands. 1213 992 1214 EXAMPLES: 993 1215 sage: a = r([1,2,3]) 994 1216 sage: t = a.trait_names() … … class RElement(ExpectElement): 1000 1222 1001 1223 def tilde(self, x): 1002 1224 """ 1225 The tilde regression operator in R. 1226 1003 1227 EXAMPLES: 1004 1228 sage: x = r([1,2,3,4,5]) 1005 1229 sage: y = r([3,5,7,9,11]) … … class RElement(ExpectElement): 1016 1240 1017 1241 def __len__(self): 1018 1242 """ 1243 Return the length of this object. 1244 1245 OUTPUT: 1246 integer 1247 1019 1248 EXAMPLES: 1020 1249 sage: x = r([10.4,5.6,3.1,6.4,21.7]) 1021 1250 sage: len(x) … … class RElement(ExpectElement): 1025 1254 1026 1255 def __getattr__(self, attrname): 1027 1256 """ 1257 Return attribute of this object, which is an R function with this object 1258 as the first input. 1259 1260 INPUT: 1261 attrname  string 1262 1263 OUTPUT: 1264 RFunctionElement 1265 1028 1266 EXAMPLES: 1029 1267 sage: x = r([1,2,3]) 1030 1268 sage: length = x.length … … class RElement(ExpectElement): 1032 1270 <class 'sage.interfaces.r.RFunctionElement'> 1033 1271 sage: length() 1034 1272 [1] 3 1035 1036 1273 """ 1037 1274 self._check_valid() 1038 1275 if attrname[:1] == "_": … … class RElement(ExpectElement): 1041 1278 1042 1279 def __getitem__(self, n): 1043 1280 """ 1281 Return nth element of self. 1282 1283 INPUT: 1284 n  an integer 1285 OUTPUT: 1286 RElement 1287 1044 1288 EXAMPLES: 1045 1289 sage: x = r([10.4,5.6,3.1,6.4,21.7]) 1046 1290 sage: x[0] … … class RElement(ExpectElement): 1055 1299 [1] 10.4 5.6 6.4 21.7 1056 1300 sage: x[4] 1057 1301 [1] 6.4 1058 1059 1302 """ 1060 1303 P = self._check_valid() 1061 1304 if isinstance(n, basestring): … … class RElement(ExpectElement): 1068 1311 1069 1312 def __nonzero__(self): 1070 1313 """ 1071 bool(self) will only return True if self == 0 contains 1072 a FALSE. 1314 Implements bool(self). 1315 1316 NOTE: bool(self) will only return True if self == 0 contains a FALSE in its representation. 1073 1317 1074 1318 EXAMPLES: 1075 1319 sage: x = r([10.4,5.6,3.1,6.4,21.7]) … … class RElement(ExpectElement): 1082 1326 False 1083 1327 sage: bool(r(1)) 1084 1328 True 1085 1086 1329 """ 1087 1330 return "FALSE" in repr(self==0) 1088 1331 1089 1332 def _comparison(self, other, symbol): 1090 1333 """ 1334 Used to implement comparison of two objects. 1335 1336 INPUT: 1337 other  RElement 1338 symbol  string 1339 1340 OUTPUT: 1341 RElement  output is an R element; not a bool! 1342 1091 1343 TESTS: 1092 1344 sage: x = r([10.4,5.6,3.1,6.4,21.7]) 1093 1345 sage: x._comparison(10.4, "==") 1094 1346 [1] TRUE FALSE FALSE FALSE FALSE 1095 1096 1347 """ 1097 1348 P = self.parent() 1098 1349 other = P(other) … … class RElement(ExpectElement): 1100 1351 1101 1352 def __eq__(self, other): 1102 1353 """ 1103 TESTS: 1354 Equality testing term by term. 1355 1356 INPUT: 1357 other  RElement 1358 OUTPUT: 1359 RElement  an R element; not a bool! 1360 1361 EXAMPLES: 1362 Notice that comparison is term by term and returns an R element. 1104 1363 sage: x = r([10.4,5.6,3.1,6.4,21.7]) 1105 1364 sage: x == 10.4 1106 1365 [1] TRUE FALSE FALSE FALSE FALSE … … class RElement(ExpectElement): 1109 1368 1110 1369 def __lt__(self, other): 1111 1370 """ 1112 TESTS: 1371 Less than testing term by term. 1372 1373 INPUT: 1374 other  RElement 1375 OUTPUT: 1376 RElement  an R element; not a bool! 1377 1378 EXAMPLES: 1379 Notice that comparison is term by term and returns an R element. 1113 1380 sage: x = r([10.4,5.6,3.1,6.4,21.7]) 1114 1381 sage: x < 7 1115 1382 [1] FALSE TRUE TRUE TRUE FALSE 1116 1117 1383 """ 1118 1384 return self._comparison(other, "<") 1119 1385 1120 1386 def __gt__(self, other): 1121 1387 """ 1122 TESTS: 1388 Greater than testing term by term. 1389 1390 INPUT: 1391 other  RElement 1392 OUTPUT: 1393 RElement  an R element; not a bool! 1394 1395 EXAMPLES: 1396 Notice that comparison is term by term and returns an R element. 1123 1397 sage: x = r([10.4,5.6,3.1,6.4,21.7]) 1124 1398 sage: x > 8 1125 1399 [1] TRUE FALSE FALSE FALSE TRUE 1126 1127 1400 """ 1128 1401 return self._comparison(other, ">") 1129 1402 1130 1403 def __le__(self, other): 1131 1404 """ 1132 TESTS: 1405 Less than or equal testing term by term. 1406 1407 INPUT: 1408 other  RElement 1409 OUTPUT: 1410 RElement  an R element; not a bool! 1411 1412 EXAMPLES: 1133 1413 sage: x = r([10.4,5.6,3.1,6.4,21.7]) 1134 1414 sage: x <= 10.4 1135 1415 [1] TRUE TRUE TRUE TRUE FALSE 1136 1137 1416 """ 1138 1417 return self._comparison(other, "<=") 1139 1418 1140 1419 def __ge__(self, other): 1141 1420 """ 1142 TESTS: 1421 Greater than or equal testing term by term. 1422 1423 INPUT: 1424 other  RElement 1425 OUTPUT: 1426 RElement  an R element; not a bool! 1427 1428 EXAMPLES: 1143 1429 sage: x = r([10.4,5.6,3.1,6.4,21.7]) 1144 1430 sage: x >= 10.4 1145 1431 [1] TRUE FALSE FALSE FALSE TRUE 1146 1147 1432 """ 1148 1433 return self._comparison(other, ">=") 1149 1434 1150 1435 def __ne__(self, other): 1151 1436 """ 1152 TESTS: 1437 Not equal testing term by term. 1438 1439 INPUT: 1440 other  RElement 1441 OUTPUT: 1442 RElement  an R element; not a bool! 1443 1444 EXAMPLES: 1153 1445 sage: x = r([10.4,5.6,3.1,6.4,21.7]) 1154 1446 sage: x != 10.4 1155 1447 [1] FALSE TRUE TRUE TRUE TRUE … … class RElement(ExpectElement): 1158 1450 return self._comparison(other, "!=") 1159 1451 1160 1452 def __cmp__(self, other): 1161 """ 1453 r""" 1454 Return 0, 1, or 1 depending on how self and other compare. 1455 1456 This is \emph{not} called by the comparison operators, which 1457 do termbyterm comparison and return R elements. 1458 1459 INPUT: 1460 self, other  R elements 1461 OUTPUT: 1462 0, 1, or 1 1463 1162 1464 EXAMPLES: 1163 1465 sage: one = r(1) 1164 1466 sage: two = r(2) … … class RElement(ExpectElement): 1186 1488 """ 1187 1489 Implements the notation self . other. 1188 1490 1491 INPUT: 1492 self, other  R elements 1493 OUTPUT: 1494 R element 1495 1189 1496 EXAMPLES: 1190 1497 sage: c = r.c(1,2,3,4) 1191 1498 sage: c.dot_product(c.t()) … … class RElement(ExpectElement): 1202 1509 """ 1203 1510 P = self._check_valid() 1204 1511 Q = P(other) 1205 # the R operator is %*% for matrix multiplication1512 # the R operator is %*% for matrix multiplication 1206 1513 return P('%s %%*%% %s'%(self.name(), Q.name())) 1207 1208 1514 1209 1515 def _subs_dots(self, x): 1210 1516 """ 1517 Replace dots by underscores; used internally to implement 1518 conversation from R expression to Sage objects. 1519 1520 INPUT: 1521 x  regular expression match: <type '_sre.SRE_Match'> 1522 OUTPUT: 1523 string 1524 1211 1525 EXAMPLES: 1212 1526 sage: import re 1213 1527 sage: a = r([1,2,3]) … … class RElement(ExpectElement): 1219 1533 1220 1534 def _subs_xrange(self, x): 1221 1535 """ 1536 Change endpoints of xranges. This is used internally in the 1537 code for converting R expressions to Sage objects. 1538 1539 INPUT: 1540 x  regular expression match: <type '_sre.SRE_Match'> 1541 OUTPUT: 1542 string 1543 1222 1544 EXAMPLES: 1223 1545 sage: import re 1224 1546 sage: a = r([1,2,3]) … … class RElement(ExpectElement): 1233 1555 def _subs_integer(self, x): 1234 1556 """ 1235 1557 Replaces strings like 'dL' with 'Integer(d)' where d is some 1236 integer. 1558 integer. This is used internally in the code for converting R 1559 expressions to Sage objects. 1237 1560 1238 1561 EXAMPLES: 1239 1562 sage: import re … … class RElement(ExpectElement): 1249 1572 1250 1573 def _convert_nested_r_list(self, exp): 1251 1574 """ 1252 Converts a string representing a (possibly) nested 1253 list in R to a (possibly) nested Python list. 1575 Converts a string representing a (possibly) nested list in R 1576 to a (possibly) nested Python list. This is used internally 1577 in the code for converting R expressions to Sage objects. 1578 1579 INPUT: 1580 exp  a string 1581 OUTPUT 1582 a string 1254 1583 1255 1584 EXAMPLES: 1256 1585 sage: a = r([1,2,3]) … … class RElement(ExpectElement): 1286 1615 1287 1616 def _r_list(self, *args, **kwargs): 1288 1617 """ 1618 This is used internally in the code for converting R 1619 expressions to Sage objects. 1620 1289 1621 EXAMPLES: 1290 1622 sage: a = r([1,2,3]) 1291 1623 sage: list(sorted(a._r_list(1,2,3,k=5).items())) … … class RElement(ExpectElement): 1300 1632 1301 1633 def _r_structure(self, __DATA__, **kwargs): 1302 1634 """ 1635 This is used internally in the code for converting R 1636 expressions to Sage objects. 1637 1303 1638 EXAMPLES: 1304 1639 sage: a = r([1,2,3]) 1305 1640 sage: d = a._r_structure('data', a=1, b=2) … … class RElement(ExpectElement): 1330 1665 return d 1331 1666 1332 1667 def _sage_(self): 1333 """1668 r""" 1334 1669 Returns Sage representation of the R object. 1335 R objects are basic C structures, of different kind,1336 that can be stacked together.1337 This is similar to Python lists with variable objects,1338 including lists in lists.1339 If R lists have names, they are translated to a Python1340 dictionary, anonymous list entries are called #{number}1341 1670 1671 R objects are basic C structures, of different kind, that can 1672 be stacked together. This is similar to Python lists with 1673 variable objects, including lists of lists. If R lists have 1674 names, they are translated to a Python dictionary, with anonymous 1675 list entries called \#\{number\}. 1676 1677 OUTPUT: 1678 object  Python object 1342 1679 1343 1680 EXAMPLES: 1344 1681 sage: rs = r.summary(r.c(1,4,3,4,3,2,5,1)) … … class RElement(ExpectElement): 1347 1684 [('DATA', [1, 1.75, 3, 2.875, 4, 5]), 1348 1685 ('_Names', ['Min.', '1st Qu.', 'Median', 'Mean', '3rd Qu.', 'Max.']), 1349 1686 ('_r_class', 'table')] 1350 1351 1687 """ 1352 1688 self._check_valid() 1353 1689 P = self.parent() 1354 1690 1355 # thats the core of the trick: using dput1691 # This is the core of the trick: using dput 1356 1692 # dput prints out the internal structure of R's data elements 1357 1693 # options via .deparseOpts(control=...) 1358 # TODO dput also works with a file, if things get huge! 1694 # TODO: dput also works with a file, if things get huge! 1695 # [[However, using a file for output often isn't necessary 1696 # since pipe buffering works pretty well for output. 1697 # That said, benchmark this.  William Stein]] 1359 1698 exp = P.eval('dput(%s)'%self.name()) 1360 1361 1699 1362 # preprocess expression1700 # Preprocess expression 1363 1701 # example what this could be: 1364 1702 # structure(list(statistic = structure(0.233549683248457, .Names = "t"), 1365 1703 # parameter = structure(5.58461538461538, .Names = "df"), p.value = 0.823657802106985, … … class RElement(ExpectElement): 1398 1736 exp = re.sub(' structure\(', ' _r_structure(', exp) 1399 1737 exp = re.sub('^structure\(', '_r_structure(', exp) #special case 1400 1738 1401 # Change 'list' to '_r_list'1739 # Change 'list' to '_r_list' 1402 1740 exp = re.sub(' list\(', ' _r_list(', exp) 1403 1741 exp = re.sub('\(list\(', '(_r_list(', exp) 1404 1742 1405 # Change 'a:b' to 'xrange(a,b+1)'1743 # Change 'a:b' to 'xrange(a,b+1)' 1406 1744 exp = rel_re_xrange.sub(self._subs_xrange, exp) 1407 1745 1408 # Change 'dL' to 'Integer(d)'1746 # Change 'dL' to 'Integer(d)' 1409 1747 exp = rel_re_integer.sub(self._subs_integer, exp) 1410 1748 1411 # Wrap the right hand side of terms = ... in quotes since it1412 # has a ~ in it.1749 # Wrap the right hand side of terms = ... in quotes since it 1750 # has a ~ in it. 1413 1751 exp = rel_re_terms.sub(r'terms = "\1",', exp) 1414 1752 1415 1753 1416 # Change call = ..., to call = "...",1754 # Change call = ..., to call = "...", 1417 1755 exp = rel_re_call.sub(r'call = "\1",', exp) 1418 1756 1419 1757 # seems to work for … … class RElement(ExpectElement): 1432 1770 1433 1771 exp = self._convert_nested_r_list(exp) 1434 1772 1435 # Set up the globals1773 # Set up the globals 1436 1774 globs = {'NA':None, 'NULL':None, 'FALSE':False, 'TRUE':True, 1437 1775 '_r_list':self._r_list, '_r_structure':self._r_structure, 1438 1776 'Integer':sage.rings.integer.Integer, … … class RElement(ExpectElement): 1442 1780 1443 1781 1444 1782 def _latex_(self): 1445 """1783 r""" 1446 1784 Return LaTeX representation of this R object. 1447 1785 1448 This calls the tex command in R 1786 This calls the \code{latex} command in R. 1787 1788 OUTPUT: 1789 a latex expression (basically a string) 1449 1790 1450 1791 EXAMPLES: 1451 sage: latex(r(2)) # optional requires the Hmisc R package1792 sage: latex(r(2)) # optional requires the Hmisc R package 1452 1793 2 1453 1794 """ 1454 1795 self._check_valid() 1455 1796 P = self.parent() 1456 1797 # latex is in Hmisc, this is currently not part of Sage's R!!! 1457 if P.library('Hmisc'): 1458 #s = P._eval_line('latex(%s, file="");'%self.name(), reformat=False) 1459 s = P.eval('latex(%s, file="");'%self.name()) 1460 return s 1798 try: 1799 P.library('Hmisc') 1800 except ImportError: 1801 raise RuntimeError, "The R package 'Hmisc' is required for R to LaTeX conversion, but it is not available." 1802 return LatexExpr(P.eval('latex(%s, file="");'%self.name())) 1461 1803 1462 raise RuntimeError, "The R package 'Hmisc' is required for R to LaTeX conversion, but it is not available." 1804 1463 1805 1464 1806 class RFunctionElement(FunctionElement): 1807 def __reduce__(self): 1808 """ 1809 EXAMPLES: 1810 sage: a = r([1,2,3]) 1811 sage: a.mean 1812 mean 1813 sage: dumps(a.mean) 1814 Traceback (most recent call last): 1815 ... 1816 NotImplementedError: pickling of R element methods is not yet supported 1817 """ 1818 raise NotImplementedError, "pickling of R element methods is not yet supported" 1819 1465 1820 def _sage_doc_(self): 1466 1821 """ 1467 Returns the help for self .1822 Returns the help for self as a string. 1468 1823 1469 1824 EXAMPLES: 1470 1825 sage: a = r([1,2,3]) … … class RFunctionElement(FunctionElement): 1473 1828 length package:base R Documentation 1474 1829 ... 1475 1830 <BLANKLINE> 1476 1477 1831 """ 1478 1832 M = self._obj.parent() 1479 1833 return M.help(self._name) 1480 1834 1481 1835 def _sage_src_(self): 1482 1836 """ 1483 Returns the source of self.1837 Returns the source code of self. 1484 1838 1485 1839 EXAMPLES: 1486 1840 sage: a = r([1,2,3]) 1487 1841 sage: length = a.length 1488 1842 sage: print length._sage_src_() 1489 1843 function (x) .Primitive("length") 1490 1491 1844 """ 1492 1845 M = self._obj.parent() 1493 1846 return M.source(self._name) … … class RFunctionElement(FunctionElement): 1499 1852 sage: length = a.length 1500 1853 sage: length() 1501 1854 [1] 3 1502 1503 1855 """ 1504 1856 return self._obj.parent().function_call(self._name, args=[self._obj] + list(args), kwargs=kwargs) 1505 1857 … … class RFunction(ExpectFunction): 1507 1859 class RFunction(ExpectFunction): 1508 1860 def __init__(self, parent, name, r_name=None): 1509 1861 """ 1862 A Function in the R interface. 1863 1864 INPUT: 1865 parent  the R interface 1866 name  the name of the function for Python 1867 r_name  the name of the function in R itself (which can have dots in it) 1868 1510 1869 EXAMPLES: 1511 1870 sage: length = r.length 1512 1871 sage: type(length) … … class RFunction(ExpectFunction): 1519 1878 self._name = name 1520 1879 else: 1521 1880 self._name = parent._sage_to_r_name(name) 1881 1882 def __cmp__(self, other): 1883 """ 1884 EXAMPLES: 1885 sage: r.mean == loads(dumps(r.mean)) 1886 True 1887 sage: r.mean == r.lr 1888 False 1889 """ 1890 if not isinstance(other, RFunction): 1891 return cmp(type(self), type(other)) 1892 return cmp(self._name, other._name) 1522 1893 1523 1894 def _sage_doc_(self): 1524 1895 """ … … class RFunction(ExpectFunction): 1530 1901 length package:base R Documentation 1531 1902 ... 1532 1903 <BLANKLINE> 1533 1534 1904 """ 1535 1905 M = self._parent 1536 1906 return M.help(self._name) … … class RFunction(ExpectFunction): 1559 1929 1560 1930 def is_RElement(x): 1561 1931 """ 1932 Return True if x is an element in an R interface. 1933 1934 INPUT: 1935 x  object 1936 OUTPUT: 1937 bool 1938 1562 1939 EXAMPLES: 1563 1940 sage: is_RElement(2) 1564 1941 False … … def is_RElement(x): 1567 1944 """ 1568 1945 return isinstance(x, RElement) 1569 1946 1570 # An instance 1947 # An instance of R 1571 1948 r = R() 1572 1949 1573 1950 def reduce_load_R(): 1574 1951 """ 1952 Used for reconstructing a copy of the R interpreter from a pickle. 1953 1575 1954 EXAMPLES: 1576 1955 sage: from sage.interfaces.r import reduce_load_R 1577 1956 sage: reduce_load_R() … … def reduce_load_R(): 1581 1960 1582 1961 import os 1583 1962 def r_console(): 1963 """ 1964 Spawn a new R commandline session. 1965 1966 EXAMPLES: 1967 sage: r.console() # not tested 1968 R version 2.6.1 (20071126) 1969 Copyright (C) 2007 The R Foundation for Statistical Computing 1970 ISBN 3900051070 1971 ... 1972 """ 1584 1973 # This will only spawn local processes 1585 1974 os.system('R vanilla') 1586 1975 … … def r_version(): 1589 1978 EXAMPLES: 1590 1979 sage: r.version() 1591 1980 ((2, 6, 1), 'R version 2.6.1 (20071126)') 1592 1593 1981 """ 1594 1982 return r.version() 1983 1984 class HelpExpression(str): 1985 """ 1986 Used to improve printing of output of r.help. 1987 """ 1988 def __repr__(self): 1989 """ 1990 Return string representatin of self. 1991 1992 OUTPUT: 1993 string 1994 1995 EXAMPLES: 1996 sage: a = sage.interfaces.r.HelpExpression("This\nis\nR!") 1997 sage: type(a) 1998 <class 'sage.interfaces.r.HelpExpression'> 1999 sage: a 2000 This 2001 is 2002 R! 2003 """ 2004 return self.__str__() 2005 
sage/stats/r.py
diff r dff3e5df5ef8 r e53b80ecaab1 sage/stats/r.py
a b from sage.interfaces.r import R, RElemen 1 ########################################################################## 2 # 3 # Copyright (C) 2007 William Stein <wstein@gmail.com> 4 # 2007 Mike Hansen <mhansen@gmail.com> 5 # 2008 Harald Schilly <harald.schilly@gmail.com> 6 # 7 # Distributed under the terms of the GNU General Public License (GPL) 8 # 9 # http://www.gnu.org/licenses/ 10 # 11 ########################################################################## 12 1 13 from sage.interfaces.r import R, RElement 2 14 3 # my own copy15 # my own copy of an R interface 4 16 myR = R() 5 17 6 18 def ttest(x,y,conf_level = 0.95, **kw): 
sage/structure/sage_object.pyx
diff r dff3e5df5ef8 r e53b80ecaab1 sage/structure/sage_object.pyx
a b cdef class SageObject: 364 364 return self._interface_init_() 365 365 366 366 def _r_init_(self): 367 """ 368 Return default string expression that evaluates in R to this 369 object. 370 371 OUTPUT: 372 string 373 374 EXAMPLES: 375 sage: a = 2/3 376 sage: a._r_init_() 377 '2/3' 378 """ 367 379 return self._interface_init_() 368 380 369 381 def _singular_(self, G=None, have_ring=False):