test_pickling.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723
  1. import inspect
  2. import copy
  3. import pickle
  4. from sympy.physics.units import meter
  5. from sympy.testing.pytest import XFAIL, raises, ignore_warnings
  6. from sympy.core.basic import Atom, Basic
  7. from sympy.core.singleton import SingletonRegistry
  8. from sympy.core.symbol import Str, Dummy, Symbol, Wild
  9. from sympy.core.numbers import (E, I, pi, oo, zoo, nan, Integer,
  10. Rational, Float, AlgebraicNumber)
  11. from sympy.core.relational import (Equality, GreaterThan, LessThan, Relational,
  12. StrictGreaterThan, StrictLessThan, Unequality)
  13. from sympy.core.add import Add
  14. from sympy.core.mul import Mul
  15. from sympy.core.power import Pow
  16. from sympy.core.function import Derivative, Function, FunctionClass, Lambda, \
  17. WildFunction
  18. from sympy.sets.sets import Interval
  19. from sympy.core.multidimensional import vectorize
  20. from sympy.external.gmpy import gmpy as _gmpy
  21. from sympy.utilities.exceptions import SymPyDeprecationWarning
  22. from sympy.core.singleton import S
  23. from sympy.core.symbol import symbols
  24. from sympy.external import import_module
  25. cloudpickle = import_module('cloudpickle')
  26. not_equal_attrs = {
  27. '_assumptions', # This is a local cache that isn't automatically filled on creation
  28. '_mhash', # Cached after __hash__ is called but set to None after creation
  29. }
  30. deprecated_attrs = {
  31. 'is_EmptySet', # Deprecated from SymPy 1.5. This can be removed when is_EmptySet is removed.
  32. 'expr_free_symbols', # Deprecated from SymPy 1.9. This can be removed when exr_free_symbols is removed.
  33. }
  34. dont_check_attrs = {
  35. '_sage_', # Fails because Sage is not installed
  36. }
  37. def check(a, exclude=[], check_attr=True, deprecated=()):
  38. """ Check that pickling and copying round-trips.
  39. """
  40. # Pickling with protocols 0 and 1 is disabled for Basic instances:
  41. if isinstance(a, Basic):
  42. for protocol in [0, 1]:
  43. raises(NotImplementedError, lambda: pickle.dumps(a, protocol))
  44. protocols = [2, copy.copy, copy.deepcopy, 3, 4]
  45. if cloudpickle:
  46. protocols.extend([cloudpickle])
  47. for protocol in protocols:
  48. if protocol in exclude:
  49. continue
  50. if callable(protocol):
  51. if isinstance(a, type):
  52. # Classes can't be copied, but that's okay.
  53. continue
  54. b = protocol(a)
  55. elif inspect.ismodule(protocol):
  56. b = protocol.loads(protocol.dumps(a))
  57. else:
  58. b = pickle.loads(pickle.dumps(a, protocol))
  59. d1 = dir(a)
  60. d2 = dir(b)
  61. assert set(d1) == set(d2)
  62. if not check_attr:
  63. continue
  64. def c(a, b, d):
  65. for i in d:
  66. if i in dont_check_attrs:
  67. continue
  68. elif i in not_equal_attrs:
  69. if hasattr(a, i):
  70. assert hasattr(b, i), i
  71. elif i in deprecated_attrs or i in deprecated:
  72. with ignore_warnings(SymPyDeprecationWarning):
  73. assert getattr(a, i) == getattr(b, i), i
  74. elif not hasattr(a, i):
  75. continue
  76. else:
  77. attr = getattr(a, i)
  78. if not hasattr(attr, "__call__"):
  79. assert hasattr(b, i), i
  80. assert getattr(b, i) == attr, "%s != %s, protocol: %s" % (getattr(b, i), attr, protocol)
  81. c(a, b, d1)
  82. c(b, a, d2)
  83. #================== core =========================
  84. def test_core_basic():
  85. for c in (Atom, Atom(), Basic, Basic(), SingletonRegistry, S):
  86. check(c)
  87. def test_core_Str():
  88. check(Str('x'))
  89. def test_core_symbol():
  90. # make the Symbol a unique name that doesn't class with any other
  91. # testing variable in this file since after this test the symbol
  92. # having the same name will be cached as noncommutative
  93. for c in (Dummy, Dummy("x", commutative=False), Symbol,
  94. Symbol("_issue_3130", commutative=False), Wild, Wild("x")):
  95. check(c)
  96. def test_core_numbers():
  97. for c in (Integer(2), Rational(2, 3), Float("1.2")):
  98. check(c)
  99. for c in (AlgebraicNumber, AlgebraicNumber(sqrt(3))):
  100. check(c, check_attr=False)
  101. def test_core_float_copy():
  102. # See gh-7457
  103. y = Symbol("x") + 1.0
  104. check(y) # does not raise TypeError ("argument is not an mpz")
  105. def test_core_relational():
  106. x = Symbol("x")
  107. y = Symbol("y")
  108. for c in (Equality, Equality(x, y), GreaterThan, GreaterThan(x, y),
  109. LessThan, LessThan(x, y), Relational, Relational(x, y),
  110. StrictGreaterThan, StrictGreaterThan(x, y), StrictLessThan,
  111. StrictLessThan(x, y), Unequality, Unequality(x, y)):
  112. check(c)
  113. def test_core_add():
  114. x = Symbol("x")
  115. for c in (Add, Add(x, 4)):
  116. check(c)
  117. def test_core_mul():
  118. x = Symbol("x")
  119. for c in (Mul, Mul(x, 4)):
  120. check(c)
  121. def test_core_power():
  122. x = Symbol("x")
  123. for c in (Pow, Pow(x, 4)):
  124. check(c)
  125. def test_core_function():
  126. x = Symbol("x")
  127. for f in (Derivative, Derivative(x), Function, FunctionClass, Lambda,
  128. WildFunction):
  129. check(f)
  130. def test_core_undefinedfunctions():
  131. f = Function("f")
  132. check(f)
  133. def test_core_appliedundef():
  134. x = Symbol("_long_unique_name_1")
  135. f = Function("_long_unique_name_2")
  136. check(f(x))
  137. def test_core_interval():
  138. for c in (Interval, Interval(0, 2)):
  139. check(c)
  140. def test_core_multidimensional():
  141. for c in (vectorize, vectorize(0)):
  142. check(c)
  143. def test_Singletons():
  144. protocols = [0, 1, 2, 3, 4]
  145. copiers = [copy.copy, copy.deepcopy]
  146. copiers += [lambda x: pickle.loads(pickle.dumps(x, proto))
  147. for proto in protocols]
  148. if cloudpickle:
  149. copiers += [lambda x: cloudpickle.loads(cloudpickle.dumps(x))]
  150. for obj in (Integer(-1), Integer(0), Integer(1), Rational(1, 2), pi, E, I,
  151. oo, -oo, zoo, nan, S.GoldenRatio, S.TribonacciConstant,
  152. S.EulerGamma, S.Catalan, S.EmptySet, S.IdentityFunction):
  153. for func in copiers:
  154. assert func(obj) is obj
  155. #================== combinatorics ===================
  156. from sympy.combinatorics.free_groups import FreeGroup
  157. def test_free_group():
  158. check(FreeGroup("x, y, z"), check_attr=False)
  159. #================== functions ===================
  160. from sympy.functions import (Piecewise, lowergamma, acosh, chebyshevu,
  161. chebyshevt, ln, chebyshevt_root, legendre, Heaviside, bernoulli, coth,
  162. tanh, assoc_legendre, sign, arg, asin, DiracDelta, re, rf, Abs,
  163. uppergamma, binomial, sinh, cos, cot, acos, acot, gamma, bell,
  164. hermite, harmonic, LambertW, zeta, log, factorial, asinh, acoth, cosh,
  165. dirichlet_eta, Eijk, loggamma, erf, ceiling, im, fibonacci,
  166. tribonacci, conjugate, tan, chebyshevu_root, floor, atanh, sqrt, sin,
  167. atan, ff, lucas, atan2, polygamma, exp)
  168. def test_functions():
  169. one_var = (acosh, ln, Heaviside, factorial, bernoulli, coth, tanh,
  170. sign, arg, asin, DiracDelta, re, Abs, sinh, cos, cot, acos, acot,
  171. gamma, bell, harmonic, LambertW, zeta, log, factorial, asinh,
  172. acoth, cosh, dirichlet_eta, loggamma, erf, ceiling, im, fibonacci,
  173. tribonacci, conjugate, tan, floor, atanh, sin, atan, lucas, exp)
  174. two_var = (rf, ff, lowergamma, chebyshevu, chebyshevt, binomial,
  175. atan2, polygamma, hermite, legendre, uppergamma)
  176. x, y, z = symbols("x,y,z")
  177. others = (chebyshevt_root, chebyshevu_root, Eijk(x, y, z),
  178. Piecewise( (0, x < -1), (x**2, x <= 1), (x**3, True)),
  179. assoc_legendre)
  180. for cls in one_var:
  181. check(cls)
  182. c = cls(x)
  183. check(c)
  184. for cls in two_var:
  185. check(cls)
  186. c = cls(x, y)
  187. check(c)
  188. for cls in others:
  189. check(cls)
  190. #================== geometry ====================
  191. from sympy.geometry.entity import GeometryEntity
  192. from sympy.geometry.point import Point
  193. from sympy.geometry.ellipse import Circle, Ellipse
  194. from sympy.geometry.line import Line, LinearEntity, Ray, Segment
  195. from sympy.geometry.polygon import Polygon, RegularPolygon, Triangle
  196. def test_geometry():
  197. p1 = Point(1, 2)
  198. p2 = Point(2, 3)
  199. p3 = Point(0, 0)
  200. p4 = Point(0, 1)
  201. for c in (
  202. GeometryEntity, GeometryEntity(), Point, p1, Circle, Circle(p1, 2),
  203. Ellipse, Ellipse(p1, 3, 4), Line, Line(p1, p2), LinearEntity,
  204. LinearEntity(p1, p2), Ray, Ray(p1, p2), Segment, Segment(p1, p2),
  205. Polygon, Polygon(p1, p2, p3, p4), RegularPolygon,
  206. RegularPolygon(p1, 4, 5), Triangle, Triangle(p1, p2, p3)):
  207. check(c, check_attr=False)
  208. #================== integrals ====================
  209. from sympy.integrals.integrals import Integral
  210. def test_integrals():
  211. x = Symbol("x")
  212. for c in (Integral, Integral(x)):
  213. check(c)
  214. #==================== logic =====================
  215. from sympy.core.logic import Logic
  216. def test_logic():
  217. for c in (Logic, Logic(1)):
  218. check(c)
  219. #================== matrices ====================
  220. from sympy.matrices import Matrix, SparseMatrix
  221. def test_matrices():
  222. for c in (Matrix, Matrix([1, 2, 3]), SparseMatrix, SparseMatrix([[1, 2], [3, 4]])):
  223. check(c, deprecated=['_smat', '_mat'])
  224. #================== ntheory =====================
  225. from sympy.ntheory.generate import Sieve
  226. def test_ntheory():
  227. for c in (Sieve, Sieve()):
  228. check(c)
  229. #================== physics =====================
  230. from sympy.physics.paulialgebra import Pauli
  231. from sympy.physics.units import Unit
  232. def test_physics():
  233. for c in (Unit, meter, Pauli, Pauli(1)):
  234. check(c)
  235. #================== plotting ====================
  236. # XXX: These tests are not complete, so XFAIL them
  237. @XFAIL
  238. def test_plotting():
  239. from sympy.plotting.pygletplot.color_scheme import ColorGradient, ColorScheme
  240. from sympy.plotting.pygletplot.managed_window import ManagedWindow
  241. from sympy.plotting.plot import Plot, ScreenShot
  242. from sympy.plotting.pygletplot.plot_axes import PlotAxes, PlotAxesBase, PlotAxesFrame, PlotAxesOrdinate
  243. from sympy.plotting.pygletplot.plot_camera import PlotCamera
  244. from sympy.plotting.pygletplot.plot_controller import PlotController
  245. from sympy.plotting.pygletplot.plot_curve import PlotCurve
  246. from sympy.plotting.pygletplot.plot_interval import PlotInterval
  247. from sympy.plotting.pygletplot.plot_mode import PlotMode
  248. from sympy.plotting.pygletplot.plot_modes import Cartesian2D, Cartesian3D, Cylindrical, \
  249. ParametricCurve2D, ParametricCurve3D, ParametricSurface, Polar, Spherical
  250. from sympy.plotting.pygletplot.plot_object import PlotObject
  251. from sympy.plotting.pygletplot.plot_surface import PlotSurface
  252. from sympy.plotting.pygletplot.plot_window import PlotWindow
  253. for c in (
  254. ColorGradient, ColorGradient(0.2, 0.4), ColorScheme, ManagedWindow,
  255. ManagedWindow, Plot, ScreenShot, PlotAxes, PlotAxesBase,
  256. PlotAxesFrame, PlotAxesOrdinate, PlotCamera, PlotController,
  257. PlotCurve, PlotInterval, PlotMode, Cartesian2D, Cartesian3D,
  258. Cylindrical, ParametricCurve2D, ParametricCurve3D,
  259. ParametricSurface, Polar, Spherical, PlotObject, PlotSurface,
  260. PlotWindow):
  261. check(c)
  262. @XFAIL
  263. def test_plotting2():
  264. #from sympy.plotting.color_scheme import ColorGradient
  265. from sympy.plotting.pygletplot.color_scheme import ColorScheme
  266. #from sympy.plotting.managed_window import ManagedWindow
  267. from sympy.plotting.plot import Plot
  268. #from sympy.plotting.plot import ScreenShot
  269. from sympy.plotting.pygletplot.plot_axes import PlotAxes
  270. #from sympy.plotting.plot_axes import PlotAxesBase, PlotAxesFrame, PlotAxesOrdinate
  271. #from sympy.plotting.plot_camera import PlotCamera
  272. #from sympy.plotting.plot_controller import PlotController
  273. #from sympy.plotting.plot_curve import PlotCurve
  274. #from sympy.plotting.plot_interval import PlotInterval
  275. #from sympy.plotting.plot_mode import PlotMode
  276. #from sympy.plotting.plot_modes import Cartesian2D, Cartesian3D, Cylindrical, \
  277. # ParametricCurve2D, ParametricCurve3D, ParametricSurface, Polar, Spherical
  278. #from sympy.plotting.plot_object import PlotObject
  279. #from sympy.plotting.plot_surface import PlotSurface
  280. # from sympy.plotting.plot_window import PlotWindow
  281. check(ColorScheme("rainbow"))
  282. check(Plot(1, visible=False))
  283. check(PlotAxes())
  284. #================== polys =======================
  285. from sympy.polys.domains.integerring import ZZ
  286. from sympy.polys.domains.rationalfield import QQ
  287. from sympy.polys.orderings import lex
  288. from sympy.polys.polytools import Poly
  289. def test_pickling_polys_polytools():
  290. from sympy.polys.polytools import PurePoly
  291. # from sympy.polys.polytools import GroebnerBasis
  292. x = Symbol('x')
  293. for c in (Poly, Poly(x, x)):
  294. check(c)
  295. for c in (PurePoly, PurePoly(x)):
  296. check(c)
  297. # TODO: fix pickling of Options class (see GroebnerBasis._options)
  298. # for c in (GroebnerBasis, GroebnerBasis([x**2 - 1], x, order=lex)):
  299. # check(c)
  300. def test_pickling_polys_polyclasses():
  301. from sympy.polys.polyclasses import DMP, DMF, ANP
  302. for c in (DMP, DMP([[ZZ(1)], [ZZ(2)], [ZZ(3)]], ZZ)):
  303. check(c, deprecated=['rep'])
  304. for c in (DMF, DMF(([ZZ(1), ZZ(2)], [ZZ(1), ZZ(3)]), ZZ)):
  305. check(c)
  306. for c in (ANP, ANP([QQ(1), QQ(2)], [QQ(1), QQ(2), QQ(3)], QQ)):
  307. check(c)
  308. @XFAIL
  309. def test_pickling_polys_rings():
  310. # NOTE: can't use protocols < 2 because we have to execute __new__ to
  311. # make sure caching of rings works properly.
  312. from sympy.polys.rings import PolyRing
  313. ring = PolyRing("x,y,z", ZZ, lex)
  314. for c in (PolyRing, ring):
  315. check(c, exclude=[0, 1])
  316. for c in (ring.dtype, ring.one):
  317. check(c, exclude=[0, 1], check_attr=False) # TODO: Py3k
  318. def test_pickling_polys_fields():
  319. pass
  320. # NOTE: can't use protocols < 2 because we have to execute __new__ to
  321. # make sure caching of fields works properly.
  322. # from sympy.polys.fields import FracField
  323. # field = FracField("x,y,z", ZZ, lex)
  324. # TODO: AssertionError: assert id(obj) not in self.memo
  325. # for c in (FracField, field):
  326. # check(c, exclude=[0, 1])
  327. # TODO: AssertionError: assert id(obj) not in self.memo
  328. # for c in (field.dtype, field.one):
  329. # check(c, exclude=[0, 1])
  330. def test_pickling_polys_elements():
  331. from sympy.polys.domains.pythonrational import PythonRational
  332. #from sympy.polys.domains.pythonfinitefield import PythonFiniteField
  333. #from sympy.polys.domains.mpelements import MPContext
  334. for c in (PythonRational, PythonRational(1, 7)):
  335. check(c)
  336. #gf = PythonFiniteField(17)
  337. # TODO: fix pickling of ModularInteger
  338. # for c in (gf.dtype, gf(5)):
  339. # check(c)
  340. #mp = MPContext()
  341. # TODO: fix pickling of RealElement
  342. # for c in (mp.mpf, mp.mpf(1.0)):
  343. # check(c)
  344. # TODO: fix pickling of ComplexElement
  345. # for c in (mp.mpc, mp.mpc(1.0, -1.5)):
  346. # check(c)
  347. def test_pickling_polys_domains():
  348. # from sympy.polys.domains.pythonfinitefield import PythonFiniteField
  349. from sympy.polys.domains.pythonintegerring import PythonIntegerRing
  350. from sympy.polys.domains.pythonrationalfield import PythonRationalField
  351. # TODO: fix pickling of ModularInteger
  352. # for c in (PythonFiniteField, PythonFiniteField(17)):
  353. # check(c)
  354. for c in (PythonIntegerRing, PythonIntegerRing()):
  355. check(c, check_attr=False)
  356. for c in (PythonRationalField, PythonRationalField()):
  357. check(c, check_attr=False)
  358. if _gmpy is not None:
  359. # from sympy.polys.domains.gmpyfinitefield import GMPYFiniteField
  360. from sympy.polys.domains.gmpyintegerring import GMPYIntegerRing
  361. from sympy.polys.domains.gmpyrationalfield import GMPYRationalField
  362. # TODO: fix pickling of ModularInteger
  363. # for c in (GMPYFiniteField, GMPYFiniteField(17)):
  364. # check(c)
  365. for c in (GMPYIntegerRing, GMPYIntegerRing()):
  366. check(c, check_attr=False)
  367. for c in (GMPYRationalField, GMPYRationalField()):
  368. check(c, check_attr=False)
  369. #from sympy.polys.domains.realfield import RealField
  370. #from sympy.polys.domains.complexfield import ComplexField
  371. from sympy.polys.domains.algebraicfield import AlgebraicField
  372. #from sympy.polys.domains.polynomialring import PolynomialRing
  373. #from sympy.polys.domains.fractionfield import FractionField
  374. from sympy.polys.domains.expressiondomain import ExpressionDomain
  375. # TODO: fix pickling of RealElement
  376. # for c in (RealField, RealField(100)):
  377. # check(c)
  378. # TODO: fix pickling of ComplexElement
  379. # for c in (ComplexField, ComplexField(100)):
  380. # check(c)
  381. for c in (AlgebraicField, AlgebraicField(QQ, sqrt(3))):
  382. check(c, check_attr=False)
  383. # TODO: AssertionError
  384. # for c in (PolynomialRing, PolynomialRing(ZZ, "x,y,z")):
  385. # check(c)
  386. # TODO: AttributeError: 'PolyElement' object has no attribute 'ring'
  387. # for c in (FractionField, FractionField(ZZ, "x,y,z")):
  388. # check(c)
  389. for c in (ExpressionDomain, ExpressionDomain()):
  390. check(c, check_attr=False)
  391. def test_pickling_polys_orderings():
  392. from sympy.polys.orderings import (LexOrder, GradedLexOrder,
  393. ReversedGradedLexOrder, InverseOrder)
  394. # from sympy.polys.orderings import ProductOrder
  395. for c in (LexOrder, LexOrder()):
  396. check(c)
  397. for c in (GradedLexOrder, GradedLexOrder()):
  398. check(c)
  399. for c in (ReversedGradedLexOrder, ReversedGradedLexOrder()):
  400. check(c)
  401. # TODO: Argh, Python is so naive. No lambdas nor inner function support in
  402. # pickling module. Maybe someone could figure out what to do with this.
  403. #
  404. # for c in (ProductOrder, ProductOrder((LexOrder(), lambda m: m[:2]),
  405. # (GradedLexOrder(), lambda m: m[2:]))):
  406. # check(c)
  407. for c in (InverseOrder, InverseOrder(LexOrder())):
  408. check(c)
  409. def test_pickling_polys_monomials():
  410. from sympy.polys.monomials import MonomialOps, Monomial
  411. x, y, z = symbols("x,y,z")
  412. for c in (MonomialOps, MonomialOps(3)):
  413. check(c)
  414. for c in (Monomial, Monomial((1, 2, 3), (x, y, z))):
  415. check(c)
  416. def test_pickling_polys_errors():
  417. from sympy.polys.polyerrors import (HeuristicGCDFailed,
  418. HomomorphismFailed, IsomorphismFailed, ExtraneousFactors,
  419. EvaluationFailed, RefinementFailed, CoercionFailed, NotInvertible,
  420. NotReversible, NotAlgebraic, DomainError, PolynomialError,
  421. UnificationFailed, GeneratorsError, GeneratorsNeeded,
  422. UnivariatePolynomialError, MultivariatePolynomialError, OptionError,
  423. FlagError)
  424. # from sympy.polys.polyerrors import (ExactQuotientFailed,
  425. # OperationNotSupported, ComputationFailed, PolificationFailed)
  426. # x = Symbol('x')
  427. # TODO: TypeError: __init__() takes at least 3 arguments (1 given)
  428. # for c in (ExactQuotientFailed, ExactQuotientFailed(x, 3*x, ZZ)):
  429. # check(c)
  430. # TODO: TypeError: can't pickle instancemethod objects
  431. # for c in (OperationNotSupported, OperationNotSupported(Poly(x), Poly.gcd)):
  432. # check(c)
  433. for c in (HeuristicGCDFailed, HeuristicGCDFailed()):
  434. check(c)
  435. for c in (HomomorphismFailed, HomomorphismFailed()):
  436. check(c)
  437. for c in (IsomorphismFailed, IsomorphismFailed()):
  438. check(c)
  439. for c in (ExtraneousFactors, ExtraneousFactors()):
  440. check(c)
  441. for c in (EvaluationFailed, EvaluationFailed()):
  442. check(c)
  443. for c in (RefinementFailed, RefinementFailed()):
  444. check(c)
  445. for c in (CoercionFailed, CoercionFailed()):
  446. check(c)
  447. for c in (NotInvertible, NotInvertible()):
  448. check(c)
  449. for c in (NotReversible, NotReversible()):
  450. check(c)
  451. for c in (NotAlgebraic, NotAlgebraic()):
  452. check(c)
  453. for c in (DomainError, DomainError()):
  454. check(c)
  455. for c in (PolynomialError, PolynomialError()):
  456. check(c)
  457. for c in (UnificationFailed, UnificationFailed()):
  458. check(c)
  459. for c in (GeneratorsError, GeneratorsError()):
  460. check(c)
  461. for c in (GeneratorsNeeded, GeneratorsNeeded()):
  462. check(c)
  463. # TODO: PicklingError: Can't pickle <function <lambda> at 0x38578c0>: it's not found as __main__.<lambda>
  464. # for c in (ComputationFailed, ComputationFailed(lambda t: t, 3, None)):
  465. # check(c)
  466. for c in (UnivariatePolynomialError, UnivariatePolynomialError()):
  467. check(c)
  468. for c in (MultivariatePolynomialError, MultivariatePolynomialError()):
  469. check(c)
  470. # TODO: TypeError: __init__() takes at least 3 arguments (1 given)
  471. # for c in (PolificationFailed, PolificationFailed({}, x, x, False)):
  472. # check(c)
  473. for c in (OptionError, OptionError()):
  474. check(c)
  475. for c in (FlagError, FlagError()):
  476. check(c)
  477. #def test_pickling_polys_options():
  478. #from sympy.polys.polyoptions import Options
  479. # TODO: fix pickling of `symbols' flag
  480. # for c in (Options, Options((), dict(domain='ZZ', polys=False))):
  481. # check(c)
  482. # TODO: def test_pickling_polys_rootisolation():
  483. # RealInterval
  484. # ComplexInterval
  485. def test_pickling_polys_rootoftools():
  486. from sympy.polys.rootoftools import CRootOf, RootSum
  487. x = Symbol('x')
  488. f = x**3 + x + 3
  489. for c in (CRootOf, CRootOf(f, 0)):
  490. check(c)
  491. for c in (RootSum, RootSum(f, exp)):
  492. check(c)
  493. #================== printing ====================
  494. from sympy.printing.latex import LatexPrinter
  495. from sympy.printing.mathml import MathMLContentPrinter, MathMLPresentationPrinter
  496. from sympy.printing.pretty.pretty import PrettyPrinter
  497. from sympy.printing.pretty.stringpict import prettyForm, stringPict
  498. from sympy.printing.printer import Printer
  499. from sympy.printing.python import PythonPrinter
  500. def test_printing():
  501. for c in (LatexPrinter, LatexPrinter(), MathMLContentPrinter,
  502. MathMLPresentationPrinter, PrettyPrinter, prettyForm, stringPict,
  503. stringPict("a"), Printer, Printer(), PythonPrinter,
  504. PythonPrinter()):
  505. check(c)
  506. @XFAIL
  507. def test_printing1():
  508. check(MathMLContentPrinter())
  509. @XFAIL
  510. def test_printing2():
  511. check(MathMLPresentationPrinter())
  512. @XFAIL
  513. def test_printing3():
  514. check(PrettyPrinter())
  515. #================== series ======================
  516. from sympy.series.limits import Limit
  517. from sympy.series.order import Order
  518. def test_series():
  519. e = Symbol("e")
  520. x = Symbol("x")
  521. for c in (Limit, Limit(e, x, 1), Order, Order(e)):
  522. check(c)
  523. #================== concrete ==================
  524. from sympy.concrete.products import Product
  525. from sympy.concrete.summations import Sum
  526. def test_concrete():
  527. x = Symbol("x")
  528. for c in (Product, Product(x, (x, 2, 4)), Sum, Sum(x, (x, 2, 4))):
  529. check(c)
  530. def test_deprecation_warning():
  531. w = SymPyDeprecationWarning("message", deprecated_since_version='1.0', active_deprecations_target="active-deprecations")
  532. check(w)
  533. def test_issue_18438():
  534. assert pickle.loads(pickle.dumps(S.Half)) == S.Half
  535. #================= old pickles =================
  536. def test_unpickle_from_older_versions():
  537. data = (
  538. b'\x80\x04\x95^\x00\x00\x00\x00\x00\x00\x00\x8c\x10sympy.core.power'
  539. b'\x94\x8c\x03Pow\x94\x93\x94\x8c\x12sympy.core.numbers\x94\x8c'
  540. b'\x07Integer\x94\x93\x94K\x02\x85\x94R\x94}\x94bh\x03\x8c\x04Half'
  541. b'\x94\x93\x94)R\x94}\x94b\x86\x94R\x94}\x94b.'
  542. )
  543. assert pickle.loads(data) == sqrt(2)