sequences.py 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240
  1. from sympy.core.basic import Basic
  2. from sympy.core.cache import cacheit
  3. from sympy.core.containers import Tuple
  4. from sympy.core.decorators import call_highest_priority
  5. from sympy.core.parameters import global_parameters
  6. from sympy.core.function import AppliedUndef, expand
  7. from sympy.core.mul import Mul
  8. from sympy.core.numbers import Integer
  9. from sympy.core.relational import Eq
  10. from sympy.core.singleton import S, Singleton
  11. from sympy.core.sorting import ordered
  12. from sympy.core.symbol import Dummy, Symbol, Wild
  13. from sympy.core.sympify import sympify
  14. from sympy.matrices import Matrix
  15. from sympy.polys import lcm, factor
  16. from sympy.sets.sets import Interval, Intersection
  17. from sympy.tensor.indexed import Idx
  18. from sympy.utilities.iterables import flatten, is_sequence, iterable
  19. ###############################################################################
  20. # SEQUENCES #
  21. ###############################################################################
  22. class SeqBase(Basic):
  23. """Base class for sequences"""
  24. is_commutative = True
  25. _op_priority = 15
  26. @staticmethod
  27. def _start_key(expr):
  28. """Return start (if possible) else S.Infinity.
  29. adapted from Set._infimum_key
  30. """
  31. try:
  32. start = expr.start
  33. except (NotImplementedError,
  34. AttributeError, ValueError):
  35. start = S.Infinity
  36. return start
  37. def _intersect_interval(self, other):
  38. """Returns start and stop.
  39. Takes intersection over the two intervals.
  40. """
  41. interval = Intersection(self.interval, other.interval)
  42. return interval.inf, interval.sup
  43. @property
  44. def gen(self):
  45. """Returns the generator for the sequence"""
  46. raise NotImplementedError("(%s).gen" % self)
  47. @property
  48. def interval(self):
  49. """The interval on which the sequence is defined"""
  50. raise NotImplementedError("(%s).interval" % self)
  51. @property
  52. def start(self):
  53. """The starting point of the sequence. This point is included"""
  54. raise NotImplementedError("(%s).start" % self)
  55. @property
  56. def stop(self):
  57. """The ending point of the sequence. This point is included"""
  58. raise NotImplementedError("(%s).stop" % self)
  59. @property
  60. def length(self):
  61. """Length of the sequence"""
  62. raise NotImplementedError("(%s).length" % self)
  63. @property
  64. def variables(self):
  65. """Returns a tuple of variables that are bounded"""
  66. return ()
  67. @property
  68. def free_symbols(self):
  69. """
  70. This method returns the symbols in the object, excluding those
  71. that take on a specific value (i.e. the dummy symbols).
  72. Examples
  73. ========
  74. >>> from sympy import SeqFormula
  75. >>> from sympy.abc import n, m
  76. >>> SeqFormula(m*n**2, (n, 0, 5)).free_symbols
  77. {m}
  78. """
  79. return ({j for i in self.args for j in i.free_symbols
  80. .difference(self.variables)})
  81. @cacheit
  82. def coeff(self, pt):
  83. """Returns the coefficient at point pt"""
  84. if pt < self.start or pt > self.stop:
  85. raise IndexError("Index %s out of bounds %s" % (pt, self.interval))
  86. return self._eval_coeff(pt)
  87. def _eval_coeff(self, pt):
  88. raise NotImplementedError("The _eval_coeff method should be added to"
  89. "%s to return coefficient so it is available"
  90. "when coeff calls it."
  91. % self.func)
  92. def _ith_point(self, i):
  93. """Returns the i'th point of a sequence.
  94. Explanation
  95. ===========
  96. If start point is negative infinity, point is returned from the end.
  97. Assumes the first point to be indexed zero.
  98. Examples
  99. =========
  100. >>> from sympy import oo
  101. >>> from sympy.series.sequences import SeqPer
  102. bounded
  103. >>> SeqPer((1, 2, 3), (-10, 10))._ith_point(0)
  104. -10
  105. >>> SeqPer((1, 2, 3), (-10, 10))._ith_point(5)
  106. -5
  107. End is at infinity
  108. >>> SeqPer((1, 2, 3), (0, oo))._ith_point(5)
  109. 5
  110. Starts at negative infinity
  111. >>> SeqPer((1, 2, 3), (-oo, 0))._ith_point(5)
  112. -5
  113. """
  114. if self.start is S.NegativeInfinity:
  115. initial = self.stop
  116. else:
  117. initial = self.start
  118. if self.start is S.NegativeInfinity:
  119. step = -1
  120. else:
  121. step = 1
  122. return initial + i*step
  123. def _add(self, other):
  124. """
  125. Should only be used internally.
  126. Explanation
  127. ===========
  128. self._add(other) returns a new, term-wise added sequence if self
  129. knows how to add with other, otherwise it returns ``None``.
  130. ``other`` should only be a sequence object.
  131. Used within :class:`SeqAdd` class.
  132. """
  133. return None
  134. def _mul(self, other):
  135. """
  136. Should only be used internally.
  137. Explanation
  138. ===========
  139. self._mul(other) returns a new, term-wise multiplied sequence if self
  140. knows how to multiply with other, otherwise it returns ``None``.
  141. ``other`` should only be a sequence object.
  142. Used within :class:`SeqMul` class.
  143. """
  144. return None
  145. def coeff_mul(self, other):
  146. """
  147. Should be used when ``other`` is not a sequence. Should be
  148. defined to define custom behaviour.
  149. Examples
  150. ========
  151. >>> from sympy import SeqFormula
  152. >>> from sympy.abc import n
  153. >>> SeqFormula(n**2).coeff_mul(2)
  154. SeqFormula(2*n**2, (n, 0, oo))
  155. Notes
  156. =====
  157. '*' defines multiplication of sequences with sequences only.
  158. """
  159. return Mul(self, other)
  160. def __add__(self, other):
  161. """Returns the term-wise addition of 'self' and 'other'.
  162. ``other`` should be a sequence.
  163. Examples
  164. ========
  165. >>> from sympy import SeqFormula
  166. >>> from sympy.abc import n
  167. >>> SeqFormula(n**2) + SeqFormula(n**3)
  168. SeqFormula(n**3 + n**2, (n, 0, oo))
  169. """
  170. if not isinstance(other, SeqBase):
  171. raise TypeError('cannot add sequence and %s' % type(other))
  172. return SeqAdd(self, other)
  173. @call_highest_priority('__add__')
  174. def __radd__(self, other):
  175. return self + other
  176. def __sub__(self, other):
  177. """Returns the term-wise subtraction of ``self`` and ``other``.
  178. ``other`` should be a sequence.
  179. Examples
  180. ========
  181. >>> from sympy import SeqFormula
  182. >>> from sympy.abc import n
  183. >>> SeqFormula(n**2) - (SeqFormula(n))
  184. SeqFormula(n**2 - n, (n, 0, oo))
  185. """
  186. if not isinstance(other, SeqBase):
  187. raise TypeError('cannot subtract sequence and %s' % type(other))
  188. return SeqAdd(self, -other)
  189. @call_highest_priority('__sub__')
  190. def __rsub__(self, other):
  191. return (-self) + other
  192. def __neg__(self):
  193. """Negates the sequence.
  194. Examples
  195. ========
  196. >>> from sympy import SeqFormula
  197. >>> from sympy.abc import n
  198. >>> -SeqFormula(n**2)
  199. SeqFormula(-n**2, (n, 0, oo))
  200. """
  201. return self.coeff_mul(-1)
  202. def __mul__(self, other):
  203. """Returns the term-wise multiplication of 'self' and 'other'.
  204. ``other`` should be a sequence. For ``other`` not being a
  205. sequence see :func:`coeff_mul` method.
  206. Examples
  207. ========
  208. >>> from sympy import SeqFormula
  209. >>> from sympy.abc import n
  210. >>> SeqFormula(n**2) * (SeqFormula(n))
  211. SeqFormula(n**3, (n, 0, oo))
  212. """
  213. if not isinstance(other, SeqBase):
  214. raise TypeError('cannot multiply sequence and %s' % type(other))
  215. return SeqMul(self, other)
  216. @call_highest_priority('__mul__')
  217. def __rmul__(self, other):
  218. return self * other
  219. def __iter__(self):
  220. for i in range(self.length):
  221. pt = self._ith_point(i)
  222. yield self.coeff(pt)
  223. def __getitem__(self, index):
  224. if isinstance(index, int):
  225. index = self._ith_point(index)
  226. return self.coeff(index)
  227. elif isinstance(index, slice):
  228. start, stop = index.start, index.stop
  229. if start is None:
  230. start = 0
  231. if stop is None:
  232. stop = self.length
  233. return [self.coeff(self._ith_point(i)) for i in
  234. range(start, stop, index.step or 1)]
  235. def find_linear_recurrence(self,n,d=None,gfvar=None):
  236. r"""
  237. Finds the shortest linear recurrence that satisfies the first n
  238. terms of sequence of order `\leq` ``n/2`` if possible.
  239. If ``d`` is specified, find shortest linear recurrence of order
  240. `\leq` min(d, n/2) if possible.
  241. Returns list of coefficients ``[b(1), b(2), ...]`` corresponding to the
  242. recurrence relation ``x(n) = b(1)*x(n-1) + b(2)*x(n-2) + ...``
  243. Returns ``[]`` if no recurrence is found.
  244. If gfvar is specified, also returns ordinary generating function as a
  245. function of gfvar.
  246. Examples
  247. ========
  248. >>> from sympy import sequence, sqrt, oo, lucas
  249. >>> from sympy.abc import n, x, y
  250. >>> sequence(n**2).find_linear_recurrence(10, 2)
  251. []
  252. >>> sequence(n**2).find_linear_recurrence(10)
  253. [3, -3, 1]
  254. >>> sequence(2**n).find_linear_recurrence(10)
  255. [2]
  256. >>> sequence(23*n**4+91*n**2).find_linear_recurrence(10)
  257. [5, -10, 10, -5, 1]
  258. >>> sequence(sqrt(5)*(((1 + sqrt(5))/2)**n - (-(1 + sqrt(5))/2)**(-n))/5).find_linear_recurrence(10)
  259. [1, 1]
  260. >>> sequence(x+y*(-2)**(-n), (n, 0, oo)).find_linear_recurrence(30)
  261. [1/2, 1/2]
  262. >>> sequence(3*5**n + 12).find_linear_recurrence(20,gfvar=x)
  263. ([6, -5], 3*(5 - 21*x)/((x - 1)*(5*x - 1)))
  264. >>> sequence(lucas(n)).find_linear_recurrence(15,gfvar=x)
  265. ([1, 1], (x - 2)/(x**2 + x - 1))
  266. """
  267. from sympy.simplify import simplify
  268. x = [simplify(expand(t)) for t in self[:n]]
  269. lx = len(x)
  270. if d is None:
  271. r = lx//2
  272. else:
  273. r = min(d,lx//2)
  274. coeffs = []
  275. for l in range(1, r+1):
  276. l2 = 2*l
  277. mlist = []
  278. for k in range(l):
  279. mlist.append(x[k:k+l])
  280. m = Matrix(mlist)
  281. if m.det() != 0:
  282. y = simplify(m.LUsolve(Matrix(x[l:l2])))
  283. if lx == l2:
  284. coeffs = flatten(y[::-1])
  285. break
  286. mlist = []
  287. for k in range(l,lx-l):
  288. mlist.append(x[k:k+l])
  289. m = Matrix(mlist)
  290. if m*y == Matrix(x[l2:]):
  291. coeffs = flatten(y[::-1])
  292. break
  293. if gfvar is None:
  294. return coeffs
  295. else:
  296. l = len(coeffs)
  297. if l == 0:
  298. return [], None
  299. else:
  300. n, d = x[l-1]*gfvar**(l-1), 1 - coeffs[l-1]*gfvar**l
  301. for i in range(l-1):
  302. n += x[i]*gfvar**i
  303. for j in range(l-i-1):
  304. n -= coeffs[i]*x[j]*gfvar**(i+j+1)
  305. d -= coeffs[i]*gfvar**(i+1)
  306. return coeffs, simplify(factor(n)/factor(d))
  307. class EmptySequence(SeqBase, metaclass=Singleton):
  308. """Represents an empty sequence.
  309. The empty sequence is also available as a singleton as
  310. ``S.EmptySequence``.
  311. Examples
  312. ========
  313. >>> from sympy import EmptySequence, SeqPer
  314. >>> from sympy.abc import x
  315. >>> EmptySequence
  316. EmptySequence
  317. >>> SeqPer((1, 2), (x, 0, 10)) + EmptySequence
  318. SeqPer((1, 2), (x, 0, 10))
  319. >>> SeqPer((1, 2)) * EmptySequence
  320. EmptySequence
  321. >>> EmptySequence.coeff_mul(-1)
  322. EmptySequence
  323. """
  324. @property
  325. def interval(self):
  326. return S.EmptySet
  327. @property
  328. def length(self):
  329. return S.Zero
  330. def coeff_mul(self, coeff):
  331. """See docstring of SeqBase.coeff_mul"""
  332. return self
  333. def __iter__(self):
  334. return iter([])
  335. class SeqExpr(SeqBase):
  336. """Sequence expression class.
  337. Various sequences should inherit from this class.
  338. Examples
  339. ========
  340. >>> from sympy.series.sequences import SeqExpr
  341. >>> from sympy.abc import x
  342. >>> from sympy import Tuple
  343. >>> s = SeqExpr(Tuple(1, 2, 3), Tuple(x, 0, 10))
  344. >>> s.gen
  345. (1, 2, 3)
  346. >>> s.interval
  347. Interval(0, 10)
  348. >>> s.length
  349. 11
  350. See Also
  351. ========
  352. sympy.series.sequences.SeqPer
  353. sympy.series.sequences.SeqFormula
  354. """
  355. @property
  356. def gen(self):
  357. return self.args[0]
  358. @property
  359. def interval(self):
  360. return Interval(self.args[1][1], self.args[1][2])
  361. @property
  362. def start(self):
  363. return self.interval.inf
  364. @property
  365. def stop(self):
  366. return self.interval.sup
  367. @property
  368. def length(self):
  369. return self.stop - self.start + 1
  370. @property
  371. def variables(self):
  372. return (self.args[1][0],)
  373. class SeqPer(SeqExpr):
  374. """
  375. Represents a periodic sequence.
  376. The elements are repeated after a given period.
  377. Examples
  378. ========
  379. >>> from sympy import SeqPer, oo
  380. >>> from sympy.abc import k
  381. >>> s = SeqPer((1, 2, 3), (0, 5))
  382. >>> s.periodical
  383. (1, 2, 3)
  384. >>> s.period
  385. 3
  386. For value at a particular point
  387. >>> s.coeff(3)
  388. 1
  389. supports slicing
  390. >>> s[:]
  391. [1, 2, 3, 1, 2, 3]
  392. iterable
  393. >>> list(s)
  394. [1, 2, 3, 1, 2, 3]
  395. sequence starts from negative infinity
  396. >>> SeqPer((1, 2, 3), (-oo, 0))[0:6]
  397. [1, 2, 3, 1, 2, 3]
  398. Periodic formulas
  399. >>> SeqPer((k, k**2, k**3), (k, 0, oo))[0:6]
  400. [0, 1, 8, 3, 16, 125]
  401. See Also
  402. ========
  403. sympy.series.sequences.SeqFormula
  404. """
  405. def __new__(cls, periodical, limits=None):
  406. periodical = sympify(periodical)
  407. def _find_x(periodical):
  408. free = periodical.free_symbols
  409. if len(periodical.free_symbols) == 1:
  410. return free.pop()
  411. else:
  412. return Dummy('k')
  413. x, start, stop = None, None, None
  414. if limits is None:
  415. x, start, stop = _find_x(periodical), 0, S.Infinity
  416. if is_sequence(limits, Tuple):
  417. if len(limits) == 3:
  418. x, start, stop = limits
  419. elif len(limits) == 2:
  420. x = _find_x(periodical)
  421. start, stop = limits
  422. if not isinstance(x, (Symbol, Idx)) or start is None or stop is None:
  423. raise ValueError('Invalid limits given: %s' % str(limits))
  424. if start is S.NegativeInfinity and stop is S.Infinity:
  425. raise ValueError("Both the start and end value"
  426. "cannot be unbounded")
  427. limits = sympify((x, start, stop))
  428. if is_sequence(periodical, Tuple):
  429. periodical = sympify(tuple(flatten(periodical)))
  430. else:
  431. raise ValueError("invalid period %s should be something "
  432. "like e.g (1, 2) " % periodical)
  433. if Interval(limits[1], limits[2]) is S.EmptySet:
  434. return S.EmptySequence
  435. return Basic.__new__(cls, periodical, limits)
  436. @property
  437. def period(self):
  438. return len(self.gen)
  439. @property
  440. def periodical(self):
  441. return self.gen
  442. def _eval_coeff(self, pt):
  443. if self.start is S.NegativeInfinity:
  444. idx = (self.stop - pt) % self.period
  445. else:
  446. idx = (pt - self.start) % self.period
  447. return self.periodical[idx].subs(self.variables[0], pt)
  448. def _add(self, other):
  449. """See docstring of SeqBase._add"""
  450. if isinstance(other, SeqPer):
  451. per1, lper1 = self.periodical, self.period
  452. per2, lper2 = other.periodical, other.period
  453. per_length = lcm(lper1, lper2)
  454. new_per = []
  455. for x in range(per_length):
  456. ele1 = per1[x % lper1]
  457. ele2 = per2[x % lper2]
  458. new_per.append(ele1 + ele2)
  459. start, stop = self._intersect_interval(other)
  460. return SeqPer(new_per, (self.variables[0], start, stop))
  461. def _mul(self, other):
  462. """See docstring of SeqBase._mul"""
  463. if isinstance(other, SeqPer):
  464. per1, lper1 = self.periodical, self.period
  465. per2, lper2 = other.periodical, other.period
  466. per_length = lcm(lper1, lper2)
  467. new_per = []
  468. for x in range(per_length):
  469. ele1 = per1[x % lper1]
  470. ele2 = per2[x % lper2]
  471. new_per.append(ele1 * ele2)
  472. start, stop = self._intersect_interval(other)
  473. return SeqPer(new_per, (self.variables[0], start, stop))
  474. def coeff_mul(self, coeff):
  475. """See docstring of SeqBase.coeff_mul"""
  476. coeff = sympify(coeff)
  477. per = [x * coeff for x in self.periodical]
  478. return SeqPer(per, self.args[1])
  479. class SeqFormula(SeqExpr):
  480. """
  481. Represents sequence based on a formula.
  482. Elements are generated using a formula.
  483. Examples
  484. ========
  485. >>> from sympy import SeqFormula, oo, Symbol
  486. >>> n = Symbol('n')
  487. >>> s = SeqFormula(n**2, (n, 0, 5))
  488. >>> s.formula
  489. n**2
  490. For value at a particular point
  491. >>> s.coeff(3)
  492. 9
  493. supports slicing
  494. >>> s[:]
  495. [0, 1, 4, 9, 16, 25]
  496. iterable
  497. >>> list(s)
  498. [0, 1, 4, 9, 16, 25]
  499. sequence starts from negative infinity
  500. >>> SeqFormula(n**2, (-oo, 0))[0:6]
  501. [0, 1, 4, 9, 16, 25]
  502. See Also
  503. ========
  504. sympy.series.sequences.SeqPer
  505. """
  506. def __new__(cls, formula, limits=None):
  507. formula = sympify(formula)
  508. def _find_x(formula):
  509. free = formula.free_symbols
  510. if len(free) == 1:
  511. return free.pop()
  512. elif not free:
  513. return Dummy('k')
  514. else:
  515. raise ValueError(
  516. " specify dummy variables for %s. If the formula contains"
  517. " more than one free symbol, a dummy variable should be"
  518. " supplied explicitly e.g., SeqFormula(m*n**2, (n, 0, 5))"
  519. % formula)
  520. x, start, stop = None, None, None
  521. if limits is None:
  522. x, start, stop = _find_x(formula), 0, S.Infinity
  523. if is_sequence(limits, Tuple):
  524. if len(limits) == 3:
  525. x, start, stop = limits
  526. elif len(limits) == 2:
  527. x = _find_x(formula)
  528. start, stop = limits
  529. if not isinstance(x, (Symbol, Idx)) or start is None or stop is None:
  530. raise ValueError('Invalid limits given: %s' % str(limits))
  531. if start is S.NegativeInfinity and stop is S.Infinity:
  532. raise ValueError("Both the start and end value "
  533. "cannot be unbounded")
  534. limits = sympify((x, start, stop))
  535. if Interval(limits[1], limits[2]) is S.EmptySet:
  536. return S.EmptySequence
  537. return Basic.__new__(cls, formula, limits)
  538. @property
  539. def formula(self):
  540. return self.gen
  541. def _eval_coeff(self, pt):
  542. d = self.variables[0]
  543. return self.formula.subs(d, pt)
  544. def _add(self, other):
  545. """See docstring of SeqBase._add"""
  546. if isinstance(other, SeqFormula):
  547. form1, v1 = self.formula, self.variables[0]
  548. form2, v2 = other.formula, other.variables[0]
  549. formula = form1 + form2.subs(v2, v1)
  550. start, stop = self._intersect_interval(other)
  551. return SeqFormula(formula, (v1, start, stop))
  552. def _mul(self, other):
  553. """See docstring of SeqBase._mul"""
  554. if isinstance(other, SeqFormula):
  555. form1, v1 = self.formula, self.variables[0]
  556. form2, v2 = other.formula, other.variables[0]
  557. formula = form1 * form2.subs(v2, v1)
  558. start, stop = self._intersect_interval(other)
  559. return SeqFormula(formula, (v1, start, stop))
  560. def coeff_mul(self, coeff):
  561. """See docstring of SeqBase.coeff_mul"""
  562. coeff = sympify(coeff)
  563. formula = self.formula * coeff
  564. return SeqFormula(formula, self.args[1])
  565. def expand(self, *args, **kwargs):
  566. return SeqFormula(expand(self.formula, *args, **kwargs), self.args[1])
  567. class RecursiveSeq(SeqBase):
  568. """
  569. A finite degree recursive sequence.
  570. Explanation
  571. ===========
  572. That is, a sequence a(n) that depends on a fixed, finite number of its
  573. previous values. The general form is
  574. a(n) = f(a(n - 1), a(n - 2), ..., a(n - d))
  575. for some fixed, positive integer d, where f is some function defined by a
  576. SymPy expression.
  577. Parameters
  578. ==========
  579. recurrence : SymPy expression defining recurrence
  580. This is *not* an equality, only the expression that the nth term is
  581. equal to. For example, if :code:`a(n) = f(a(n - 1), ..., a(n - d))`,
  582. then the expression should be :code:`f(a(n - 1), ..., a(n - d))`.
  583. yn : applied undefined function
  584. Represents the nth term of the sequence as e.g. :code:`y(n)` where
  585. :code:`y` is an undefined function and `n` is the sequence index.
  586. n : symbolic argument
  587. The name of the variable that the recurrence is in, e.g., :code:`n` if
  588. the recurrence function is :code:`y(n)`.
  589. initial : iterable with length equal to the degree of the recurrence
  590. The initial values of the recurrence.
  591. start : start value of sequence (inclusive)
  592. Examples
  593. ========
  594. >>> from sympy import Function, symbols
  595. >>> from sympy.series.sequences import RecursiveSeq
  596. >>> y = Function("y")
  597. >>> n = symbols("n")
  598. >>> fib = RecursiveSeq(y(n - 1) + y(n - 2), y(n), n, [0, 1])
  599. >>> fib.coeff(3) # Value at a particular point
  600. 2
  601. >>> fib[:6] # supports slicing
  602. [0, 1, 1, 2, 3, 5]
  603. >>> fib.recurrence # inspect recurrence
  604. Eq(y(n), y(n - 2) + y(n - 1))
  605. >>> fib.degree # automatically determine degree
  606. 2
  607. >>> for x in zip(range(10), fib): # supports iteration
  608. ... print(x)
  609. (0, 0)
  610. (1, 1)
  611. (2, 1)
  612. (3, 2)
  613. (4, 3)
  614. (5, 5)
  615. (6, 8)
  616. (7, 13)
  617. (8, 21)
  618. (9, 34)
  619. See Also
  620. ========
  621. sympy.series.sequences.SeqFormula
  622. """
  623. def __new__(cls, recurrence, yn, n, initial=None, start=0):
  624. if not isinstance(yn, AppliedUndef):
  625. raise TypeError("recurrence sequence must be an applied undefined function"
  626. ", found `{}`".format(yn))
  627. if not isinstance(n, Basic) or not n.is_symbol:
  628. raise TypeError("recurrence variable must be a symbol"
  629. ", found `{}`".format(n))
  630. if yn.args != (n,):
  631. raise TypeError("recurrence sequence does not match symbol")
  632. y = yn.func
  633. k = Wild("k", exclude=(n,))
  634. degree = 0
  635. # Find all applications of y in the recurrence and check that:
  636. # 1. The function y is only being used with a single argument; and
  637. # 2. All arguments are n + k for constant negative integers k.
  638. prev_ys = recurrence.find(y)
  639. for prev_y in prev_ys:
  640. if len(prev_y.args) != 1:
  641. raise TypeError("Recurrence should be in a single variable")
  642. shift = prev_y.args[0].match(n + k)[k]
  643. if not (shift.is_constant() and shift.is_integer and shift < 0):
  644. raise TypeError("Recurrence should have constant,"
  645. " negative, integer shifts"
  646. " (found {})".format(prev_y))
  647. if -shift > degree:
  648. degree = -shift
  649. if not initial:
  650. initial = [Dummy("c_{}".format(k)) for k in range(degree)]
  651. if len(initial) != degree:
  652. raise ValueError("Number of initial terms must equal degree")
  653. degree = Integer(degree)
  654. start = sympify(start)
  655. initial = Tuple(*(sympify(x) for x in initial))
  656. seq = Basic.__new__(cls, recurrence, yn, n, initial, start)
  657. seq.cache = {y(start + k): init for k, init in enumerate(initial)}
  658. seq.degree = degree
  659. return seq
  660. @property
  661. def _recurrence(self):
  662. """Equation defining recurrence."""
  663. return self.args[0]
  664. @property
  665. def recurrence(self):
  666. """Equation defining recurrence."""
  667. return Eq(self.yn, self.args[0])
  668. @property
  669. def yn(self):
  670. """Applied function representing the nth term"""
  671. return self.args[1]
  672. @property
  673. def y(self):
  674. """Undefined function for the nth term of the sequence"""
  675. return self.yn.func
  676. @property
  677. def n(self):
  678. """Sequence index symbol"""
  679. return self.args[2]
  680. @property
  681. def initial(self):
  682. """The initial values of the sequence"""
  683. return self.args[3]
  684. @property
  685. def start(self):
  686. """The starting point of the sequence. This point is included"""
  687. return self.args[4]
  688. @property
  689. def stop(self):
  690. """The ending point of the sequence. (oo)"""
  691. return S.Infinity
  692. @property
  693. def interval(self):
  694. """Interval on which sequence is defined."""
  695. return (self.start, S.Infinity)
  696. def _eval_coeff(self, index):
  697. if index - self.start < len(self.cache):
  698. return self.cache[self.y(index)]
  699. for current in range(len(self.cache), index + 1):
  700. # Use xreplace over subs for performance.
  701. # See issue #10697.
  702. seq_index = self.start + current
  703. current_recurrence = self._recurrence.xreplace({self.n: seq_index})
  704. new_term = current_recurrence.xreplace(self.cache)
  705. self.cache[self.y(seq_index)] = new_term
  706. return self.cache[self.y(self.start + current)]
  707. def __iter__(self):
  708. index = self.start
  709. while True:
  710. yield self._eval_coeff(index)
  711. index += 1
  712. def sequence(seq, limits=None):
  713. """
  714. Returns appropriate sequence object.
  715. Explanation
  716. ===========
  717. If ``seq`` is a SymPy sequence, returns :class:`SeqPer` object
  718. otherwise returns :class:`SeqFormula` object.
  719. Examples
  720. ========
  721. >>> from sympy import sequence
  722. >>> from sympy.abc import n
  723. >>> sequence(n**2, (n, 0, 5))
  724. SeqFormula(n**2, (n, 0, 5))
  725. >>> sequence((1, 2, 3), (n, 0, 5))
  726. SeqPer((1, 2, 3), (n, 0, 5))
  727. See Also
  728. ========
  729. sympy.series.sequences.SeqPer
  730. sympy.series.sequences.SeqFormula
  731. """
  732. seq = sympify(seq)
  733. if is_sequence(seq, Tuple):
  734. return SeqPer(seq, limits)
  735. else:
  736. return SeqFormula(seq, limits)
  737. ###############################################################################
  738. # OPERATIONS #
  739. ###############################################################################
  740. class SeqExprOp(SeqBase):
  741. """
  742. Base class for operations on sequences.
  743. Examples
  744. ========
  745. >>> from sympy.series.sequences import SeqExprOp, sequence
  746. >>> from sympy.abc import n
  747. >>> s1 = sequence(n**2, (n, 0, 10))
  748. >>> s2 = sequence((1, 2, 3), (n, 5, 10))
  749. >>> s = SeqExprOp(s1, s2)
  750. >>> s.gen
  751. (n**2, (1, 2, 3))
  752. >>> s.interval
  753. Interval(5, 10)
  754. >>> s.length
  755. 6
  756. See Also
  757. ========
  758. sympy.series.sequences.SeqAdd
  759. sympy.series.sequences.SeqMul
  760. """
  761. @property
  762. def gen(self):
  763. """Generator for the sequence.
  764. returns a tuple of generators of all the argument sequences.
  765. """
  766. return tuple(a.gen for a in self.args)
  767. @property
  768. def interval(self):
  769. """Sequence is defined on the intersection
  770. of all the intervals of respective sequences
  771. """
  772. return Intersection(*(a.interval for a in self.args))
  773. @property
  774. def start(self):
  775. return self.interval.inf
  776. @property
  777. def stop(self):
  778. return self.interval.sup
  779. @property
  780. def variables(self):
  781. """Cumulative of all the bound variables"""
  782. return tuple(flatten([a.variables for a in self.args]))
  783. @property
  784. def length(self):
  785. return self.stop - self.start + 1
  786. class SeqAdd(SeqExprOp):
  787. """Represents term-wise addition of sequences.
  788. Rules:
  789. * The interval on which sequence is defined is the intersection
  790. of respective intervals of sequences.
  791. * Anything + :class:`EmptySequence` remains unchanged.
  792. * Other rules are defined in ``_add`` methods of sequence classes.
  793. Examples
  794. ========
  795. >>> from sympy import EmptySequence, oo, SeqAdd, SeqPer, SeqFormula
  796. >>> from sympy.abc import n
  797. >>> SeqAdd(SeqPer((1, 2), (n, 0, oo)), EmptySequence)
  798. SeqPer((1, 2), (n, 0, oo))
  799. >>> SeqAdd(SeqPer((1, 2), (n, 0, 5)), SeqPer((1, 2), (n, 6, 10)))
  800. EmptySequence
  801. >>> SeqAdd(SeqPer((1, 2), (n, 0, oo)), SeqFormula(n**2, (n, 0, oo)))
  802. SeqAdd(SeqFormula(n**2, (n, 0, oo)), SeqPer((1, 2), (n, 0, oo)))
  803. >>> SeqAdd(SeqFormula(n**3), SeqFormula(n**2))
  804. SeqFormula(n**3 + n**2, (n, 0, oo))
  805. See Also
  806. ========
  807. sympy.series.sequences.SeqMul
  808. """
  809. def __new__(cls, *args, **kwargs):
  810. evaluate = kwargs.get('evaluate', global_parameters.evaluate)
  811. # flatten inputs
  812. args = list(args)
  813. # adapted from sympy.sets.sets.Union
  814. def _flatten(arg):
  815. if isinstance(arg, SeqBase):
  816. if isinstance(arg, SeqAdd):
  817. return sum(map(_flatten, arg.args), [])
  818. else:
  819. return [arg]
  820. if iterable(arg):
  821. return sum(map(_flatten, arg), [])
  822. raise TypeError("Input must be Sequences or "
  823. " iterables of Sequences")
  824. args = _flatten(args)
  825. args = [a for a in args if a is not S.EmptySequence]
  826. # Addition of no sequences is EmptySequence
  827. if not args:
  828. return S.EmptySequence
  829. if Intersection(*(a.interval for a in args)) is S.EmptySet:
  830. return S.EmptySequence
  831. # reduce using known rules
  832. if evaluate:
  833. return SeqAdd.reduce(args)
  834. args = list(ordered(args, SeqBase._start_key))
  835. return Basic.__new__(cls, *args)
  836. @staticmethod
  837. def reduce(args):
  838. """Simplify :class:`SeqAdd` using known rules.
  839. Iterates through all pairs and ask the constituent
  840. sequences if they can simplify themselves with any other constituent.
  841. Notes
  842. =====
  843. adapted from ``Union.reduce``
  844. """
  845. new_args = True
  846. while new_args:
  847. for id1, s in enumerate(args):
  848. new_args = False
  849. for id2, t in enumerate(args):
  850. if id1 == id2:
  851. continue
  852. new_seq = s._add(t)
  853. # This returns None if s does not know how to add
  854. # with t. Returns the newly added sequence otherwise
  855. if new_seq is not None:
  856. new_args = [a for a in args if a not in (s, t)]
  857. new_args.append(new_seq)
  858. break
  859. if new_args:
  860. args = new_args
  861. break
  862. if len(args) == 1:
  863. return args.pop()
  864. else:
  865. return SeqAdd(args, evaluate=False)
  866. def _eval_coeff(self, pt):
  867. """adds up the coefficients of all the sequences at point pt"""
  868. return sum(a.coeff(pt) for a in self.args)
  869. class SeqMul(SeqExprOp):
  870. r"""Represents term-wise multiplication of sequences.
  871. Explanation
  872. ===========
  873. Handles multiplication of sequences only. For multiplication
  874. with other objects see :func:`SeqBase.coeff_mul`.
  875. Rules:
  876. * The interval on which sequence is defined is the intersection
  877. of respective intervals of sequences.
  878. * Anything \* :class:`EmptySequence` returns :class:`EmptySequence`.
  879. * Other rules are defined in ``_mul`` methods of sequence classes.
  880. Examples
  881. ========
  882. >>> from sympy import EmptySequence, oo, SeqMul, SeqPer, SeqFormula
  883. >>> from sympy.abc import n
  884. >>> SeqMul(SeqPer((1, 2), (n, 0, oo)), EmptySequence)
  885. EmptySequence
  886. >>> SeqMul(SeqPer((1, 2), (n, 0, 5)), SeqPer((1, 2), (n, 6, 10)))
  887. EmptySequence
  888. >>> SeqMul(SeqPer((1, 2), (n, 0, oo)), SeqFormula(n**2))
  889. SeqMul(SeqFormula(n**2, (n, 0, oo)), SeqPer((1, 2), (n, 0, oo)))
  890. >>> SeqMul(SeqFormula(n**3), SeqFormula(n**2))
  891. SeqFormula(n**5, (n, 0, oo))
  892. See Also
  893. ========
  894. sympy.series.sequences.SeqAdd
  895. """
  896. def __new__(cls, *args, **kwargs):
  897. evaluate = kwargs.get('evaluate', global_parameters.evaluate)
  898. # flatten inputs
  899. args = list(args)
  900. # adapted from sympy.sets.sets.Union
  901. def _flatten(arg):
  902. if isinstance(arg, SeqBase):
  903. if isinstance(arg, SeqMul):
  904. return sum(map(_flatten, arg.args), [])
  905. else:
  906. return [arg]
  907. elif iterable(arg):
  908. return sum(map(_flatten, arg), [])
  909. raise TypeError("Input must be Sequences or "
  910. " iterables of Sequences")
  911. args = _flatten(args)
  912. # Multiplication of no sequences is EmptySequence
  913. if not args:
  914. return S.EmptySequence
  915. if Intersection(*(a.interval for a in args)) is S.EmptySet:
  916. return S.EmptySequence
  917. # reduce using known rules
  918. if evaluate:
  919. return SeqMul.reduce(args)
  920. args = list(ordered(args, SeqBase._start_key))
  921. return Basic.__new__(cls, *args)
  922. @staticmethod
  923. def reduce(args):
  924. """Simplify a :class:`SeqMul` using known rules.
  925. Explanation
  926. ===========
  927. Iterates through all pairs and ask the constituent
  928. sequences if they can simplify themselves with any other constituent.
  929. Notes
  930. =====
  931. adapted from ``Union.reduce``
  932. """
  933. new_args = True
  934. while new_args:
  935. for id1, s in enumerate(args):
  936. new_args = False
  937. for id2, t in enumerate(args):
  938. if id1 == id2:
  939. continue
  940. new_seq = s._mul(t)
  941. # This returns None if s does not know how to multiply
  942. # with t. Returns the newly multiplied sequence otherwise
  943. if new_seq is not None:
  944. new_args = [a for a in args if a not in (s, t)]
  945. new_args.append(new_seq)
  946. break
  947. if new_args:
  948. args = new_args
  949. break
  950. if len(args) == 1:
  951. return args.pop()
  952. else:
  953. return SeqMul(args, evaluate=False)
  954. def _eval_coeff(self, pt):
  955. """multiplies the coefficients of all the sequences at point pt"""
  956. val = 1
  957. for a in self.args:
  958. val *= a.coeff(pt)
  959. return val