sequences.py 35 KB

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