Guest User

Untitled

a guest
Feb 13th, 2018
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.56 KB | None | 0 0
  1. from itertools import combinations
  2. from functools import reduce
  3. import numpy as np
  4.  
  5. def countlessND(data, factor):
  6. assert len(data.shape) == len(factor)
  7.  
  8. sections = []
  9.  
  10. mode_of = reduce(lambda x,y: x * y, factor)
  11. majority = int(math.ceil(float(mode_of) / 2))
  12.  
  13. data += 1 # offset from zero
  14.  
  15. # This loop splits the 2D array apart into four arrays that are
  16. # all the result of striding by 2 and offset by (0,0), (0,1), (1,0),
  17. # and (1,1) representing the A, B, C, and D positions from Figure 1.
  18. for offset in np.ndindex(factor):
  19. part = data[tuple(np.s_[o::f] for o, f in zip(offset, factor))]
  20. sections.append(part)
  21.  
  22. pick = lambda a,b: a * (a == b)
  23. lor = lambda x,y: x + (x == 0) * y # logical or
  24.  
  25. subproblems = [ {}, {} ]
  26. results2 = None
  27. for x,y in combinations(range(len(sections) - 1), 2):
  28. res = pick(sections[x], sections[y])
  29. subproblems[0][(x,y)] = res
  30. if results2 is not None:
  31. results2 = lor(results2, res)
  32. else:
  33. results2 = res
  34.  
  35. results = [ results2 ]
  36. for r in range(3, majority+1):
  37. r_results = None
  38. for combo in combinations(range(len(sections)), r):
  39. res = pick(subproblems[0][combo[:-1]], sections[combo[-1]])
  40.  
  41. if combo[-1] != len(sections) - 1:
  42. subproblems[1][combo] = res
  43.  
  44. if r_results is not None:
  45. r_results = lor(r_results, res)
  46. else:
  47. r_results = res
  48. results.append(r_results)
  49. subproblems[0] = subproblems[1]
  50. subproblems[1] = {}
  51.  
  52. results.reverse()
  53. final_result = lor(reduce(lor, results), sections[-1]) - 1
  54. data -= 1
  55. return final_result
Add Comment
Please, Sign In to add comment