Introduction
This tutorial and its program shows the usage of input and output files and command line parameters. With the use of input files its no longer necessary to recompile the whole program when you want to change a parameter and its no longer necessary to write a huge number of parameters on the command line.
With a carefully designed order of parsing the command line options and reading the input file, it is even possible that the parameters on the command line overwrite the parameters in the input file.
The input file has a C-like syntax. You can derive the structure from the following example:
string title "testing blending maps"
string author "Philipp Frauenfelder, 2001"
int level 1
int polynomial 15
string uex "(x*(1-x-y)*(x-1-y))"
string fex "(-4 + 4*x + x*(1 - x - y)*(-1 + x - y))"
array string bcform {
1 "(0)"
2 "(1)"
}
array int bctype {
1 1
2 2
}
string meshouteps "blendmesh.eps"
string meshoutdx "blendmesh.dx"
string dataoutnumeric "blendnumeric.data"
string parameterout "blendoutput2.concepts"
double a 1.0
bool subdivide false
The results from the program are stored in a similar structure. At the end of a program, it is possible to write the input and output data into one file. The output file has the same syntax and structure as the input file and can therefore be used as an input file to reproduce the results at a later time. See the results section for an example.
Commented Program
First we have to import certain modules from the libconceptspy
package and other required python modules.
1from libconceptspy
import concepts
All code in this example is in one large routine, the main program.
Some default values for the parameters used. l
and p
are just two variables. If debug
is set to true, more information is printed to screen.
First, set up the input parameter class: some parameters are set up with a default value.
17 inputParameters = inp.inputParameters()
18 inputParameters.addInt(
'level',l)
19 inputParameters.addInt(
'polynomial',p)
20 inputParameters.addBool(
'debug',debug)
21 inputParameters.addString(
'parameterout',
"inputoutput.out")
The variable outputParameter is for easier access to the output area. There, the results of the computations can be stored and eventually written to disk if necessary.
Prepare an array for values computed later. This array is then added to table
which is able to nicely format the content of the different arrays (e.g. for later processing with Gnuplot).
27 outputParameters.addArrayDouble(
"error")
29 table.addMap(concepts.ResultsTable.DOUBLE,
"error", outputParameters)
Command Line Parsing
Here, we start with the command line parsing.
parser = argparse.ArgumentParser()
parser.add_argument('-l',help='LEVEL: level of refinement',required=False, type = int)
parser.add_argument('-p',help='DEGREE: polynomial degree', required=False, type = int)
parser.add_argument('-f',help='FILE: name of the input file',required=False, type = str)
parser.add_argument('-d',action = "store_true",help='-d: print the matrices',required=False)
args = parser.parse_args()
Enter -h
as command line argument for more information. The parameters are processed in the order they appear in the command line. When first specifying an input file with -f
, the values in the file can be overridden with additional command line arguments after -f
.
36 inputParameters.addInt(
"level",args.l)
38 inputParameters.addInt(
"polynomial",args.p)
43 inputParameters.addBool(
'debug',
True)
If there is an error reading the input file, then an exception error message is returned.
46 print(
"Input file not found.Cannot open input file.")
Print the parameters to show the user what is going on.
50 print(
'['+argv[0]+
']')
53 print(
' input file = %s\n%s'%(inputfile,inputParameters))
Next, the parameters from the command line or the input file are stored in the respective variables. This is only used for abbrevation.
57 l = inputParameters.getInt(
'level')
58 p = inputParameters.getInt(
'polynomial')
Computations
Here are some dummy computations to fill the output area with content.
62 outputParameters.addInt(
"nelm", 10)
64 outputParameters.addArrayDouble(
"error",i,1.0/(1<<i))
Output
Finally, the input and output data are written to disk with some more information about the user and the system in the header of the file.
70 print 'Writing gathered data to disk: ',inputParameters.getString(
"parameterout")
72 filename = inputParameters.getString(
"parameterout")
73 ofile = open(filename,
'w')
74 ofile.write(
"/* program:\t %s \n * command:\t " % (argv[0]))
75 for i
in range(0,len(argv)):
76 ofile.write(argv[i]+
" ")
78 ofile.write(
"\n * inputfile:\t %s \n" % (inputfile))
This prints the table and its content to the screen and also stores it with high precision in a file suitable for later processing with Gnuplot.
84 gnu_file = open(
"inputoutput.gnuplot",
'w')
85 gnu_file.write(str(table))
Results
The output of the program called without parameters:
[inputoutput]
--
Parameters:
input file =
string author "(empty)"
string comment "(empty)"
string parameterout "inputoutput.out"
string title "(empty)"
int level 0
int polynomial 1
bool debug false
--
--
Writing gathered data to disk: inputoutput.out
ResultsTable(
error error
0 1
1 0.5
2 0.25
3 0.125
4 0.0625
5 0.03125
6 0.015625
7 0.0078125
8 0.00390625
9 0.00195312
)
The program creates the following output files:
inputoutput.out:
inputoutput.gnuplot:
# error error
0 1q
1 0.5
2 0.25
3 0.125
4 0.0625
5 0.03125
6 0.015625
7 0.0078125
8 0.00390625
9 0.00195312
Note the end
keyword at the end of the input part and right before the output part. When reading in this file as input file, the parsing stops right there, ie. the previous output data is not read in.
@section complete Complete Source Code
1from libconceptspy import concepts
2import sys
3import argparse
4
5def main(args,argv):
6 try:
7 l = 0
8 p = 1
9 debug = False
10
11
14 inputParameters = inp.inputParameters()
15 inputParameters.addInt('level',l)
16 inputParameters.addInt('polynomial',p)
17 inputParameters.addBool('debug',debug)
18 inputParameters.addString('parameterout',"inputoutput.out")
19
21 outputParameters = inp.outputParameters()
22 outputParameters.addArrayDouble("error")
24 table.addMap(concepts.ResultsTable.DOUBLE, "error", outputParameters)
25
26 inputfile = ''
27
28 if (len(argv)>1):
29 if args.l:
30 inputParameters.addInt("level",args.l)
31 if args.p:
32 inputParameters.addInt("polynomial",args.p)
33 if args.f:
34 inputfile = args.f
35 inp.parse(inputfile)
36 if args.d:
37 inputParameters.addBool('debug', True)
38 except RuntimeError:
39 print("Input file not found.Cannot open input file.")
40 else:
41
42 print('['+argv[0]+']')
43 print('--')
44 print('Parameters:')
45 print(' input file = %s\n%s'%(inputfile,inputParameters))
46 print('--')
47
48 l = inputParameters.getInt('level')
49 p = inputParameters.getInt('polynomial')
50
51
52 outputParameters.addInt("nelm", 10)
53 for i in range(10):
54 outputParameters.addArrayDouble("error",i,1.0/(1<<i))
55
56
57
58 print('--')
59 print 'Writing gathered data to disk: ',inputParameters.getString("parameterout")
60
61 filename = inputParameters.getString("parameterout")
62 ofile = open(filename,'w')
63 ofile.write("/* program:\t %s \n * command:\t " % (argv[0]))
64 for i in range(0,len(argv)):
65 ofile.write(argv[i]+ " ")
66
67 ofile.write("\n * inputfile:\t %s \n" % (inputfile))
68 ofile.write(" */ \n")
69 ofile.write(str(inp))
70 ofile.close()
71 print(table)
72 gnu_file = open("inputoutput.gnuplot",'w')
73 gnu_file.write(str(table))
74 gnu_file.close()
75
76if __name__ == "__main__":
77 parser = argparse.ArgumentParser()
78 parser.add_argument('-l',help='LEVEL: level of refinement',required=False, type = int)
79 parser.add_argument('-p',help='DEGREE: polynomial degree', required=False, type = int)
80 parser.add_argument('-f',help='FILE: name of the input file',required=False, type = str)
81 parser.add_argument('-d',action = "store_true",help='-d: print the matrices',required=False)
82 args = parser.parse_args()
83 main(args,sys.argv)