# Lilian Besson (Naereen)Small overload of the numpy.polynomial.Polynomial class to add a better printing (change the __str__ method only)

  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 # Note: For an example showing how to use this sort of technique to pretty print a polynomial object with LaTeX in a IPython console or notebook, see this tutorial: # http://nbviewer.jupyter.org/github/Naereen/notebooks/blob/master/Demonstration%20of%20numpy.polynomial.Polynomial%20and%20nice%20display%20with%20LaTeX%20and%20MathJax%20%28python3%29.ipynb Automatic test of all the docstrings: Trying: P = MyPolynomial Expecting nothing ok Trying: X = P([0, 1]) # We define the monome X, to work with it efficiently Expecting nothing ok Trying: print(X) Expecting: X ok Trying: Q1 = 1 + 2*X + 17*X**3 Expecting nothing ok Trying: print(Q1) Expecting: 1 + 2 * X + 17 * X**3 ok Trying: Q2 = Q1 - 2*X Expecting nothing ok Trying: print(Q2) Expecting: 1 + 17 * X**3 ok Trying: Q3 = -1 - 2*X - 17*X**3 Expecting nothing ok Trying: print(Q3) Expecting: (-1) + (-2) * X + (-17) * X**3 ok Trying: print(-Q3) Expecting: 1 + 2 * X + 17 * X**3 ok Trying: Q4 = (1 + 2*X + 17*X**3) ** 20 Expecting nothing ok Trying: print(Q4) # doctest: +ELLIPSIS Expecting: 1 + 40 * X + 760 * X**2 + 9460 * X**3 + 90440 * X**4 + ... + 4064231406647572451819520 * X**60 ok Trying: Q5 = (1 + 2*X + 17*X**3) ** 100 Expecting nothing ok Trying: print(Q5) # doctest: +ELLIPSIS Expecting: 1 + 200 * X + 19800 * X**2 + 1295300 * X**3 + ... + 1108899372780782949283060780215564719143115314569706274981249422854766735454757111223455545827324114733078454801811428605952 * X**300 ok 3 items had no tests: __main__ __main__.MyPolynomial __main__.MyPolynomial.__str__ 1 items passed all tests: 14 tests in __main__.test 14 tests in 4 items. 14 passed and 0 failed. Test passed. More details on these doctests can be found online in the official Python documentation: https://docs.python.org/3/library/doctest.html 
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 #! /usr/bin/env python3 # -*- coding: utf-8; mode: python -*- """ A tiny modification of the method numpy.polynomial.Polynomial.__str__ to nicely display a polynomials. Cf. https://docs.scipy.org/doc/numpy/reference/generated/numpy.polynomial.polynomial.Polynomial.html for more details about the original class. For an example showing how to use this sort of technique to pretty print a polynomial object with LaTeX in a IPython console or notebook, see this tutorial: http://nbviewer.jupyter.org/github/Naereen/notebooks/blob/master/Demonstration%20of%20numpy.polynomial.Polynomial%20and%20nice%20display%20with%20LaTeX%20and%20MathJax%20%28python3%29.ipynb - *Online:* https://bitbucket.org/snippets/lbesson/j6dpz#file-nicedisplay_numpy_polynomial_Polynomial.py - *Author:* Lilian Besson, for http://perso.crans.org/besson/infoMP/oraux/solutions/PSI_Mat2_2015_25.html, - *License:* MIT Licence (http://lbesson.mit-license.org). """ from __future__ import print_function, division # Python 2 compatibility from numpy.polynomial import Polynomial class MyPolynomial(Polynomial): """ Small extension of the numpy.polynomial.Polynomial class to change its __str__ method. """ def __str__(self): """ Improved __str__ method to print nicely the polynomial as we write it in maths.""" coefs = self.coef res = "" for i, a in enumerate(coefs): if int(a) == a: # Remove the trailing .0 a = int(a) if i == 0: if a > 0: res += "{a} + ".format(a=a) elif a < 0: res += "({a}) + ".format(a=a) elif i == 1: if a == 1: res += "X + " elif a > 0: res += "{a} * X + ".format(a=a) elif a < 0: res += "({a}) * X + ".format(a=a) else: if a == 1: res += "X**{i} + ".format(i=i) elif a > 0: res += "{a} * X**{i} + ".format(a=a, i=i) elif a < 0: res += "({a}) * X**{i} + ".format(a=a, i=i) return res[:-3] if res else "" P = MyPolynomial X = P([0, 1]) # We define the monome X, to work with it efficiently # eg. 1 + 2*X + 17*X**3 def test(): """ Some tests of our improved __str__ method. First, let start by defining the monome X: >>> P = MyPolynomial >>> X = P([0, 1]) # We define the monome X, to work with it efficiently >>> print(X) X And then a few other polynomials: >>> Q1 = 1 + 2*X + 17*X**3 >>> print(Q1) 1 + 2 * X + 17 * X**3 >>> Q2 = Q1 - 2*X >>> print(Q2) 1 + 17 * X**3 We can check that the negative signs work too: >>> Q3 = -1 - 2*X - 17*X**3 >>> print(Q3) (-1) + (-2) * X + (-17) * X**3 >>> print(-Q3) 1 + 2 * X + 17 * X**3 And with crazily long polynomials: >>> Q4 = (1 + 2*X + 17*X**3) ** 20 >>> print(Q4) # doctest: +ELLIPSIS 1 + 40 * X + 760 * X**2 + 9460 * X**3 + 90440 * X**4 + ... + 4064231406647572451819520 * X**60 >>> Q5 = (1 + 2*X + 17*X**3) ** 100 >>> print(Q5) # doctest: +ELLIPSIS 1 + 200 * X + 19800 * X**2 + 1295300 * X**3 + ... + 1108899372780782949283060780215564719143115314569706274981249422854766735454757111223455545827324114733078454801811428605952 * X**300 It works nicely ! """ pass if __name__ == '__main__': from doctest import testmod print("Automatic test of all the docstrings:") testmod(verbose=True) print("\nMore details on these doctests can be found online in the official Python documentation:\nhttps://docs.python.org/3/library/doctest.html") # End of the file 
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 Help on module nicedisplay_numpy_polynomial_Polynomial: NAME nicedisplay_numpy_polynomial_Polynomial - A tiny modification of the method numpy.polynomial.Polynomial.__str__ to nicely display a polynomials. FILE /home/lilian/publis/snippets/small-overload-of-the/nicedisplay_numpy_polynomial_Polynomial.py DESCRIPTION Cf. https://docs.scipy.org/doc/numpy/reference/generated/numpy.polynomial.polynomial.Polynomial.html for more details about the original class. - *Online:* https://bitbucket.org/snippets/lbesson/j6dpz#file-nicedisplay_numpy_polynomial_Polynomial.py - *Author:* Lilian Besson, for http://perso.crans.org/besson/infoMP/oraux/solutions/PSI_Mat2_2015_25.html, - *License:* MIT Licence (http://lbesson.mit-license.org). CLASSES numpy.polynomial.polynomial.Polynomial(numpy.polynomial._polybase.ABCPolyBase) MyPolynomial class MyPolynomial(numpy.polynomial.polynomial.Polynomial) | Small extension of the numpy.polynomial.Polynomial class to change its __str__ method. | | Method resolution order: | MyPolynomial | numpy.polynomial.polynomial.Polynomial | numpy.polynomial._polybase.ABCPolyBase | __builtin__.object | | Methods defined here: | | __str__(self) | Improved __str__ method to print nicely the polynomial as we write it in maths. | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | __abstractmethods__ = frozenset([]) | | ---------------------------------------------------------------------- | Data and other attributes inherited from numpy.polynomial.polynomial.Polynomial: | | domain = array([-1, 1]) | | nickname = 'poly' | | window = array([-1, 1]) | | ---------------------------------------------------------------------- | Methods inherited from numpy.polynomial._polybase.ABCPolyBase: | | __add__(self, other) | | __call__(self, arg) | | __div__(self, other) | | __divmod__(self, other) | | __eq__(self, other) | | __floordiv__(self, other) | | __getstate__(self) | | __init__(self, coef, domain=None, window=None) | | __iter__(self) | | __len__(self) | | __mod__(self, other) | | __mul__(self, other) | | __ne__(self, other) | | __neg__(self) | | __pos__(self) | | __pow__(self, other) | | __radd__(self, other) | | __rdiv__(self, other) | | __rdivmod__(self, other) | | __repr__(self) | | __rfloordiv__(self, other) | | __rmod__(self, other) | | __rmul__(self, other) | | __rsub__(self, other) | | __rtruediv__(self, other) | | __setstate__(self, dict) | | __sub__(self, other) | | __truediv__(self, other) | | convert(self, domain=None, kind=None, window=None) | Convert series to a different kind and/or domain and/or window. | | Parameters | ---------- | domain : array_like, optional | The domain of the converted series. If the value is None, | the default domain of kind is used. | kind : class, optional | The polynomial series type class to which the current instance | should be converted. If kind is None, then the class of the | current instance is used. | window : array_like, optional | The window of the converted series. If the value is None, | the default window of kind is used. | | Returns | ------- | new_series : series | The returned class can be of different type than the current | instance and/or have a different domain and/or different | window. | | Notes | ----- | Conversion between domains and class types can result in | numerically ill defined series. | | Examples | -------- | | copy(self) | Return a copy. | | Returns | ------- | new_series : series | Copy of self. | | cutdeg(self, deg) | Truncate series to the given degree. | | Reduce the degree of the series to deg by discarding the | high order terms. If deg is greater than the current degree a | copy of the current series is returned. This can be useful in least | squares where the coefficients of the high degree terms may be very | small. | | .. versionadded:: 1.5.0 | | Parameters | ---------- | deg : non-negative int | The series is reduced to degree deg by discarding the high | order terms. The value of deg must be a non-negative integer. | | Returns | ------- | new_series : series | New instance of series with reduced degree. | | degree(self) | The degree of the series. | | .. versionadded:: 1.5.0 | | Returns | ------- | degree : int | Degree of the series, one less than the number of coefficients. | | deriv(self, m=1) | Differentiate. | | Return a series instance of that is the derivative of the current | series. | | Parameters | ---------- | m : non-negative int | Find the derivative of order m. | | Returns | ------- | new_series : series | A new series representing the derivative. The domain is the same | as the domain of the differentiated series. | | has_samecoef(self, other) | Check if coefficients match. | | .. versionadded:: 1.6.0 | | Parameters | ---------- | other : class instance | The other class must have the coef attribute. | | Returns | ------- | bool : boolean | True if the coefficients are the same, False otherwise. | | has_samedomain(self, other) | Check if domains match. | | .. versionadded:: 1.6.0 | | Parameters | ---------- | other : class instance | The other class must have the domain attribute. | | Returns | ------- | bool : boolean | True if the domains are the same, False otherwise. | | has_sametype(self, other) | Check if types match. | | .. versionadded:: 1.7.0 | | Parameters | ---------- | other : object | Class instance. | | Returns | ------- | bool : boolean | True if other is same class as self | | has_samewindow(self, other) | Check if windows match. | | .. versionadded:: 1.6.0 | | Parameters | ---------- | other : class instance | The other class must have the window attribute. | | Returns | ------- | bool : boolean | True if the windows are the same, False otherwise. | | integ(self, m=1, k=[], lbnd=None) | Integrate. | | Return a series instance that is the definite integral of the | current series. | | Parameters | ---------- | m : non-negative int | The number of integrations to perform. | k : array_like | Integration constants. The first constant is applied to the | first integration, the second to the second, and so on. The | list of values must less than or equal to m in length and any | missing values are set to zero. | lbnd : Scalar | The lower bound of the definite integral. | | Returns | ------- | new_series : series | A new series representing the integral. The domain is the same | as the domain of the integrated series. | | linspace(self, n=100, domain=None) | Return x, y values at equally spaced points in domain. | | Returns the x, y values at n linearly spaced points across the | domain. Here y is the value of the polynomial at the points x. By | default the domain is the same as that of the series instance. | This method is intended mostly as a plotting aid. | | .. versionadded:: 1.5.0 | | Parameters | ---------- | n : int, optional | Number of point pairs to return. The default value is 100. | domain : {None, array_like}, optional | If not None, the specified domain is used instead of that of | the calling instance. It should be of the form [beg,end]. | The default is None which case the class domain is used. | | Returns | ------- | x, y : ndarray | x is equal to linspace(self.domain[0], self.domain[1], n) and | y is the series evaluated at element of x. | | mapparms(self) | Return the mapping parameters. | | The returned values define a linear map off + scl*x that is | applied to the input arguments before the series is evaluated. The | map depends on the domain and window; if the current | domain is equal to the window the resulting map is the | identity. If the coefficients of the series instance are to be | used by themselves outside this class, then the linear function | must be substituted for the x in the standard representation of | the base polynomials. | | Returns | ------- | off, scl : float or complex | The mapping function is defined by off + scl*x. | | Notes | ----- | If the current domain is the interval [l1, r1] and the window | is [l2, r2], then the linear mapping function L is | defined by the equations:: | | L(l1) = l2 | L(r1) = r2 | | roots(self) | Return the roots of the series polynomial. | | Compute the roots for the series. Note that the accuracy of the | roots decrease the further outside the domain they lie. | | Returns | ------- | roots : ndarray | Array containing the roots of the series. | | trim(self, tol=0) | Remove trailing coefficients | | Remove trailing coefficients until a coefficient is reached whose | absolute value greater than tol or the beginning of the series is | reached. If all the coefficients would be removed the series is set | to [0]. A new series instance is returned with the new | coefficients. The current instance remains unchanged. | | Parameters | ---------- | tol : non-negative number. | All trailing coefficients less than tol will be removed. | | Returns | ------- | new_series : series | Contains the new set of coefficients. | | truncate(self, size) | Truncate series to length size. | | Reduce the series to length size by discarding the high | degree terms. The value of size must be a positive integer. This | can be useful in least squares where the coefficients of the | high degree terms may be very small. | | Parameters | ---------- | size : positive int | The series is reduced to length size by discarding the high | degree terms. The value of size must be a positive integer. | | Returns | ------- | new_series : series | New instance of series with truncated coefficients. | | ---------------------------------------------------------------------- | Class methods inherited from numpy.polynomial._polybase.ABCPolyBase: | | basis(cls, deg, domain=None, window=None) from abc.ABCMeta | Series basis polynomial of degree deg. | | Returns the series representing the basis polynomial of degree deg. | | .. versionadded:: 1.7.0 | | Parameters | ---------- | deg : int | Degree of the basis polynomial for the series. Must be >= 0. | domain : {None, array_like}, optional | If given, the array must be of the form [beg, end], where | beg and end are the endpoints of the domain. If None is | given then the class domain is used. The default is None. | window : {None, array_like}, optional | If given, the resulting array must be if the form | [beg, end], where beg and end are the endpoints of | the window. If None is given then the class window is used. The | default is None. | | Returns | ------- | new_series : series | A series with the coefficient of the deg term set to one and | all others zero. | | cast(cls, series, domain=None, window=None) from abc.ABCMeta | Convert series to series of this class. | | The series is expected to be an instance of some polynomial | series of one of the types supported by by the numpy.polynomial | module, but could be some other class that supports the convert | method. | | .. versionadded:: 1.7.0 | | Parameters | ---------- | series : series | The series instance to be converted. | domain : {None, array_like}, optional | If given, the array must be of the form [beg, end], where | beg and end are the endpoints of the domain. If None is | given then the class domain is used. The default is None. | window : {None, array_like}, optional | If given, the resulting array must be if the form | [beg, end], where beg and end are the endpoints of | the window. If None is given then the class window is used. The | default is None. | | Returns | ------- | new_series : series | A series of the same kind as the calling class and equal to | series when evaluated. | | See Also | -------- | convert : similar instance method | | fit(cls, x, y, deg, domain=None, rcond=None, full=False, w=None, window=None) from abc.ABCMeta | Least squares fit to data. | | Return a series instance that is the least squares fit to the data | y sampled at x. The domain of the returned instance can be | specified and this will often result in a superior fit with less | chance of ill conditioning. | | Parameters | ---------- | x : array_like, shape (M,) | x-coordinates of the M sample points (x[i], y[i]). | y : array_like, shape (M,) or (M, K) | y-coordinates of the sample points. Several data sets of sample | points sharing the same x-coordinates can be fitted at once by | passing in a 2D-array that contains one dataset per column. | deg : int | Degree of the fitting polynomial. | domain : {None, [beg, end], []}, optional | Domain to use for the returned series. If None, | then a minimal domain that covers the points x is chosen. If | [] the class domain is used. The default value was the | class domain in NumPy 1.4 and None in later versions. | The [] option was added in numpy 1.5.0. | rcond : float, optional | Relative condition number of the fit. Singular values smaller | than this relative to the largest singular value will be | ignored. The default value is len(x)*eps, where eps is the | relative precision of the float type, about 2e-16 in most | cases. | full : bool, optional | Switch determining nature of return value. When it is False | (the default) just the coefficients are returned, when True | diagnostic information from the singular value decomposition is | also returned. | w : array_like, shape (M,), optional | Weights. If not None the contribution of each point | (x[i],y[i]) to the fit is weighted by w[i]. Ideally the | weights are chosen so that the errors of the products | w[i]*y[i] all have the same variance. The default value is | None. | | .. versionadded:: 1.5.0 | window : {[beg, end]}, optional | Window to use for the returned series. The default | value is the default class domain | | .. versionadded:: 1.6.0 | | Returns | ------- | new_series : series | A series that represents the least squares fit to the data and | has the domain specified in the call. | | [resid, rank, sv, rcond] : list | These values are only returned if full = True | | resid -- sum of squared residuals of the least squares fit | rank -- the numerical rank of the scaled Vandermonde matrix | sv -- singular values of the scaled Vandermonde matrix | rcond -- value of rcond. | | For more details, see linalg.lstsq. | | fromroots(cls, roots, domain=[], window=None) from abc.ABCMeta | Return series instance that has the specified roots. | | Returns a series representing the product | (x - r[0])*(x - r[1])*...*(x - r[n-1]), where r is a | list of roots. | | Parameters | ---------- | roots : array_like | List of roots. | domain : {[], None, array_like}, optional | Domain for the resulting series. If None the domain is the | interval from the smallest root to the largest. If [] the | domain is the class domain. The default is []. | window : {None, array_like}, optional | Window for the returned series. If None the class window is | used. The default is None. | | Returns | ------- | new_series : series | Series with the specified roots. | | identity(cls, domain=None, window=None) from abc.ABCMeta | Identity function. | | If p is the returned series, then p(x) == x for all | values of x. | | Parameters | ---------- | domain : {None, array_like}, optional | If given, the array must be of the form [beg, end], where | beg and end are the endpoints of the domain. If None is | given then the class domain is used. The default is None. | window : {None, array_like}, optional | If given, the resulting array must be if the form | [beg, end], where beg and end are the endpoints of | the window. If None is given then the class window is used. The | default is None. | | Returns | ------- | new_series : series | Series of representing the identity. | | ---------------------------------------------------------------------- | Data descriptors inherited from numpy.polynomial._polybase.ABCPolyBase: | | __dict__ | dictionary for instance variables (if defined) | | __weakref__ | list of weak references to the object (if defined) | | ---------------------------------------------------------------------- | Data and other attributes inherited from numpy.polynomial._polybase.ABCPolyBase: | | __array_priority__ = 1000 | | __hash__ = None | | __metaclass__ = | Metaclass for defining Abstract Base Classes (ABCs). | | Use this metaclass to create an ABC. An ABC can be subclassed | directly, and then acts as a mix-in class. You can also register | unrelated concrete classes (even built-in classes) and unrelated | ABCs as 'virtual subclasses' -- these and their descendants will | be considered subclasses of the registering ABC by the built-in | issubclass() function, but the registering ABC won't show up in | their MRO (Method Resolution Order) nor will method | implementations defined by the registering ABC be callable (not | even via super()). | | maxpower = 100 P = class MyPolynomial(numpy.polynomial.polynomial.Polynomial) | Small extension of the numpy.polynomial.Polynomial class to change its __str__ method. | | Method resolution order: | MyPolynomial | numpy.polynomial.polynomial.Polynomial | numpy.polynomial._polybase.ABCPolyBase | __builtin__.object | | Methods defined here: | | __str__(self) | Improved __str__ method to print nicely the polynomial as we write it in maths. | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | __abstractmethods__ = frozenset([]) | | ---------------------------------------------------------------------- | Data and other attributes inherited from numpy.polynomial.polynomial.Polynomial: | | domain = array([-1, 1]) | | nickname = 'poly' | | window = array([-1, 1]) | | ---------------------------------------------------------------------- | Methods inherited from numpy.polynomial._polybase.ABCPolyBase: | | __add__(self, other) | | __call__(self, arg) | | __div__(self, other) | | __divmod__(self, other) | | __eq__(self, other) | | __floordiv__(self, other) | | __getstate__(self) | | __init__(self, coef, domain=None, window=None) | | __iter__(self) | | __len__(self) | | __mod__(self, other) | | __mul__(self, other) | | __ne__(self, other) | | __neg__(self) | | __pos__(self) | | __pow__(self, other) | | __radd__(self, other) | | __rdiv__(self, other) | | __rdivmod__(self, other) | | __repr__(self) | | __rfloordiv__(self, other) | | __rmod__(self, other) | | __rmul__(self, other) | | __rsub__(self, other) | | __rtruediv__(self, other) | | __setstate__(self, dict) | | __sub__(self, other) | | __truediv__(self, other) | | convert(self, domain=None, kind=None, window=None) | Convert series to a different kind and/or domain and/or window. | | Parameters | ---------- | domain : array_like, optional | The domain of the converted series. If the value is None, | the default domain of kind is used. | kind : class, optional | The polynomial series type class to which the current instance | should be converted. If kind is None, then the class of the | current instance is used. | window : array_like, optional | The window of the converted series. If the value is None, | the default window of kind is used. | | Returns | ------- | new_series : series | The returned class can be of different type than the current | instance and/or have a different domain and/or different | window. | | Notes | ----- | Conversion between domains and class types can result in | numerically ill defined series. | | Examples | -------- | | copy(self) | Return a copy. | | Returns | ------- | new_series : series | Copy of self. | | cutdeg(self, deg) | Truncate series to the given degree. | | Reduce the degree of the series to deg by discarding the | high order terms. If deg is greater than the current degree a | copy of the current series is returned. This can be useful in least | squares where the coefficients of the high degree terms may be very | small. | | .. versionadded:: 1.5.0 | | Parameters | ---------- | deg : non-negative int | The series is reduced to degree deg by discarding the high | order terms. The value of deg must be a non-negative integer. | | Returns | ------- | new_series : series | New instance of series with reduced degree. | | degree(self) | The degree of the series. | | .. versionadded:: 1.5.0 | | Returns | ------- | degree : int | Degree of the series, one less than the number of coefficients. | | deriv(self, m=1) | Differentiate. | | Return a series instance of that is the derivative of the current | series. | | Parameters | ---------- | m : non-negative int | Find the derivative of order m. | | Returns | ------- | new_series : series | A new series representing the derivative. The domain is the same | as the domain of the differentiated series. | | has_samecoef(self, other) | Check if coefficients match. | | .. versionadded:: 1.6.0 | | Parameters | ---------- | other : class instance | The other class must have the coef attribute. | | Returns | ------- | bool : boolean | True if the coefficients are the same, False otherwise. | | has_samedomain(self, other) | Check if domains match. | | .. versionadded:: 1.6.0 | | Parameters | ---------- | other : class instance | The other class must have the domain attribute. | | Returns | ------- | bool : boolean | True if the domains are the same, False otherwise. | | has_sametype(self, other) | Check if types match. | | .. versionadded:: 1.7.0 | | Parameters | ---------- | other : object | Class instance. | | Returns | ------- | bool : boolean | True if other is same class as self | | has_samewindow(self, other) | Check if windows match. | | .. versionadded:: 1.6.0 | | Parameters | ---------- | other : class instance | The other class must have the window attribute. | | Returns | ------- | bool : boolean | True if the windows are the same, False otherwise. | | integ(self, m=1, k=[], lbnd=None) | Integrate. | | Return a series instance that is the definite integral of the | current series. | | Parameters | ---------- | m : non-negative int | The number of integrations to perform. | k : array_like | Integration constants. The first constant is applied to the | first integration, the second to the second, and so on. The | list of values must less than or equal to m in length and any | missing values are set to zero. | lbnd : Scalar | The lower bound of the definite integral. | | Returns | ------- | new_series : series | A new series representing the integral. The domain is the same | as the domain of the integrated series. | | linspace(self, n=100, domain=None) | Return x, y values at equally spaced points in domain. | | Returns the x, y values at n linearly spaced points across the | domain. Here y is the value of the polynomial at the points x. By | default the domain is the same as that of the series instance. | This method is intended mostly as a plotting aid. | | .. versionadded:: 1.5.0 | | Parameters | ---------- | n : int, optional | Number of point pairs to return. The default value is 100. | domain : {None, array_like}, optional | If not None, the specified domain is used instead of that of | the calling instance. It should be of the form [beg,end]. | The default is None which case the class domain is used. | | Returns | ------- | x, y : ndarray | x is equal to linspace(self.domain[0], self.domain[1], n) and | y is the series evaluated at element of x. | | mapparms(self) | Return the mapping parameters. | | The returned values define a linear map off + scl*x that is | applied to the input arguments before the series is evaluated. The | map depends on the domain and window; if the current | domain is equal to the window the resulting map is the | identity. If the coefficients of the series instance are to be | used by themselves outside this class, then the linear function | must be substituted for the x in the standard representation of | the base polynomials. | | Returns | ------- | off, scl : float or complex | The mapping function is defined by off + scl*x. | | Notes | ----- | If the current domain is the interval [l1, r1] and the window | is [l2, r2], then the linear mapping function L is | defined by the equations:: | | L(l1) = l2 | L(r1) = r2 | | roots(self) | Return the roots of the series polynomial. | | Compute the roots for the series. Note that the accuracy of the | roots decrease the further outside the domain they lie. | | Returns | ------- | roots : ndarray | Array containing the roots of the series. | | trim(self, tol=0) | Remove trailing coefficients | | Remove trailing coefficients until a coefficient is reached whose | absolute value greater than tol or the beginning of the series is | reached. If all the coefficients would be removed the series is set | to [0]. A new series instance is returned with the new | coefficients. The current instance remains unchanged. | | Parameters | ---------- | tol : non-negative number. | All trailing coefficients less than tol will be removed. | | Returns | ------- | new_series : series | Contains the new set of coefficients. | | truncate(self, size) | Truncate series to length size. | | Reduce the series to length size by discarding the high | degree terms. The value of size must be a positive integer. This | can be useful in least squares where the coefficients of the | high degree terms may be very small. | | Parameters | ---------- | size : positive int | The series is reduced to length size by discarding the high | degree terms. The value of size must be a positive integer. | | Returns | ------- | new_series : series | New instance of series with truncated coefficients. | | ---------------------------------------------------------------------- | Class methods inherited from numpy.polynomial._polybase.ABCPolyBase: | | basis(cls, deg, domain=None, window=None) from abc.ABCMeta | Series basis polynomial of degree deg. | | Returns the series representing the basis polynomial of degree deg. | | .. versionadded:: 1.7.0 | | Parameters | ---------- | deg : int | Degree of the basis polynomial for the series. Must be >= 0. | domain : {None, array_like}, optional | If given, the array must be of the form [beg, end], where | beg and end are the endpoints of the domain. If None is | given then the class domain is used. The default is None. | window : {None, array_like}, optional | If given, the resulting array must be if the form | [beg, end], where beg and end are the endpoints of | the window. If None is given then the class window is used. The | default is None. | | Returns | ------- | new_series : series | A series with the coefficient of the deg term set to one and | all others zero. | | cast(cls, series, domain=None, window=None) from abc.ABCMeta | Convert series to series of this class. | | The series is expected to be an instance of some polynomial | series of one of the types supported by by the numpy.polynomial | module, but could be some other class that supports the convert | method. | | .. versionadded:: 1.7.0 | | Parameters | ---------- | series : series | The series instance to be converted. | domain : {None, array_like}, optional | If given, the array must be of the form [beg, end], where | beg and end are the endpoints of the domain. If None is | given then the class domain is used. The default is None. | window : {None, array_like}, optional | If given, the resulting array must be if the form | [beg, end], where beg and end are the endpoints of | the window. If None is given then the class window is used. The | default is None. | | Returns | ------- | new_series : series | A series of the same kind as the calling class and equal to | series when evaluated. | | See Also | -------- | convert : similar instance method | | fit(cls, x, y, deg, domain=None, rcond=None, full=False, w=None, window=None) from abc.ABCMeta | Least squares fit to data. | | Return a series instance that is the least squares fit to the data | y sampled at x. The domain of the returned instance can be | specified and this will often result in a superior fit with less | chance of ill conditioning. | | Parameters | ---------- | x : array_like, shape (M,) | x-coordinates of the M sample points (x[i], y[i]). | y : array_like, shape (M,) or (M, K) | y-coordinates of the sample points. Several data sets of sample | points sharing the same x-coordinates can be fitted at once by | passing in a 2D-array that contains one dataset per column. | deg : int | Degree of the fitting polynomial. | domain : {None, [beg, end], []}, optional | Domain to use for the returned series. If None, | then a minimal domain that covers the points x is chosen. If | [] the class domain is used. The default value was the | class domain in NumPy 1.4 and None in later versions. | The [] option was added in numpy 1.5.0. | rcond : float, optional | Relative condition number of the fit. Singular values smaller | than this relative to the largest singular value will be | ignored. The default value is len(x)*eps, where eps is the | relative precision of the float type, about 2e-16 in most | cases. | full : bool, optional | Switch determining nature of return value. When it is False | (the default) just the coefficients are returned, when True | diagnostic information from the singular value decomposition is | also returned. | w : array_like, shape (M,), optional | Weights. If not None the contribution of each point | (x[i],y[i]) to the fit is weighted by w[i]. Ideally the | weights are chosen so that the errors of the products | w[i]*y[i] all have the same variance. The default value is | None. | | .. versionadded:: 1.5.0 | window : {[beg, end]}, optional | Window to use for the returned series. The default | value is the default class domain | | .. versionadded:: 1.6.0 | | Returns | ------- | new_series : series | A series that represents the least squares fit to the data and | has the domain specified in the call. | | [resid, rank, sv, rcond] : list | These values are only returned if full = True | | resid -- sum of squared residuals of the least squares fit | rank -- the numerical rank of the scaled Vandermonde matrix | sv -- singular values of the scaled Vandermonde matrix | rcond -- value of rcond. | | For more details, see linalg.lstsq. | | fromroots(cls, roots, domain=[], window=None) from abc.ABCMeta | Return series instance that has the specified roots. | | Returns a series representing the product | (x - r[0])*(x - r[1])*...*(x - r[n-1]), where r is a | list of roots. | | Parameters | ---------- | roots : array_like | List of roots. | domain : {[], None, array_like}, optional | Domain for the resulting series. If None the domain is the | interval from the smallest root to the largest. If [] the | domain is the class domain. The default is []. | window : {None, array_like}, optional | Window for the returned series. If None the class window is | used. The default is None. | | Returns | ------- | new_series : series | Series with the specified roots. | | identity(cls, domain=None, window=None) from abc.ABCMeta | Identity function. | | If p is the returned series, then p(x) == x for all | values of x. | | Parameters | ---------- | domain : {None, array_like}, optional | If given, the array must be of the form [beg, end], where | beg and end are the endpoints of the domain. If None is | given then the class domain is used. The default is None. | window : {None, array_like}, optional | If given, the resulting array must be if the form | [beg, end], where beg and end are the endpoints of | the window. If None is given then the class window is used. The | default is None. | | Returns | ------- | new_series : series | Series of representing the identity. | | ---------------------------------------------------------------------- | Data descriptors inherited from numpy.polynomial._polybase.ABCPolyBase: | | __dict__ | dictionary for instance variables (if defined) | | __weakref__ | list of weak references to the object (if defined) | | ---------------------------------------------------------------------- | Data and other attributes inherited from numpy.polynomial._polybase.ABCPolyBase: | | __array_priority__ = 1000 | | __hash__ = None | | __metaclass__ = | Metaclass for defining Abstract Base Classes (ABCs). | | Use this metaclass to create an ABC. An ABC can be subclassed | directly, and then acts as a mix-in class. You can also register | unrelated concrete classes (even built-in classes) and unrelated | ABCs as 'virtual subclasses' -- these and their descendants will | be considered subclasses of the registering ABC by the built-in | issubclass() function, but the registering ABC won't show up in | their MRO (Method Resolution Order) nor will method | implementations defined by the registering ABC be callable (not | even via super()). | | maxpower = 100 FUNCTIONS test() Some tests of our improved __str__ method. First, let start by defining the monome X: >>> P = MyPolynomial >>> X = P([0, 1]) # We define the monome X, to work with it efficiently >>> print(X) X And then a few other polynomials: >>> Q1 = 1 + 2*X + 17*X**3 >>> print(Q1) 1 + 2 * X + 17 * X**3 >>> Q2 = Q1 - 2*X >>> print(Q2) 1 + 17 * X**3 We can check that the negative signs work too: >>> Q3 = -1 - 2*X - 17*X**3 >>> print(Q3) (-1) + (-2) * X + (-17) * X**3 >>> print(-Q3) 1 + 2 * X + 17 * X**3 And with crazily long polynomials: >>> Q4 = (1 + 2*X + 17*X**3) ** 20 >>> print(Q4) # doctest: +ELLIPSIS 1 + 40 * X + 760 * X**2 + 9460 * X**3 + 90440 * X**4 + ... + 4064231406647572451819520 * X**60 >>> Q5 = (1 + 2*X + 17*X**3) ** 100 >>> print(Q5) # doctest: +ELLIPSIS 1 + 200 * X + 19800 * X**2 + 1295300 * X**3 + ... + 1108899372780782949283060780215564719143115314569706274981249422854766735454757111223455545827324114733078454801811428605952 * X**300 It works nicely ! DATA X = MyPolynomial([ 0., 1.], [-1, 1], [-1, 1]) division = _Feature((2, 2, 0, 'alpha', 2), (3, 0, 0, 'alpha', 0), 8192... print_function = _Feature((2, 6, 0, 'alpha', 2), (3, 0, 0, 'alpha', 0)... 
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85  Report ====== 38 statements analysed. Statistics by type ------------------ +---------+-------+-----------+-----------+------------+---------+ |type |number |old number |difference |%documented |%badname | +=========+=======+===========+===========+============+=========+ |module |1 |1 |= |100.00 |100.00 | +---------+-------+-----------+-----------+------------+---------+ |class |1 |1 |= |100.00 |100.00 | +---------+-------+-----------+-----------+------------+---------+ |method |1 |1 |= |100.00 |0.00 | +---------+-------+-----------+-----------+------------+---------+ |function |1 |1 |= |100.00 |0.00 | +---------+-------+-----------+-----------+------------+---------+ External dependencies --------------------- :: numpy \-polynomial (nicedisplay_numpy_polynomial_Polynomial) Raw metrics ----------- +----------+-------+------+---------+-----------+ |type |number |% |previous |difference | +==========+=======+======+=========+===========+ |code |39 |38.61 |39 |= | +----------+-------+------+---------+-----------+ |docstring |49 |48.51 |49 |= | +----------+-------+------+---------+-----------+ |comment |2 |1.98 |2 |= | +----------+-------+------+---------+-----------+ |empty |11 |10.89 |11 |= | +----------+-------+------+---------+-----------+ Duplication ----------- +-------------------------+------+---------+-----------+ | |now |previous |difference | +=========================+======+=========+===========+ |nb duplicated lines |0 |0 |= | +-------------------------+------+---------+-----------+ |percent duplicated lines |0.000 |0.000 |= | +-------------------------+------+---------+-----------+ Messages by category -------------------- +-----------+-------+---------+-----------+ |type |number |previous |difference | +===========+=======+=========+===========+ |convention |0 |0 |= | +-----------+-------+---------+-----------+ |refactor |0 |0 |= | +-----------+-------+---------+-----------+ |warning |0 |0 |= | +-----------+-------+---------+-----------+ |error |0 |0 |= | +-----------+-------+---------+-----------+ Global evaluation ----------------- Your code has been rated at 10.00/10 (previous run: 10.00/10, +0.00) Wow ! Now this deserves our uttermost respect. Please send your code to python-projects@logilab.org