Last active
December 19, 2015 14:19
-
-
Save fnielsen/5968772 to your computer and use it in GitHub Desktop.
Demonstration program for Python docopt module. Here with fitting of a polynomial.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
""" | |
mydocopter. | |
Usage: mydocopter [options] <filename> | |
Options: | |
-v --verbose Log messages | |
-o OUTPUT --output=OUTPUT Output file | |
-a <a> Initial coefficient for second order term [default: 1.] | |
-b <b> Initial coefficient for first order term [default: 1.] | |
-c <c> Initial coefficient for constant term [default: 1.] | |
Example: | |
$ echo -e "1 4\\n2 5\\n6 8\\n3 3.2" > datafile.txt | |
$ ./mydocopter --verbose datafile.txt | |
0.315471154631 -1.51271481921 5.64476836068 | |
$ ./mydocopter -o p.txt datafile.txt | |
$ ipython --pylab --c="m=loadtxt('datafile.txt'); p=loadtxt('p.txt'); x=linspace(1,6); plot(m[:,0], m[:,1], 'o', x, p[0]*x**2+p[1]*x+p[2], '-'); raw_input()" | |
Description: | |
Fit a polynomial to data. The datafile should have x y values in each row | |
""" | |
import docopt, logging, scipy.optimize | |
args = docopt.docopt(__doc__, version=1.0) | |
if args['--verbose']: | |
logging.getLogger().setLevel(logging.INFO) | |
a, b, c = (float(args['-' + coef]) for coef in ['a', 'b', 'c']) | |
logging.info("Setting 'a' to %f" % a) | |
logging.info('Reading data from ' + args['<filename>']) | |
data = [ map(float, line.split()) for line in open(args['<filename>']).readlines()] | |
def cost_function((a, b, c), data): | |
return sum(map(lambda (x, y): (a*x**2 + b*x + c - y)**2, data)) | |
parameters = scipy.optimize.fmin(cost_function, [a, b, c], | |
args=(data,), disp=False) | |
if args['--output'] is None: | |
print(" ".join(map(str, parameters))) | |
else: | |
with open(args['--output'], 'w') as f: | |
f.write(" ".join(map(str, parameters))) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment