29
|
1 #!/usr/bin/env python
|
|
2 # -*- coding: utf-8 -*-
|
|
3
|
|
4 """
|
|
5 smoothing
|
|
6 """
|
|
7
|
|
8 # imports
|
|
9 import argparse
|
|
10 import os
|
|
11 import subprocess
|
|
12 import sys
|
|
13
|
|
14 # module globals
|
|
15 __all__ = ['main', 'smooth', 'SmoothingParser']
|
|
16
|
|
17 def smooth(iterations, *values):
|
|
18 assert len(values) >= 2
|
|
19 while iterations > 0:
|
|
20 inner = [sum(i) for i in zip(values[1:], values[:-1])]
|
|
21 left = [inner[0]] + inner[:]
|
|
22 right = inner[:] + [inner[-1]]
|
|
23 values = [0.25*sum(i) for i in zip(left, right)]
|
|
24 iterations -= 1
|
|
25 return values
|
|
26
|
|
27 class SmoothingParser(argparse.ArgumentParser):
|
|
28 """`smooth` CLI option parser"""
|
|
29 def __init__(self, **kwargs):
|
|
30 kwargs.setdefault('description', __doc__)
|
|
31 argparse.ArgumentParser.__init__(self, **kwargs)
|
|
32 self.add_argument('input', nargs='?',
|
|
33 type=argparse.FileType('r'), default=sys.stdin,
|
|
34 help='input file, or read from stdin if ommitted')
|
|
35 self.add_argument('-o', '--output', dest='output',
|
|
36 type=argparse.FileType('a'), default=sys.stdout,
|
|
37 help="output file to write to, or stdout")
|
|
38 self.add_argument('-n', '--iterations', dest='iterations',
|
|
39 type=int, default=1,
|
|
40 help="number of iterations to apply [DEFAULT: %(default)s]")
|
|
41 self.options = None
|
|
42
|
|
43 def parse_args(self, *args, **kw):
|
|
44 options = argparse.ArgumentParser.parse_args(self, *args, **kw)
|
|
45 self.validate(options)
|
|
46 self.options = options
|
|
47 return options
|
|
48
|
|
49 def validate(self, options):
|
|
50 """validate options"""
|
|
51
|
|
52 def main(args=sys.argv[1:]):
|
|
53 """CLI"""
|
|
54
|
|
55 # parse command line options
|
|
56 parser = SmoothingParser()
|
|
57 options = parser.parse_args(args)
|
|
58
|
|
59 # read data
|
|
60 data = options.input.read().strip().split()
|
|
61 data = [float(i) for i in data]
|
|
62
|
|
63 smoothed = smooth(options.iterations, *data)
|
|
64
|
|
65 # write data
|
|
66 options.output.write('\n'.join([str(i) for i in smoothed]))
|
|
67
|
|
68 if __name__ == '__main__':
|
|
69 main()
|
|
70
|