test_pickling.py 23 KB

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