Advertisement
Guest User

Untitled

a guest
Oct 5th, 2015
186
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.25 KB | None | 0 0
  1. class AdaptiveArithmeticCoder:
  2. FREQ_INIT = 1
  3. def __init__(self, character_space):
  4. self.character_space = character_space
  5. self.count = len(character_space)
  6. self.freqs = [ AdaptiveArithmeticCoder.FREQ_INIT ] * self.count
  7. self.intervals = [ None ] * self.count
  8. self.update_intervals((0, 1))
  9.  
  10. def update_intervals(self, interval):
  11. a, b = interval
  12. last = a
  13. for i in range(len(self.freqs)):
  14. probability = self.freqs[i] / self.count * (b - a)
  15. self.intervals[i] = (last, last + probability)
  16. last = last + probability
  17.  
  18. def encode(self, c):
  19. """Receives a character to encode. Updates the adaptive model."""
  20. index = self.character_space.index(c)
  21. self.freqs[index] += 1
  22. self.count += 1
  23. self.update_intervals(self.intervals[index])
  24.  
  25. def current_interval(self):
  26. """Returns the current encoded file."""
  27. a = self.intervals[0][0]
  28. b = self.intervals[-1][1]
  29. return a, b
  30.  
  31. def current(self):
  32. """Returns the current encoded file."""
  33. a, b = self.current_interval()
  34. return (a + b) / 2
  35.  
  36. def current_binary(self):
  37. """Returns the current encoded file."""
  38. out_s = ""
  39. out = 0
  40. n = -1
  41. a, b = self.current_interval()
  42. while not a < out < b:
  43. if out + 2 ** n > b:
  44. out_s += "0"
  45. else:
  46. out += 2 ** n
  47. out_s += "1"
  48.  
  49. n -= 1
  50.  
  51. return out_s
  52.  
  53.  
  54. if __name__ == '__main__':
  55. import fileinput
  56. import argparse
  57. import os
  58.  
  59. parser = argparse.ArgumentParser(description='Dynamically encodes a string received through standard input.')
  60. parser.add_argument('-interval', action="store_true", help='Print the floating interval rather than the binary coding.')
  61. parser.add_argument('-character_space', type=str, required=True, help='All possible characters in the input. e.g. "ABCD".')
  62.  
  63. args = parser.parse_args(Adaptive(args.character_space)
  64. for line in os.sys.stdin:
  65. line = line.rstrip('\n')
  66. for c in line:
  67. coder.encode(c)
  68.  
  69. if (args.interval):
  70. print(coder.current_interval())
  71. else:
  72. print(coder.current_binary())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement