test_enumerative.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. from itertools import zip_longest
  2. from sympy.utilities.enumerative import (
  3. list_visitor,
  4. MultisetPartitionTraverser,
  5. multiset_partitions_taocp
  6. )
  7. from sympy.utilities.iterables import _set_partitions
  8. # first some functions only useful as test scaffolding - these provide
  9. # straightforward, but slow reference implementations against which to
  10. # compare the real versions, and also a comparison to verify that
  11. # different versions are giving identical results.
  12. def part_range_filter(partition_iterator, lb, ub):
  13. """
  14. Filters (on the number of parts) a multiset partition enumeration
  15. Arguments
  16. =========
  17. lb, and ub are a range (in the Python slice sense) on the lpart
  18. variable returned from a multiset partition enumeration. Recall
  19. that lpart is 0-based (it points to the topmost part on the part
  20. stack), so if you want to return parts of sizes 2,3,4,5 you would
  21. use lb=1 and ub=5.
  22. """
  23. for state in partition_iterator:
  24. f, lpart, pstack = state
  25. if lpart >= lb and lpart < ub:
  26. yield state
  27. def multiset_partitions_baseline(multiplicities, components):
  28. """Enumerates partitions of a multiset
  29. Parameters
  30. ==========
  31. multiplicities
  32. list of integer multiplicities of the components of the multiset.
  33. components
  34. the components (elements) themselves
  35. Returns
  36. =======
  37. Set of partitions. Each partition is tuple of parts, and each
  38. part is a tuple of components (with repeats to indicate
  39. multiplicity)
  40. Notes
  41. =====
  42. Multiset partitions can be created as equivalence classes of set
  43. partitions, and this function does just that. This approach is
  44. slow and memory intensive compared to the more advanced algorithms
  45. available, but the code is simple and easy to understand. Hence
  46. this routine is strictly for testing -- to provide a
  47. straightforward baseline against which to regress the production
  48. versions. (This code is a simplified version of an earlier
  49. production implementation.)
  50. """
  51. canon = [] # list of components with repeats
  52. for ct, elem in zip(multiplicities, components):
  53. canon.extend([elem]*ct)
  54. # accumulate the multiset partitions in a set to eliminate dups
  55. cache = set()
  56. n = len(canon)
  57. for nc, q in _set_partitions(n):
  58. rv = [[] for i in range(nc)]
  59. for i in range(n):
  60. rv[q[i]].append(canon[i])
  61. canonical = tuple(
  62. sorted([tuple(p) for p in rv]))
  63. cache.add(canonical)
  64. return cache
  65. def compare_multiset_w_baseline(multiplicities):
  66. """
  67. Enumerates the partitions of multiset with AOCP algorithm and
  68. baseline implementation, and compare the results.
  69. """
  70. letters = "abcdefghijklmnopqrstuvwxyz"
  71. bl_partitions = multiset_partitions_baseline(multiplicities, letters)
  72. # The partitions returned by the different algorithms may have
  73. # their parts in different orders. Also, they generate partitions
  74. # in different orders. Hence the sorting, and set comparison.
  75. aocp_partitions = set()
  76. for state in multiset_partitions_taocp(multiplicities):
  77. p1 = tuple(sorted(
  78. [tuple(p) for p in list_visitor(state, letters)]))
  79. aocp_partitions.add(p1)
  80. assert bl_partitions == aocp_partitions
  81. def compare_multiset_states(s1, s2):
  82. """compare for equality two instances of multiset partition states
  83. This is useful for comparing different versions of the algorithm
  84. to verify correctness."""
  85. # Comparison is physical, the only use of semantics is to ignore
  86. # trash off the top of the stack.
  87. f1, lpart1, pstack1 = s1
  88. f2, lpart2, pstack2 = s2
  89. if (lpart1 == lpart2) and (f1[0:lpart1+1] == f2[0:lpart2+1]):
  90. if pstack1[0:f1[lpart1+1]] == pstack2[0:f2[lpart2+1]]:
  91. return True
  92. return False
  93. def test_multiset_partitions_taocp():
  94. """Compares the output of multiset_partitions_taocp with a baseline
  95. (set partition based) implementation."""
  96. # Test cases should not be too large, since the baseline
  97. # implementation is fairly slow.
  98. multiplicities = [2,2]
  99. compare_multiset_w_baseline(multiplicities)
  100. multiplicities = [4,3,1]
  101. compare_multiset_w_baseline(multiplicities)
  102. def test_multiset_partitions_versions():
  103. """Compares Knuth-based versions of multiset_partitions"""
  104. multiplicities = [5,2,2,1]
  105. m = MultisetPartitionTraverser()
  106. for s1, s2 in zip_longest(m.enum_all(multiplicities),
  107. multiset_partitions_taocp(multiplicities)):
  108. assert compare_multiset_states(s1, s2)
  109. def subrange_exercise(mult, lb, ub):
  110. """Compare filter-based and more optimized subrange implementations
  111. Helper for tests, called with both small and larger multisets.
  112. """
  113. m = MultisetPartitionTraverser()
  114. assert m.count_partitions(mult) == \
  115. m.count_partitions_slow(mult)
  116. # Note - multiple traversals from the same
  117. # MultisetPartitionTraverser object cannot execute at the same
  118. # time, hence make several instances here.
  119. ma = MultisetPartitionTraverser()
  120. mc = MultisetPartitionTraverser()
  121. md = MultisetPartitionTraverser()
  122. # Several paths to compute just the size two partitions
  123. a_it = ma.enum_range(mult, lb, ub)
  124. b_it = part_range_filter(multiset_partitions_taocp(mult), lb, ub)
  125. c_it = part_range_filter(mc.enum_small(mult, ub), lb, sum(mult))
  126. d_it = part_range_filter(md.enum_large(mult, lb), 0, ub)
  127. for sa, sb, sc, sd in zip_longest(a_it, b_it, c_it, d_it):
  128. assert compare_multiset_states(sa, sb)
  129. assert compare_multiset_states(sa, sc)
  130. assert compare_multiset_states(sa, sd)
  131. def test_subrange():
  132. # Quick, but doesn't hit some of the corner cases
  133. mult = [4,4,2,1] # mississippi
  134. lb = 1
  135. ub = 2
  136. subrange_exercise(mult, lb, ub)
  137. def test_subrange_large():
  138. # takes a second or so, depending on cpu, Python version, etc.
  139. mult = [6,3,2,1]
  140. lb = 4
  141. ub = 7
  142. subrange_exercise(mult, lb, ub)