plot_implicit.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. """Implicit plotting module for SymPy.
  2. Explanation
  3. ===========
  4. The module implements a data series called ImplicitSeries which is used by
  5. ``Plot`` class to plot implicit plots for different backends. The module,
  6. by default, implements plotting using interval arithmetic. It switches to a
  7. fall back algorithm if the expression cannot be plotted using interval arithmetic.
  8. It is also possible to specify to use the fall back algorithm for all plots.
  9. Boolean combinations of expressions cannot be plotted by the fall back
  10. algorithm.
  11. See Also
  12. ========
  13. sympy.plotting.plot
  14. References
  15. ==========
  16. .. [1] Jeffrey Allen Tupper. Reliable Two-Dimensional Graphing Methods for
  17. Mathematical Formulae with Two Free Variables.
  18. .. [2] Jeffrey Allen Tupper. Graphing Equations with Generalized Interval
  19. Arithmetic. Master's thesis. University of Toronto, 1996
  20. """
  21. from .plot import BaseSeries, Plot
  22. from .experimental_lambdify import experimental_lambdify, vectorized_lambdify
  23. from .intervalmath import interval
  24. from sympy.core.relational import (Equality, GreaterThan, LessThan,
  25. Relational, StrictLessThan, StrictGreaterThan)
  26. from sympy.core.containers import Tuple
  27. from sympy.core.relational import Eq
  28. from sympy.core.symbol import (Dummy, Symbol)
  29. from sympy.core.sympify import sympify
  30. from sympy.external import import_module
  31. from sympy.logic.boolalg import BooleanFunction
  32. from sympy.polys.polyutils import _sort_gens
  33. from sympy.utilities.decorator import doctest_depends_on
  34. from sympy.utilities.iterables import flatten
  35. import warnings
  36. class ImplicitSeries(BaseSeries):
  37. """ Representation for Implicit plot """
  38. is_implicit = True
  39. def __init__(self, expr, var_start_end_x, var_start_end_y,
  40. has_equality, use_interval_math, depth, nb_of_points,
  41. line_color):
  42. super().__init__()
  43. self.expr = sympify(expr)
  44. self.label = self.expr
  45. self.var_x = sympify(var_start_end_x[0])
  46. self.start_x = float(var_start_end_x[1])
  47. self.end_x = float(var_start_end_x[2])
  48. self.var_y = sympify(var_start_end_y[0])
  49. self.start_y = float(var_start_end_y[1])
  50. self.end_y = float(var_start_end_y[2])
  51. self.get_points = self.get_raster
  52. self.has_equality = has_equality # If the expression has equality, i.e.
  53. #Eq, Greaterthan, LessThan.
  54. self.nb_of_points = nb_of_points
  55. self.use_interval_math = use_interval_math
  56. self.depth = 4 + depth
  57. self.line_color = line_color
  58. def __str__(self):
  59. return ('Implicit equation: %s for '
  60. '%s over %s and %s over %s') % (
  61. str(self.expr),
  62. str(self.var_x),
  63. str((self.start_x, self.end_x)),
  64. str(self.var_y),
  65. str((self.start_y, self.end_y)))
  66. def get_raster(self):
  67. func = experimental_lambdify((self.var_x, self.var_y), self.expr,
  68. use_interval=True)
  69. xinterval = interval(self.start_x, self.end_x)
  70. yinterval = interval(self.start_y, self.end_y)
  71. try:
  72. func(xinterval, yinterval)
  73. except AttributeError:
  74. # XXX: AttributeError("'list' object has no attribute 'is_real'")
  75. # That needs fixing somehow - we shouldn't be catching
  76. # AttributeError here.
  77. if self.use_interval_math:
  78. warnings.warn("Adaptive meshing could not be applied to the"
  79. " expression. Using uniform meshing.", stacklevel=7)
  80. self.use_interval_math = False
  81. if self.use_interval_math:
  82. return self._get_raster_interval(func)
  83. else:
  84. return self._get_meshes_grid()
  85. def _get_raster_interval(self, func):
  86. """ Uses interval math to adaptively mesh and obtain the plot"""
  87. k = self.depth
  88. interval_list = []
  89. #Create initial 32 divisions
  90. np = import_module('numpy')
  91. xsample = np.linspace(self.start_x, self.end_x, 33)
  92. ysample = np.linspace(self.start_y, self.end_y, 33)
  93. #Add a small jitter so that there are no false positives for equality.
  94. # Ex: y==x becomes True for x interval(1, 2) and y interval(1, 2)
  95. #which will draw a rectangle.
  96. jitterx = (np.random.rand(
  97. len(xsample)) * 2 - 1) * (self.end_x - self.start_x) / 2**20
  98. jittery = (np.random.rand(
  99. len(ysample)) * 2 - 1) * (self.end_y - self.start_y) / 2**20
  100. xsample += jitterx
  101. ysample += jittery
  102. xinter = [interval(x1, x2) for x1, x2 in zip(xsample[:-1],
  103. xsample[1:])]
  104. yinter = [interval(y1, y2) for y1, y2 in zip(ysample[:-1],
  105. ysample[1:])]
  106. interval_list = [[x, y] for x in xinter for y in yinter]
  107. plot_list = []
  108. #recursive call refinepixels which subdivides the intervals which are
  109. #neither True nor False according to the expression.
  110. def refine_pixels(interval_list):
  111. """ Evaluates the intervals and subdivides the interval if the
  112. expression is partially satisfied."""
  113. temp_interval_list = []
  114. plot_list = []
  115. for intervals in interval_list:
  116. #Convert the array indices to x and y values
  117. intervalx = intervals[0]
  118. intervaly = intervals[1]
  119. func_eval = func(intervalx, intervaly)
  120. #The expression is valid in the interval. Change the contour
  121. #array values to 1.
  122. if func_eval[1] is False or func_eval[0] is False:
  123. pass
  124. elif func_eval == (True, True):
  125. plot_list.append([intervalx, intervaly])
  126. elif func_eval[1] is None or func_eval[0] is None:
  127. #Subdivide
  128. avgx = intervalx.mid
  129. avgy = intervaly.mid
  130. a = interval(intervalx.start, avgx)
  131. b = interval(avgx, intervalx.end)
  132. c = interval(intervaly.start, avgy)
  133. d = interval(avgy, intervaly.end)
  134. temp_interval_list.append([a, c])
  135. temp_interval_list.append([a, d])
  136. temp_interval_list.append([b, c])
  137. temp_interval_list.append([b, d])
  138. return temp_interval_list, plot_list
  139. while k >= 0 and len(interval_list):
  140. interval_list, plot_list_temp = refine_pixels(interval_list)
  141. plot_list.extend(plot_list_temp)
  142. k = k - 1
  143. #Check whether the expression represents an equality
  144. #If it represents an equality, then none of the intervals
  145. #would have satisfied the expression due to floating point
  146. #differences. Add all the undecided values to the plot.
  147. if self.has_equality:
  148. for intervals in interval_list:
  149. intervalx = intervals[0]
  150. intervaly = intervals[1]
  151. func_eval = func(intervalx, intervaly)
  152. if func_eval[1] and func_eval[0] is not False:
  153. plot_list.append([intervalx, intervaly])
  154. return plot_list, 'fill'
  155. def _get_meshes_grid(self):
  156. """Generates the mesh for generating a contour.
  157. In the case of equality, ``contour`` function of matplotlib can
  158. be used. In other cases, matplotlib's ``contourf`` is used.
  159. """
  160. equal = False
  161. if isinstance(self.expr, Equality):
  162. expr = self.expr.lhs - self.expr.rhs
  163. equal = True
  164. elif isinstance(self.expr, (GreaterThan, StrictGreaterThan)):
  165. expr = self.expr.lhs - self.expr.rhs
  166. elif isinstance(self.expr, (LessThan, StrictLessThan)):
  167. expr = self.expr.rhs - self.expr.lhs
  168. else:
  169. raise NotImplementedError("The expression is not supported for "
  170. "plotting in uniform meshed plot.")
  171. np = import_module('numpy')
  172. xarray = np.linspace(self.start_x, self.end_x, self.nb_of_points)
  173. yarray = np.linspace(self.start_y, self.end_y, self.nb_of_points)
  174. x_grid, y_grid = np.meshgrid(xarray, yarray)
  175. func = vectorized_lambdify((self.var_x, self.var_y), expr)
  176. z_grid = func(x_grid, y_grid)
  177. z_grid[np.ma.where(z_grid < 0)] = -1
  178. z_grid[np.ma.where(z_grid > 0)] = 1
  179. if equal:
  180. return xarray, yarray, z_grid, 'contour'
  181. else:
  182. return xarray, yarray, z_grid, 'contourf'
  183. @doctest_depends_on(modules=('matplotlib',))
  184. def plot_implicit(expr, x_var=None, y_var=None, adaptive=True, depth=0,
  185. points=300, line_color="blue", show=True, **kwargs):
  186. """A plot function to plot implicit equations / inequalities.
  187. Arguments
  188. =========
  189. - expr : The equation / inequality that is to be plotted.
  190. - x_var (optional) : symbol to plot on x-axis or tuple giving symbol
  191. and range as ``(symbol, xmin, xmax)``
  192. - y_var (optional) : symbol to plot on y-axis or tuple giving symbol
  193. and range as ``(symbol, ymin, ymax)``
  194. If neither ``x_var`` nor ``y_var`` are given then the free symbols in the
  195. expression will be assigned in the order they are sorted.
  196. The following keyword arguments can also be used:
  197. - ``adaptive`` Boolean. The default value is set to True. It has to be
  198. set to False if you want to use a mesh grid.
  199. - ``depth`` integer. The depth of recursion for adaptive mesh grid.
  200. Default value is 0. Takes value in the range (0, 4).
  201. - ``points`` integer. The number of points if adaptive mesh grid is not
  202. used. Default value is 300.
  203. - ``show`` Boolean. Default value is True. If set to False, the plot will
  204. not be shown. See ``Plot`` for further information.
  205. - ``title`` string. The title for the plot.
  206. - ``xlabel`` string. The label for the x-axis
  207. - ``ylabel`` string. The label for the y-axis
  208. Aesthetics options:
  209. - ``line_color``: float or string. Specifies the color for the plot.
  210. See ``Plot`` to see how to set color for the plots.
  211. Default value is "Blue"
  212. plot_implicit, by default, uses interval arithmetic to plot functions. If
  213. the expression cannot be plotted using interval arithmetic, it defaults to
  214. a generating a contour using a mesh grid of fixed number of points. By
  215. setting adaptive to False, you can force plot_implicit to use the mesh
  216. grid. The mesh grid method can be effective when adaptive plotting using
  217. interval arithmetic, fails to plot with small line width.
  218. Examples
  219. ========
  220. Plot expressions:
  221. .. plot::
  222. :context: reset
  223. :format: doctest
  224. :include-source: True
  225. >>> from sympy import plot_implicit, symbols, Eq, And
  226. >>> x, y = symbols('x y')
  227. Without any ranges for the symbols in the expression:
  228. .. plot::
  229. :context: close-figs
  230. :format: doctest
  231. :include-source: True
  232. >>> p1 = plot_implicit(Eq(x**2 + y**2, 5))
  233. With the range for the symbols:
  234. .. plot::
  235. :context: close-figs
  236. :format: doctest
  237. :include-source: True
  238. >>> p2 = plot_implicit(
  239. ... Eq(x**2 + y**2, 3), (x, -3, 3), (y, -3, 3))
  240. With depth of recursion as argument:
  241. .. plot::
  242. :context: close-figs
  243. :format: doctest
  244. :include-source: True
  245. >>> p3 = plot_implicit(
  246. ... Eq(x**2 + y**2, 5), (x, -4, 4), (y, -4, 4), depth = 2)
  247. Using mesh grid and not using adaptive meshing:
  248. .. plot::
  249. :context: close-figs
  250. :format: doctest
  251. :include-source: True
  252. >>> p4 = plot_implicit(
  253. ... Eq(x**2 + y**2, 5), (x, -5, 5), (y, -2, 2),
  254. ... adaptive=False)
  255. Using mesh grid without using adaptive meshing with number of points
  256. specified:
  257. .. plot::
  258. :context: close-figs
  259. :format: doctest
  260. :include-source: True
  261. >>> p5 = plot_implicit(
  262. ... Eq(x**2 + y**2, 5), (x, -5, 5), (y, -2, 2),
  263. ... adaptive=False, points=400)
  264. Plotting regions:
  265. .. plot::
  266. :context: close-figs
  267. :format: doctest
  268. :include-source: True
  269. >>> p6 = plot_implicit(y > x**2)
  270. Plotting Using boolean conjunctions:
  271. .. plot::
  272. :context: close-figs
  273. :format: doctest
  274. :include-source: True
  275. >>> p7 = plot_implicit(And(y > x, y > -x))
  276. When plotting an expression with a single variable (y - 1, for example),
  277. specify the x or the y variable explicitly:
  278. .. plot::
  279. :context: close-figs
  280. :format: doctest
  281. :include-source: True
  282. >>> p8 = plot_implicit(y - 1, y_var=y)
  283. >>> p9 = plot_implicit(x - 1, x_var=x)
  284. """
  285. has_equality = False # Represents whether the expression contains an Equality,
  286. #GreaterThan or LessThan
  287. def arg_expand(bool_expr):
  288. """
  289. Recursively expands the arguments of an Boolean Function
  290. """
  291. for arg in bool_expr.args:
  292. if isinstance(arg, BooleanFunction):
  293. arg_expand(arg)
  294. elif isinstance(arg, Relational):
  295. arg_list.append(arg)
  296. arg_list = []
  297. if isinstance(expr, BooleanFunction):
  298. arg_expand(expr)
  299. #Check whether there is an equality in the expression provided.
  300. if any(isinstance(e, (Equality, GreaterThan, LessThan))
  301. for e in arg_list):
  302. has_equality = True
  303. elif not isinstance(expr, Relational):
  304. expr = Eq(expr, 0)
  305. has_equality = True
  306. elif isinstance(expr, (Equality, GreaterThan, LessThan)):
  307. has_equality = True
  308. xyvar = [i for i in (x_var, y_var) if i is not None]
  309. free_symbols = expr.free_symbols
  310. range_symbols = Tuple(*flatten(xyvar)).free_symbols
  311. undeclared = free_symbols - range_symbols
  312. if len(free_symbols & range_symbols) > 2:
  313. raise NotImplementedError("Implicit plotting is not implemented for "
  314. "more than 2 variables")
  315. #Create default ranges if the range is not provided.
  316. default_range = Tuple(-5, 5)
  317. def _range_tuple(s):
  318. if isinstance(s, Symbol):
  319. return Tuple(s) + default_range
  320. if len(s) == 3:
  321. return Tuple(*s)
  322. raise ValueError('symbol or `(symbol, min, max)` expected but got %s' % s)
  323. if len(xyvar) == 0:
  324. xyvar = list(_sort_gens(free_symbols))
  325. var_start_end_x = _range_tuple(xyvar[0])
  326. x = var_start_end_x[0]
  327. if len(xyvar) != 2:
  328. if x in undeclared or not undeclared:
  329. xyvar.append(Dummy('f(%s)' % x.name))
  330. else:
  331. xyvar.append(undeclared.pop())
  332. var_start_end_y = _range_tuple(xyvar[1])
  333. #Check whether the depth is greater than 4 or less than 0.
  334. if depth > 4:
  335. depth = 4
  336. elif depth < 0:
  337. depth = 0
  338. series_argument = ImplicitSeries(expr, var_start_end_x, var_start_end_y,
  339. has_equality, adaptive, depth,
  340. points, line_color)
  341. #set the x and y limits
  342. kwargs['xlim'] = tuple(float(x) for x in var_start_end_x[1:])
  343. kwargs['ylim'] = tuple(float(y) for y in var_start_end_y[1:])
  344. # set the x and y labels
  345. kwargs.setdefault('xlabel', var_start_end_x[0])
  346. kwargs.setdefault('ylabel', var_start_end_y[0])
  347. p = Plot(series_argument, **kwargs)
  348. if show:
  349. p.show()
  350. return p