enumerative.py 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155
  1. """
  2. Algorithms and classes to support enumerative combinatorics.
  3. Currently just multiset partitions, but more could be added.
  4. Terminology (following Knuth, algorithm 7.1.2.5M TAOCP)
  5. *multiset* aaabbcccc has a *partition* aaabc | bccc
  6. The submultisets, aaabc and bccc of the partition are called
  7. *parts*, or sometimes *vectors*. (Knuth notes that multiset
  8. partitions can be thought of as partitions of vectors of integers,
  9. where the ith element of the vector gives the multiplicity of
  10. element i.)
  11. The values a, b and c are *components* of the multiset. These
  12. correspond to elements of a set, but in a multiset can be present
  13. with a multiplicity greater than 1.
  14. The algorithm deserves some explanation.
  15. Think of the part aaabc from the multiset above. If we impose an
  16. ordering on the components of the multiset, we can represent a part
  17. with a vector, in which the value of the first element of the vector
  18. corresponds to the multiplicity of the first component in that
  19. part. Thus, aaabc can be represented by the vector [3, 1, 1]. We
  20. can also define an ordering on parts, based on the lexicographic
  21. ordering of the vector (leftmost vector element, i.e., the element
  22. with the smallest component number, is the most significant), so
  23. that [3, 1, 1] > [3, 1, 0] and [3, 1, 1] > [2, 1, 4]. The ordering
  24. on parts can be extended to an ordering on partitions: First, sort
  25. the parts in each partition, left-to-right in decreasing order. Then
  26. partition A is greater than partition B if A's leftmost/greatest
  27. part is greater than B's leftmost part. If the leftmost parts are
  28. equal, compare the second parts, and so on.
  29. In this ordering, the greatest partition of a given multiset has only
  30. one part. The least partition is the one in which the components
  31. are spread out, one per part.
  32. The enumeration algorithms in this file yield the partitions of the
  33. argument multiset in decreasing order. The main data structure is a
  34. stack of parts, corresponding to the current partition. An
  35. important invariant is that the parts on the stack are themselves in
  36. decreasing order. This data structure is decremented to find the
  37. next smaller partition. Most often, decrementing the partition will
  38. only involve adjustments to the smallest parts at the top of the
  39. stack, much as adjacent integers *usually* differ only in their last
  40. few digits.
  41. Knuth's algorithm uses two main operations on parts:
  42. Decrement - change the part so that it is smaller in the
  43. (vector) lexicographic order, but reduced by the smallest amount possible.
  44. For example, if the multiset has vector [5,
  45. 3, 1], and the bottom/greatest part is [4, 2, 1], this part would
  46. decrement to [4, 2, 0], while [4, 0, 0] would decrement to [3, 3,
  47. 1]. A singleton part is never decremented -- [1, 0, 0] is not
  48. decremented to [0, 3, 1]. Instead, the decrement operator needs
  49. to fail for this case. In Knuth's pseudocode, the decrement
  50. operator is step m5.
  51. Spread unallocated multiplicity - Once a part has been decremented,
  52. it cannot be the rightmost part in the partition. There is some
  53. multiplicity that has not been allocated, and new parts must be
  54. created above it in the stack to use up this multiplicity. To
  55. maintain the invariant that the parts on the stack are in
  56. decreasing order, these new parts must be less than or equal to
  57. the decremented part.
  58. For example, if the multiset is [5, 3, 1], and its most
  59. significant part has just been decremented to [5, 3, 0], the
  60. spread operation will add a new part so that the stack becomes
  61. [[5, 3, 0], [0, 0, 1]]. If the most significant part (for the
  62. same multiset) has been decremented to [2, 0, 0] the stack becomes
  63. [[2, 0, 0], [2, 0, 0], [1, 3, 1]]. In the pseudocode, the spread
  64. operation for one part is step m2. The complete spread operation
  65. is a loop of steps m2 and m3.
  66. In order to facilitate the spread operation, Knuth stores, for each
  67. component of each part, not just the multiplicity of that component
  68. in the part, but also the total multiplicity available for this
  69. component in this part or any lesser part above it on the stack.
  70. One added twist is that Knuth does not represent the part vectors as
  71. arrays. Instead, he uses a sparse representation, in which a
  72. component of a part is represented as a component number (c), plus
  73. the multiplicity of the component in that part (v) as well as the
  74. total multiplicity available for that component (u). This saves
  75. time that would be spent skipping over zeros.
  76. """
  77. class PartComponent:
  78. """Internal class used in support of the multiset partitions
  79. enumerators and the associated visitor functions.
  80. Represents one component of one part of the current partition.
  81. A stack of these, plus an auxiliary frame array, f, represents a
  82. partition of the multiset.
  83. Knuth's pseudocode makes c, u, and v separate arrays.
  84. """
  85. __slots__ = ('c', 'u', 'v')
  86. def __init__(self):
  87. self.c = 0 # Component number
  88. self.u = 0 # The as yet unpartitioned amount in component c
  89. # *before* it is allocated by this triple
  90. self.v = 0 # Amount of c component in the current part
  91. # (v<=u). An invariant of the representation is
  92. # that the next higher triple for this component
  93. # (if there is one) will have a value of u-v in
  94. # its u attribute.
  95. def __repr__(self):
  96. "for debug/algorithm animation purposes"
  97. return 'c:%d u:%d v:%d' % (self.c, self.u, self.v)
  98. def __eq__(self, other):
  99. """Define value oriented equality, which is useful for testers"""
  100. return (isinstance(other, self.__class__) and
  101. self.c == other.c and
  102. self.u == other.u and
  103. self.v == other.v)
  104. def __ne__(self, other):
  105. """Defined for consistency with __eq__"""
  106. return not self == other
  107. # This function tries to be a faithful implementation of algorithm
  108. # 7.1.2.5M in Volume 4A, Combinatoral Algorithms, Part 1, of The Art
  109. # of Computer Programming, by Donald Knuth. This includes using
  110. # (mostly) the same variable names, etc. This makes for rather
  111. # low-level Python.
  112. # Changes from Knuth's pseudocode include
  113. # - use PartComponent struct/object instead of 3 arrays
  114. # - make the function a generator
  115. # - map (with some difficulty) the GOTOs to Python control structures.
  116. # - Knuth uses 1-based numbering for components, this code is 0-based
  117. # - renamed variable l to lpart.
  118. # - flag variable x takes on values True/False instead of 1/0
  119. #
  120. def multiset_partitions_taocp(multiplicities):
  121. """Enumerates partitions of a multiset.
  122. Parameters
  123. ==========
  124. multiplicities
  125. list of integer multiplicities of the components of the multiset.
  126. Yields
  127. ======
  128. state
  129. Internal data structure which encodes a particular partition.
  130. This output is then usually processed by a visitor function
  131. which combines the information from this data structure with
  132. the components themselves to produce an actual partition.
  133. Unless they wish to create their own visitor function, users will
  134. have little need to look inside this data structure. But, for
  135. reference, it is a 3-element list with components:
  136. f
  137. is a frame array, which is used to divide pstack into parts.
  138. lpart
  139. points to the base of the topmost part.
  140. pstack
  141. is an array of PartComponent objects.
  142. The ``state`` output offers a peek into the internal data
  143. structures of the enumeration function. The client should
  144. treat this as read-only; any modification of the data
  145. structure will cause unpredictable (and almost certainly
  146. incorrect) results. Also, the components of ``state`` are
  147. modified in place at each iteration. Hence, the visitor must
  148. be called at each loop iteration. Accumulating the ``state``
  149. instances and processing them later will not work.
  150. Examples
  151. ========
  152. >>> from sympy.utilities.enumerative import list_visitor
  153. >>> from sympy.utilities.enumerative import multiset_partitions_taocp
  154. >>> # variables components and multiplicities represent the multiset 'abb'
  155. >>> components = 'ab'
  156. >>> multiplicities = [1, 2]
  157. >>> states = multiset_partitions_taocp(multiplicities)
  158. >>> list(list_visitor(state, components) for state in states)
  159. [[['a', 'b', 'b']],
  160. [['a', 'b'], ['b']],
  161. [['a'], ['b', 'b']],
  162. [['a'], ['b'], ['b']]]
  163. See Also
  164. ========
  165. sympy.utilities.iterables.multiset_partitions: Takes a multiset
  166. as input and directly yields multiset partitions. It
  167. dispatches to a number of functions, including this one, for
  168. implementation. Most users will find it more convenient to
  169. use than multiset_partitions_taocp.
  170. """
  171. # Important variables.
  172. # m is the number of components, i.e., number of distinct elements
  173. m = len(multiplicities)
  174. # n is the cardinality, total number of elements whether or not distinct
  175. n = sum(multiplicities)
  176. # The main data structure, f segments pstack into parts. See
  177. # list_visitor() for example code indicating how this internal
  178. # state corresponds to a partition.
  179. # Note: allocation of space for stack is conservative. Knuth's
  180. # exercise 7.2.1.5.68 gives some indication of how to tighten this
  181. # bound, but this is not implemented.
  182. pstack = [PartComponent() for i in range(n * m + 1)]
  183. f = [0] * (n + 1)
  184. # Step M1 in Knuth (Initialize)
  185. # Initial state - entire multiset in one part.
  186. for j in range(m):
  187. ps = pstack[j]
  188. ps.c = j
  189. ps.u = multiplicities[j]
  190. ps.v = multiplicities[j]
  191. # Other variables
  192. f[0] = 0
  193. a = 0
  194. lpart = 0
  195. f[1] = m
  196. b = m # in general, current stack frame is from a to b - 1
  197. while True:
  198. while True:
  199. # Step M2 (Subtract v from u)
  200. k = b
  201. x = False
  202. for j in range(a, b):
  203. pstack[k].u = pstack[j].u - pstack[j].v
  204. if pstack[k].u == 0:
  205. x = True
  206. elif not x:
  207. pstack[k].c = pstack[j].c
  208. pstack[k].v = min(pstack[j].v, pstack[k].u)
  209. x = pstack[k].u < pstack[j].v
  210. k = k + 1
  211. else: # x is True
  212. pstack[k].c = pstack[j].c
  213. pstack[k].v = pstack[k].u
  214. k = k + 1
  215. # Note: x is True iff v has changed
  216. # Step M3 (Push if nonzero.)
  217. if k > b:
  218. a = b
  219. b = k
  220. lpart = lpart + 1
  221. f[lpart + 1] = b
  222. # Return to M2
  223. else:
  224. break # Continue to M4
  225. # M4 Visit a partition
  226. state = [f, lpart, pstack]
  227. yield state
  228. # M5 (Decrease v)
  229. while True:
  230. j = b-1
  231. while (pstack[j].v == 0):
  232. j = j - 1
  233. if j == a and pstack[j].v == 1:
  234. # M6 (Backtrack)
  235. if lpart == 0:
  236. return
  237. lpart = lpart - 1
  238. b = a
  239. a = f[lpart]
  240. # Return to M5
  241. else:
  242. pstack[j].v = pstack[j].v - 1
  243. for k in range(j + 1, b):
  244. pstack[k].v = pstack[k].u
  245. break # GOTO M2
  246. # --------------- Visitor functions for multiset partitions ---------------
  247. # A visitor takes the partition state generated by
  248. # multiset_partitions_taocp or other enumerator, and produces useful
  249. # output (such as the actual partition).
  250. def factoring_visitor(state, primes):
  251. """Use with multiset_partitions_taocp to enumerate the ways a
  252. number can be expressed as a product of factors. For this usage,
  253. the exponents of the prime factors of a number are arguments to
  254. the partition enumerator, while the corresponding prime factors
  255. are input here.
  256. Examples
  257. ========
  258. To enumerate the factorings of a number we can think of the elements of the
  259. partition as being the prime factors and the multiplicities as being their
  260. exponents.
  261. >>> from sympy.utilities.enumerative import factoring_visitor
  262. >>> from sympy.utilities.enumerative import multiset_partitions_taocp
  263. >>> from sympy import factorint
  264. >>> primes, multiplicities = zip(*factorint(24).items())
  265. >>> primes
  266. (2, 3)
  267. >>> multiplicities
  268. (3, 1)
  269. >>> states = multiset_partitions_taocp(multiplicities)
  270. >>> list(factoring_visitor(state, primes) for state in states)
  271. [[24], [8, 3], [12, 2], [4, 6], [4, 2, 3], [6, 2, 2], [2, 2, 2, 3]]
  272. """
  273. f, lpart, pstack = state
  274. factoring = []
  275. for i in range(lpart + 1):
  276. factor = 1
  277. for ps in pstack[f[i]: f[i + 1]]:
  278. if ps.v > 0:
  279. factor *= primes[ps.c] ** ps.v
  280. factoring.append(factor)
  281. return factoring
  282. def list_visitor(state, components):
  283. """Return a list of lists to represent the partition.
  284. Examples
  285. ========
  286. >>> from sympy.utilities.enumerative import list_visitor
  287. >>> from sympy.utilities.enumerative import multiset_partitions_taocp
  288. >>> states = multiset_partitions_taocp([1, 2, 1])
  289. >>> s = next(states)
  290. >>> list_visitor(s, 'abc') # for multiset 'a b b c'
  291. [['a', 'b', 'b', 'c']]
  292. >>> s = next(states)
  293. >>> list_visitor(s, [1, 2, 3]) # for multiset '1 2 2 3
  294. [[1, 2, 2], [3]]
  295. """
  296. f, lpart, pstack = state
  297. partition = []
  298. for i in range(lpart+1):
  299. part = []
  300. for ps in pstack[f[i]:f[i+1]]:
  301. if ps.v > 0:
  302. part.extend([components[ps.c]] * ps.v)
  303. partition.append(part)
  304. return partition
  305. class MultisetPartitionTraverser():
  306. """
  307. Has methods to ``enumerate`` and ``count`` the partitions of a multiset.
  308. This implements a refactored and extended version of Knuth's algorithm
  309. 7.1.2.5M [AOCP]_."
  310. The enumeration methods of this class are generators and return
  311. data structures which can be interpreted by the same visitor
  312. functions used for the output of ``multiset_partitions_taocp``.
  313. Examples
  314. ========
  315. >>> from sympy.utilities.enumerative import MultisetPartitionTraverser
  316. >>> m = MultisetPartitionTraverser()
  317. >>> m.count_partitions([4,4,4,2])
  318. 127750
  319. >>> m.count_partitions([3,3,3])
  320. 686
  321. See Also
  322. ========
  323. multiset_partitions_taocp
  324. sympy.utilities.iterables.multiset_partitions
  325. References
  326. ==========
  327. .. [AOCP] Algorithm 7.1.2.5M in Volume 4A, Combinatoral Algorithms,
  328. Part 1, of The Art of Computer Programming, by Donald Knuth.
  329. .. [Factorisatio] On a Problem of Oppenheim concerning
  330. "Factorisatio Numerorum" E. R. Canfield, Paul Erdos, Carl
  331. Pomerance, JOURNAL OF NUMBER THEORY, Vol. 17, No. 1. August
  332. 1983. See section 7 for a description of an algorithm
  333. similar to Knuth's.
  334. .. [Yorgey] Generating Multiset Partitions, Brent Yorgey, The
  335. Monad.Reader, Issue 8, September 2007.
  336. """
  337. def __init__(self):
  338. self.debug = False
  339. # TRACING variables. These are useful for gathering
  340. # statistics on the algorithm itself, but have no particular
  341. # benefit to a user of the code.
  342. self.k1 = 0
  343. self.k2 = 0
  344. self.p1 = 0
  345. self.pstack = None
  346. self.f = None
  347. self.lpart = 0
  348. self.discarded = 0
  349. # dp_stack is list of lists of (part_key, start_count) pairs
  350. self.dp_stack = []
  351. # dp_map is map part_key-> count, where count represents the
  352. # number of multiset which are descendants of a part with this
  353. # key, **or any of its decrements**
  354. # Thus, when we find a part in the map, we add its count
  355. # value to the running total, cut off the enumeration, and
  356. # backtrack
  357. if not hasattr(self, 'dp_map'):
  358. self.dp_map = {}
  359. def db_trace(self, msg):
  360. """Useful for understanding/debugging the algorithms. Not
  361. generally activated in end-user code."""
  362. if self.debug:
  363. # XXX: animation_visitor is undefined... Clearly this does not
  364. # work and was not tested. Previous code in comments below.
  365. raise RuntimeError
  366. #letters = 'abcdefghijklmnopqrstuvwxyz'
  367. #state = [self.f, self.lpart, self.pstack]
  368. #print("DBG:", msg,
  369. # ["".join(part) for part in list_visitor(state, letters)],
  370. # animation_visitor(state))
  371. #
  372. # Helper methods for enumeration
  373. #
  374. def _initialize_enumeration(self, multiplicities):
  375. """Allocates and initializes the partition stack.
  376. This is called from the enumeration/counting routines, so
  377. there is no need to call it separately."""
  378. num_components = len(multiplicities)
  379. # cardinality is the total number of elements, whether or not distinct
  380. cardinality = sum(multiplicities)
  381. # pstack is the partition stack, which is segmented by
  382. # f into parts.
  383. self.pstack = [PartComponent() for i in
  384. range(num_components * cardinality + 1)]
  385. self.f = [0] * (cardinality + 1)
  386. # Initial state - entire multiset in one part.
  387. for j in range(num_components):
  388. ps = self.pstack[j]
  389. ps.c = j
  390. ps.u = multiplicities[j]
  391. ps.v = multiplicities[j]
  392. self.f[0] = 0
  393. self.f[1] = num_components
  394. self.lpart = 0
  395. # The decrement_part() method corresponds to step M5 in Knuth's
  396. # algorithm. This is the base version for enum_all(). Modified
  397. # versions of this method are needed if we want to restrict
  398. # sizes of the partitions produced.
  399. def decrement_part(self, part):
  400. """Decrements part (a subrange of pstack), if possible, returning
  401. True iff the part was successfully decremented.
  402. If you think of the v values in the part as a multi-digit
  403. integer (least significant digit on the right) this is
  404. basically decrementing that integer, but with the extra
  405. constraint that the leftmost digit cannot be decremented to 0.
  406. Parameters
  407. ==========
  408. part
  409. The part, represented as a list of PartComponent objects,
  410. which is to be decremented.
  411. """
  412. plen = len(part)
  413. for j in range(plen - 1, -1, -1):
  414. if j == 0 and part[j].v > 1 or j > 0 and part[j].v > 0:
  415. # found val to decrement
  416. part[j].v -= 1
  417. # Reset trailing parts back to maximum
  418. for k in range(j + 1, plen):
  419. part[k].v = part[k].u
  420. return True
  421. return False
  422. # Version to allow number of parts to be bounded from above.
  423. # Corresponds to (a modified) step M5.
  424. def decrement_part_small(self, part, ub):
  425. """Decrements part (a subrange of pstack), if possible, returning
  426. True iff the part was successfully decremented.
  427. Parameters
  428. ==========
  429. part
  430. part to be decremented (topmost part on the stack)
  431. ub
  432. the maximum number of parts allowed in a partition
  433. returned by the calling traversal.
  434. Notes
  435. =====
  436. The goal of this modification of the ordinary decrement method
  437. is to fail (meaning that the subtree rooted at this part is to
  438. be skipped) when it can be proved that this part can only have
  439. child partitions which are larger than allowed by ``ub``. If a
  440. decision is made to fail, it must be accurate, otherwise the
  441. enumeration will miss some partitions. But, it is OK not to
  442. capture all the possible failures -- if a part is passed that
  443. should not be, the resulting too-large partitions are filtered
  444. by the enumeration one level up. However, as is usual in
  445. constrained enumerations, failing early is advantageous.
  446. The tests used by this method catch the most common cases,
  447. although this implementation is by no means the last word on
  448. this problem. The tests include:
  449. 1) ``lpart`` must be less than ``ub`` by at least 2. This is because
  450. once a part has been decremented, the partition
  451. will gain at least one child in the spread step.
  452. 2) If the leading component of the part is about to be
  453. decremented, check for how many parts will be added in
  454. order to use up the unallocated multiplicity in that
  455. leading component, and fail if this number is greater than
  456. allowed by ``ub``. (See code for the exact expression.) This
  457. test is given in the answer to Knuth's problem 7.2.1.5.69.
  458. 3) If there is *exactly* enough room to expand the leading
  459. component by the above test, check the next component (if
  460. it exists) once decrementing has finished. If this has
  461. ``v == 0``, this next component will push the expansion over the
  462. limit by 1, so fail.
  463. """
  464. if self.lpart >= ub - 1:
  465. self.p1 += 1 # increment to keep track of usefulness of tests
  466. return False
  467. plen = len(part)
  468. for j in range(plen - 1, -1, -1):
  469. # Knuth's mod, (answer to problem 7.2.1.5.69)
  470. if j == 0 and (part[0].v - 1)*(ub - self.lpart) < part[0].u:
  471. self.k1 += 1
  472. return False
  473. if j == 0 and part[j].v > 1 or j > 0 and part[j].v > 0:
  474. # found val to decrement
  475. part[j].v -= 1
  476. # Reset trailing parts back to maximum
  477. for k in range(j + 1, plen):
  478. part[k].v = part[k].u
  479. # Have now decremented part, but are we doomed to
  480. # failure when it is expanded? Check one oddball case
  481. # that turns out to be surprisingly common - exactly
  482. # enough room to expand the leading component, but no
  483. # room for the second component, which has v=0.
  484. if (plen > 1 and part[1].v == 0 and
  485. (part[0].u - part[0].v) ==
  486. ((ub - self.lpart - 1) * part[0].v)):
  487. self.k2 += 1
  488. self.db_trace("Decrement fails test 3")
  489. return False
  490. return True
  491. return False
  492. def decrement_part_large(self, part, amt, lb):
  493. """Decrements part, while respecting size constraint.
  494. A part can have no children which are of sufficient size (as
  495. indicated by ``lb``) unless that part has sufficient
  496. unallocated multiplicity. When enforcing the size constraint,
  497. this method will decrement the part (if necessary) by an
  498. amount needed to ensure sufficient unallocated multiplicity.
  499. Returns True iff the part was successfully decremented.
  500. Parameters
  501. ==========
  502. part
  503. part to be decremented (topmost part on the stack)
  504. amt
  505. Can only take values 0 or 1. A value of 1 means that the
  506. part must be decremented, and then the size constraint is
  507. enforced. A value of 0 means just to enforce the ``lb``
  508. size constraint.
  509. lb
  510. The partitions produced by the calling enumeration must
  511. have more parts than this value.
  512. """
  513. if amt == 1:
  514. # In this case we always need to decrement, *before*
  515. # enforcing the "sufficient unallocated multiplicity"
  516. # constraint. Easiest for this is just to call the
  517. # regular decrement method.
  518. if not self.decrement_part(part):
  519. return False
  520. # Next, perform any needed additional decrementing to respect
  521. # "sufficient unallocated multiplicity" (or fail if this is
  522. # not possible).
  523. min_unalloc = lb - self.lpart
  524. if min_unalloc <= 0:
  525. return True
  526. total_mult = sum(pc.u for pc in part)
  527. total_alloc = sum(pc.v for pc in part)
  528. if total_mult <= min_unalloc:
  529. return False
  530. deficit = min_unalloc - (total_mult - total_alloc)
  531. if deficit <= 0:
  532. return True
  533. for i in range(len(part) - 1, -1, -1):
  534. if i == 0:
  535. if part[0].v > deficit:
  536. part[0].v -= deficit
  537. return True
  538. else:
  539. return False # This shouldn't happen, due to above check
  540. else:
  541. if part[i].v >= deficit:
  542. part[i].v -= deficit
  543. return True
  544. else:
  545. deficit -= part[i].v
  546. part[i].v = 0
  547. def decrement_part_range(self, part, lb, ub):
  548. """Decrements part (a subrange of pstack), if possible, returning
  549. True iff the part was successfully decremented.
  550. Parameters
  551. ==========
  552. part
  553. part to be decremented (topmost part on the stack)
  554. ub
  555. the maximum number of parts allowed in a partition
  556. returned by the calling traversal.
  557. lb
  558. The partitions produced by the calling enumeration must
  559. have more parts than this value.
  560. Notes
  561. =====
  562. Combines the constraints of _small and _large decrement
  563. methods. If returns success, part has been decremented at
  564. least once, but perhaps by quite a bit more if needed to meet
  565. the lb constraint.
  566. """
  567. # Constraint in the range case is just enforcing both the
  568. # constraints from _small and _large cases. Note the 0 as the
  569. # second argument to the _large call -- this is the signal to
  570. # decrement only as needed to for constraint enforcement. The
  571. # short circuiting and left-to-right order of the 'and'
  572. # operator is important for this to work correctly.
  573. return self.decrement_part_small(part, ub) and \
  574. self.decrement_part_large(part, 0, lb)
  575. def spread_part_multiplicity(self):
  576. """Returns True if a new part has been created, and
  577. adjusts pstack, f and lpart as needed.
  578. Notes
  579. =====
  580. Spreads unallocated multiplicity from the current top part
  581. into a new part created above the current on the stack. This
  582. new part is constrained to be less than or equal to the old in
  583. terms of the part ordering.
  584. This call does nothing (and returns False) if the current top
  585. part has no unallocated multiplicity.
  586. """
  587. j = self.f[self.lpart] # base of current top part
  588. k = self.f[self.lpart + 1] # ub of current; potential base of next
  589. base = k # save for later comparison
  590. changed = False # Set to true when the new part (so far) is
  591. # strictly less than (as opposed to less than
  592. # or equal) to the old.
  593. for j in range(self.f[self.lpart], self.f[self.lpart + 1]):
  594. self.pstack[k].u = self.pstack[j].u - self.pstack[j].v
  595. if self.pstack[k].u == 0:
  596. changed = True
  597. else:
  598. self.pstack[k].c = self.pstack[j].c
  599. if changed: # Put all available multiplicity in this part
  600. self.pstack[k].v = self.pstack[k].u
  601. else: # Still maintaining ordering constraint
  602. if self.pstack[k].u < self.pstack[j].v:
  603. self.pstack[k].v = self.pstack[k].u
  604. changed = True
  605. else:
  606. self.pstack[k].v = self.pstack[j].v
  607. k = k + 1
  608. if k > base:
  609. # Adjust for the new part on stack
  610. self.lpart = self.lpart + 1
  611. self.f[self.lpart + 1] = k
  612. return True
  613. return False
  614. def top_part(self):
  615. """Return current top part on the stack, as a slice of pstack.
  616. """
  617. return self.pstack[self.f[self.lpart]:self.f[self.lpart + 1]]
  618. # Same interface and functionality as multiset_partitions_taocp(),
  619. # but some might find this refactored version easier to follow.
  620. def enum_all(self, multiplicities):
  621. """Enumerate the partitions of a multiset.
  622. Examples
  623. ========
  624. >>> from sympy.utilities.enumerative import list_visitor
  625. >>> from sympy.utilities.enumerative import MultisetPartitionTraverser
  626. >>> m = MultisetPartitionTraverser()
  627. >>> states = m.enum_all([2,2])
  628. >>> list(list_visitor(state, 'ab') for state in states)
  629. [[['a', 'a', 'b', 'b']],
  630. [['a', 'a', 'b'], ['b']],
  631. [['a', 'a'], ['b', 'b']],
  632. [['a', 'a'], ['b'], ['b']],
  633. [['a', 'b', 'b'], ['a']],
  634. [['a', 'b'], ['a', 'b']],
  635. [['a', 'b'], ['a'], ['b']],
  636. [['a'], ['a'], ['b', 'b']],
  637. [['a'], ['a'], ['b'], ['b']]]
  638. See Also
  639. ========
  640. multiset_partitions_taocp:
  641. which provides the same result as this method, but is
  642. about twice as fast. Hence, enum_all is primarily useful
  643. for testing. Also see the function for a discussion of
  644. states and visitors.
  645. """
  646. self._initialize_enumeration(multiplicities)
  647. while True:
  648. while self.spread_part_multiplicity():
  649. pass
  650. # M4 Visit a partition
  651. state = [self.f, self.lpart, self.pstack]
  652. yield state
  653. # M5 (Decrease v)
  654. while not self.decrement_part(self.top_part()):
  655. # M6 (Backtrack)
  656. if self.lpart == 0:
  657. return
  658. self.lpart -= 1
  659. def enum_small(self, multiplicities, ub):
  660. """Enumerate multiset partitions with no more than ``ub`` parts.
  661. Equivalent to enum_range(multiplicities, 0, ub)
  662. Parameters
  663. ==========
  664. multiplicities
  665. list of multiplicities of the components of the multiset.
  666. ub
  667. Maximum number of parts
  668. Examples
  669. ========
  670. >>> from sympy.utilities.enumerative import list_visitor
  671. >>> from sympy.utilities.enumerative import MultisetPartitionTraverser
  672. >>> m = MultisetPartitionTraverser()
  673. >>> states = m.enum_small([2,2], 2)
  674. >>> list(list_visitor(state, 'ab') for state in states)
  675. [[['a', 'a', 'b', 'b']],
  676. [['a', 'a', 'b'], ['b']],
  677. [['a', 'a'], ['b', 'b']],
  678. [['a', 'b', 'b'], ['a']],
  679. [['a', 'b'], ['a', 'b']]]
  680. The implementation is based, in part, on the answer given to
  681. exercise 69, in Knuth [AOCP]_.
  682. See Also
  683. ========
  684. enum_all, enum_large, enum_range
  685. """
  686. # Keep track of iterations which do not yield a partition.
  687. # Clearly, we would like to keep this number small.
  688. self.discarded = 0
  689. if ub <= 0:
  690. return
  691. self._initialize_enumeration(multiplicities)
  692. while True:
  693. while self.spread_part_multiplicity():
  694. self.db_trace('spread 1')
  695. if self.lpart >= ub:
  696. self.discarded += 1
  697. self.db_trace(' Discarding')
  698. self.lpart = ub - 2
  699. break
  700. else:
  701. # M4 Visit a partition
  702. state = [self.f, self.lpart, self.pstack]
  703. yield state
  704. # M5 (Decrease v)
  705. while not self.decrement_part_small(self.top_part(), ub):
  706. self.db_trace("Failed decrement, going to backtrack")
  707. # M6 (Backtrack)
  708. if self.lpart == 0:
  709. return
  710. self.lpart -= 1
  711. self.db_trace("Backtracked to")
  712. self.db_trace("decrement ok, about to expand")
  713. def enum_large(self, multiplicities, lb):
  714. """Enumerate the partitions of a multiset with lb < num(parts)
  715. Equivalent to enum_range(multiplicities, lb, sum(multiplicities))
  716. Parameters
  717. ==========
  718. multiplicities
  719. list of multiplicities of the components of the multiset.
  720. lb
  721. Number of parts in the partition must be greater than
  722. this lower bound.
  723. Examples
  724. ========
  725. >>> from sympy.utilities.enumerative import list_visitor
  726. >>> from sympy.utilities.enumerative import MultisetPartitionTraverser
  727. >>> m = MultisetPartitionTraverser()
  728. >>> states = m.enum_large([2,2], 2)
  729. >>> list(list_visitor(state, 'ab') for state in states)
  730. [[['a', 'a'], ['b'], ['b']],
  731. [['a', 'b'], ['a'], ['b']],
  732. [['a'], ['a'], ['b', 'b']],
  733. [['a'], ['a'], ['b'], ['b']]]
  734. See Also
  735. ========
  736. enum_all, enum_small, enum_range
  737. """
  738. self.discarded = 0
  739. if lb >= sum(multiplicities):
  740. return
  741. self._initialize_enumeration(multiplicities)
  742. self.decrement_part_large(self.top_part(), 0, lb)
  743. while True:
  744. good_partition = True
  745. while self.spread_part_multiplicity():
  746. if not self.decrement_part_large(self.top_part(), 0, lb):
  747. # Failure here should be rare/impossible
  748. self.discarded += 1
  749. good_partition = False
  750. break
  751. # M4 Visit a partition
  752. if good_partition:
  753. state = [self.f, self.lpart, self.pstack]
  754. yield state
  755. # M5 (Decrease v)
  756. while not self.decrement_part_large(self.top_part(), 1, lb):
  757. # M6 (Backtrack)
  758. if self.lpart == 0:
  759. return
  760. self.lpart -= 1
  761. def enum_range(self, multiplicities, lb, ub):
  762. """Enumerate the partitions of a multiset with
  763. ``lb < num(parts) <= ub``.
  764. In particular, if partitions with exactly ``k`` parts are
  765. desired, call with ``(multiplicities, k - 1, k)``. This
  766. method generalizes enum_all, enum_small, and enum_large.
  767. Examples
  768. ========
  769. >>> from sympy.utilities.enumerative import list_visitor
  770. >>> from sympy.utilities.enumerative import MultisetPartitionTraverser
  771. >>> m = MultisetPartitionTraverser()
  772. >>> states = m.enum_range([2,2], 1, 2)
  773. >>> list(list_visitor(state, 'ab') for state in states)
  774. [[['a', 'a', 'b'], ['b']],
  775. [['a', 'a'], ['b', 'b']],
  776. [['a', 'b', 'b'], ['a']],
  777. [['a', 'b'], ['a', 'b']]]
  778. """
  779. # combine the constraints of the _large and _small
  780. # enumerations.
  781. self.discarded = 0
  782. if ub <= 0 or lb >= sum(multiplicities):
  783. return
  784. self._initialize_enumeration(multiplicities)
  785. self.decrement_part_large(self.top_part(), 0, lb)
  786. while True:
  787. good_partition = True
  788. while self.spread_part_multiplicity():
  789. self.db_trace("spread 1")
  790. if not self.decrement_part_large(self.top_part(), 0, lb):
  791. # Failure here - possible in range case?
  792. self.db_trace(" Discarding (large cons)")
  793. self.discarded += 1
  794. good_partition = False
  795. break
  796. elif self.lpart >= ub:
  797. self.discarded += 1
  798. good_partition = False
  799. self.db_trace(" Discarding small cons")
  800. self.lpart = ub - 2
  801. break
  802. # M4 Visit a partition
  803. if good_partition:
  804. state = [self.f, self.lpart, self.pstack]
  805. yield state
  806. # M5 (Decrease v)
  807. while not self.decrement_part_range(self.top_part(), lb, ub):
  808. self.db_trace("Failed decrement, going to backtrack")
  809. # M6 (Backtrack)
  810. if self.lpart == 0:
  811. return
  812. self.lpart -= 1
  813. self.db_trace("Backtracked to")
  814. self.db_trace("decrement ok, about to expand")
  815. def count_partitions_slow(self, multiplicities):
  816. """Returns the number of partitions of a multiset whose elements
  817. have the multiplicities given in ``multiplicities``.
  818. Primarily for comparison purposes. It follows the same path as
  819. enumerate, and counts, rather than generates, the partitions.
  820. See Also
  821. ========
  822. count_partitions
  823. Has the same calling interface, but is much faster.
  824. """
  825. # number of partitions so far in the enumeration
  826. self.pcount = 0
  827. self._initialize_enumeration(multiplicities)
  828. while True:
  829. while self.spread_part_multiplicity():
  830. pass
  831. # M4 Visit (count) a partition
  832. self.pcount += 1
  833. # M5 (Decrease v)
  834. while not self.decrement_part(self.top_part()):
  835. # M6 (Backtrack)
  836. if self.lpart == 0:
  837. return self.pcount
  838. self.lpart -= 1
  839. def count_partitions(self, multiplicities):
  840. """Returns the number of partitions of a multiset whose components
  841. have the multiplicities given in ``multiplicities``.
  842. For larger counts, this method is much faster than calling one
  843. of the enumerators and counting the result. Uses dynamic
  844. programming to cut down on the number of nodes actually
  845. explored. The dictionary used in order to accelerate the
  846. counting process is stored in the ``MultisetPartitionTraverser``
  847. object and persists across calls. If the user does not
  848. expect to call ``count_partitions`` for any additional
  849. multisets, the object should be cleared to save memory. On
  850. the other hand, the cache built up from one count run can
  851. significantly speed up subsequent calls to ``count_partitions``,
  852. so it may be advantageous not to clear the object.
  853. Examples
  854. ========
  855. >>> from sympy.utilities.enumerative import MultisetPartitionTraverser
  856. >>> m = MultisetPartitionTraverser()
  857. >>> m.count_partitions([9,8,2])
  858. 288716
  859. >>> m.count_partitions([2,2])
  860. 9
  861. >>> del m
  862. Notes
  863. =====
  864. If one looks at the workings of Knuth's algorithm M [AOCP]_, it
  865. can be viewed as a traversal of a binary tree of parts. A
  866. part has (up to) two children, the left child resulting from
  867. the spread operation, and the right child from the decrement
  868. operation. The ordinary enumeration of multiset partitions is
  869. an in-order traversal of this tree, and with the partitions
  870. corresponding to paths from the root to the leaves. The
  871. mapping from paths to partitions is a little complicated,
  872. since the partition would contain only those parts which are
  873. leaves or the parents of a spread link, not those which are
  874. parents of a decrement link.
  875. For counting purposes, it is sufficient to count leaves, and
  876. this can be done with a recursive in-order traversal. The
  877. number of leaves of a subtree rooted at a particular part is a
  878. function only of that part itself, so memoizing has the
  879. potential to speed up the counting dramatically.
  880. This method follows a computational approach which is similar
  881. to the hypothetical memoized recursive function, but with two
  882. differences:
  883. 1) This method is iterative, borrowing its structure from the
  884. other enumerations and maintaining an explicit stack of
  885. parts which are in the process of being counted. (There
  886. may be multisets which can be counted reasonably quickly by
  887. this implementation, but which would overflow the default
  888. Python recursion limit with a recursive implementation.)
  889. 2) Instead of using the part data structure directly, a more
  890. compact key is constructed. This saves space, but more
  891. importantly coalesces some parts which would remain
  892. separate with physical keys.
  893. Unlike the enumeration functions, there is currently no _range
  894. version of count_partitions. If someone wants to stretch
  895. their brain, it should be possible to construct one by
  896. memoizing with a histogram of counts rather than a single
  897. count, and combining the histograms.
  898. """
  899. # number of partitions so far in the enumeration
  900. self.pcount = 0
  901. # dp_stack is list of lists of (part_key, start_count) pairs
  902. self.dp_stack = []
  903. self._initialize_enumeration(multiplicities)
  904. pkey = part_key(self.top_part())
  905. self.dp_stack.append([(pkey, 0), ])
  906. while True:
  907. while self.spread_part_multiplicity():
  908. pkey = part_key(self.top_part())
  909. if pkey in self.dp_map:
  910. # Already have a cached value for the count of the
  911. # subtree rooted at this part. Add it to the
  912. # running counter, and break out of the spread
  913. # loop. The -1 below is to compensate for the
  914. # leaf that this code path would otherwise find,
  915. # and which gets incremented for below.
  916. self.pcount += (self.dp_map[pkey] - 1)
  917. self.lpart -= 1
  918. break
  919. else:
  920. self.dp_stack.append([(pkey, self.pcount), ])
  921. # M4 count a leaf partition
  922. self.pcount += 1
  923. # M5 (Decrease v)
  924. while not self.decrement_part(self.top_part()):
  925. # M6 (Backtrack)
  926. for key, oldcount in self.dp_stack.pop():
  927. self.dp_map[key] = self.pcount - oldcount
  928. if self.lpart == 0:
  929. return self.pcount
  930. self.lpart -= 1
  931. # At this point have successfully decremented the part on
  932. # the stack and it does not appear in the cache. It needs
  933. # to be added to the list at the top of dp_stack
  934. pkey = part_key(self.top_part())
  935. self.dp_stack[-1].append((pkey, self.pcount),)
  936. def part_key(part):
  937. """Helper for MultisetPartitionTraverser.count_partitions that
  938. creates a key for ``part``, that only includes information which can
  939. affect the count for that part. (Any irrelevant information just
  940. reduces the effectiveness of dynamic programming.)
  941. Notes
  942. =====
  943. This member function is a candidate for future exploration. There
  944. are likely symmetries that can be exploited to coalesce some
  945. ``part_key`` values, and thereby save space and improve
  946. performance.
  947. """
  948. # The component number is irrelevant for counting partitions, so
  949. # leave it out of the memo key.
  950. rval = []
  951. for ps in part:
  952. rval.append(ps.u)
  953. rval.append(ps.v)
  954. return tuple(rval)