comparison numerics/interpolation.py @ 10:7517682843cb

CLI
author Jeff Hammel <k0scist@gmail.com>
date Thu, 04 Sep 2014 21:01:36 -0700
parents 097296d6132e
children 285a886255e4
comparison
equal deleted inserted replaced
9:6906e5fc6dfd 10:7517682843cb
3 3
4 """ 4 """
5 interpolation 5 interpolation
6 """ 6 """
7 7
8 __all__ = ['neighbors', 'linear_interpolation'] 8 __all__ = ['neighbors', 'linear_interpolation', 'InterpolateParser']
9 9
10 def neighbors(start, finish): 10 def neighbors(start, finish):
11 """ 11 """
12 returns the neighbors in finish from start 12 returns the neighbors in finish from start
13 assumes both are sorted 13 assumes both are sorted
63 # linearly interpolate 63 # linearly interpolate
64 ratio = (points[index] - data[left][0])/float(data[right][0] - data[left][0]) 64 ratio = (points[index] - data[left][0])/float(data[right][0] - data[left][0])
65 retval.append(ratio*data[right][1] + (1.-ratio)*data[left][1]) 65 retval.append(ratio*data[right][1] + (1.-ratio)*data[left][1])
66 return retval 66 return retval
67 67
68 class InterpolateParser(argparse.ArgumentParser):
69 """CLI option parser"""
68 70
71 def __init__(self, **kwargs):
72 kwargs.setdefault('description', __doc__)
73 argparse.ArgumentParser.__init__(self, **kwargs)
74 self.add_argument('input', nargs='?',
75 type=argparse.FileType('r'), default=sys.stdin,
76 help='input file, or read from stdin if ommitted')
77 self.add_argument('-o', '--output', dest='output',
78 type=argparse.FileType('w'), default=sys.stdout,
79 help="output file, or stdout if ommitted")
80 self.add_argument('--points', '--print-points', dest='print_points',
81 action='store_true', default=False,
82 help="print the points to interpolate to and exit")
83 self.options = None
84
85 def parse_args(self, *args, **kw):
86 options = argparse.ArgumentParser.parse_args(self, *args, **kw)
87 self.validate(options)
88 self.options = options
89 return options
90
91 def validate(self, options):
92 """validate options"""
93
94 def main(args=sys.argv[1:]):
95 """CLI"""
96
97 # parse command line options
98 parser = InterpolateParser()
99 options = parser.parse_args(args)
100
101 # read the CSV
102 reader = csv.reader(options.input)
103 data = [[float(col) for col in row] for row in reader]
104 ncols = set([len(row) for row in data])
105 assert len(ncols) == 1
106 ncols = ncols.pop()
107 assert ncols > 1
108
109 # get `x` values
110 data = sorted(data, key=lambda x: x[0])
111 x = [row[0] for row in data]
112 xmin = int(x[0]) + 1
113 xmax = int(x[-1])
114 points = range(xmin, xmax+1)
115 if options.print_points:
116 print ('\n'.join([str(point) for point in points]))
117 return
118
119 # make into x,y series
120 series = [[(row[0], row[col]) for row in data]
121 for col in range(1,ncols)]
122
123 # interpolate
124 interpolated = [linear_interpolation(s, points) for s in series]
125
126 # output interpolated data
127 writer = csv.writer(options.output)
128 for row in zip(points, *interpolated):
129 writer.writerow(row)
130
131 if __name__ == '__main__':
132 main()