11import numpy
22
3- try :
4- from ConfigParser import ConfigParser
5- except :
6- from configparser import ConfigParser
3+ from configparser import ConfigParser
74from collections import defaultdict
5+ from io import StringIO
86
97try :
108 import f90nml
1412
1513from amuse .units .quantities import new_quantity , to_quantity , is_quantity
1614
17- # CodeWithNamelistParameters
15+ # parameters can be supplied as:
1816#
19- # namelist_parameters =(
17+ # parameters =(
2018# dict(name="name", group_name="name", short="codename", dtype="int32", default=64, description="description", ptype="nml" [, set_name="name"]), ...
2119# )
2220
21+ dtype_str = { str : "str" ,
22+ bool : "bool" ,
23+ int : "int32" ,
24+ float : "float64" ,
25+ }
26+
27+ def parameter_list_py_code (parameters , label = "parameters" ):
28+ header = """from omuse.units import units
29+
30+ {label} = (
31+
32+ """ .format (label = label )
33+
34+ template = ' dict(name={name}, group_name={group}, short={short}, dtype={dtype}, default={default}, description={description}, ptype={ptype}),\n '
35+
36+ footer = """)
37+ """
38+
39+ by_group = defaultdict (dict )
40+ for key in parameters :
41+ short ,group = key
42+ by_group [group ][short ]= parameters [key ]
43+
44+ body = []
45+ for group in by_group :
46+ _body = ""
47+ for short in by_group [group ]:
48+ _body += template .format (name = by_group [group ][short ]["name" ].__repr__ (),
49+ group = by_group [group ][short ]["group_name" ].__repr__ (),
50+ short = by_group [group ][short ]["short" ].__repr__ (),
51+ dtype = by_group [group ][short ]["dtype" ].__repr__ (),
52+ default = by_group [group ][short ]["default" ].__repr__ (),
53+ description = by_group [group ][short ]["description" ].__repr__ (),
54+ ptype = by_group [group ][short ]["ptype" ].__repr__ (),)
55+
56+ body .append (_body )
57+ body = "#\n " .join (body )
58+
59+ return header + body + footer
60+
61+
2362class _CodeWithFileParameters (object ):
2463 _ptypes = None
25- def write_file (self , inputfile , ** kwargs ):
64+ def _write_file (self , inputfile , ** kwargs ):
2665 raise Exception ("not implemented" )
27- def read_file (self , inputfile , rawvals , ** kwargs ):
66+ def _read_file (self , inputfile , rawvals , ** kwargs ):
2867 raise Exception ("not implemented" )
2968
3069 def define_parameters (self , handler ):
@@ -65,14 +104,15 @@ def read_parameters(self, inputfile, add_missing_parameters=False):
65104 if key in self ._parameters :
66105 group_name = self ._parameters [key ]["group_name" ]
67106 name = self ._parameters [key ]["name" ]
107+ dtype = self ._parameters [key ]["dtype" ]
68108 val = self .interpret_value ( rawval , dtype = dtype )
69109 if is_quantity (self ._parameters [key ]["default" ]):
70- self ._parameters [key ]["value" ]= new_quantity (val , to_quantity (self ._namelist_parameters [key ]["default" ]).unit )
110+ self ._parameters [key ]["value" ]= new_quantity (val , to_quantity (self ._parameters [key ]["default" ]).unit )
71111 else :
72112 self ._parameters [key ]["value" ]= val
73113 else :
74114 if not add_missing_parameters :
75- print ("'{0}' of group '{1}' not in the namelist_parameters " .format (* key ))
115+ print ("'{0}' of group '{1}' not in the parameters list " .format (* key ))
76116 else :
77117 value = rawval
78118 description = comments .get (key , "unknown parameter read from {0}" .format (inputfile ))
@@ -84,7 +124,7 @@ def read_parameters(self, inputfile, add_missing_parameters=False):
84124 value = value ,
85125 short = key [0 ],
86126 ptype = self ._ptypes [0 ],
87- dtype = str ( type (value )) ,
127+ dtype = dtype_str [ type (value )] ,
88128 description = description
89129 )
90130
@@ -105,8 +145,8 @@ def write_parameters(self, outputfile, **options):
105145
106146 rawvals [key ]= self .output_format_value (value )
107147
108- self .write_file (outputfile , rawvals , ** options )
109-
148+ self ._write_file (outputfile , rawvals , ** options )
149+
110150class CodeWithNamelistParameters (_CodeWithFileParameters ):
111151 """
112152 Mix-in class to 1) namelist file support to code interfaces and 2) automatically generate
@@ -136,7 +176,7 @@ def _read_file(self, inputfile):
136176
137177 return rawvals , dict ()
138178
139- def write_file (self , outputfile , rawvals , do_patch = False , nml_file = None ):
179+ def _write_file (self , outputfile , rawvals , do_patch = False , nml_file = None ):
140180 patch = defaultdict ( dict )
141181
142182 for key ,rawval in rawvals .items ():
@@ -176,18 +216,44 @@ def __init__(self, _parameters=dict(), prefix="ini_"):
176216 self ._prefix = prefix
177217 self ._file = None
178218
179- def read_file (self , inputfile ):
219+ def _read_file (self , inputfile ):
220+ f = open (inputfile ,"r" )
221+ values = StringIO ()
222+ comments = StringIO ()
223+ for line in f .readlines ():
224+ if "=" in line :
225+ key , val = line .split ("=" , 1 )
226+ if "#" in val :
227+ val ,comment = val .split ("#" ,1 )
228+ comments .write ("=" .join ([key ,comment ])+ "\n " )
229+ values .write ("=" .join ([key ,val ])+ "\n " )
230+ else :
231+ values .write (line + "\n " )
232+ comments .write (line + "\n " )
233+
234+ values .seek (0 )
235+ comments .seek (0 )
236+
237+ rawvals = self .parse_fp (values )
238+ comments = self .parse_fp (comments )
239+
240+ return rawvals , comments
241+
242+
243+ def parse_fp (self , fp ):
180244 parser = ConfigParser ()
181245 parser .optionxform = self ._optionxform
182- parser .read (inputfile )
246+ parser .readfp (fp )
247+
248+ rawvals = dict ()
183249 for section in parser .sections ():
184250 group = section
185251 for option in parser .options (section ):
186252 key = (option ,group )
187253
188254 rawvals [key ]= parser .get (group , option )
189255
190- return rawvals , dict ()
256+ return rawvals
191257
192258 def _convert (self , value , dtype ):
193259 if dtype is "bool" :
@@ -204,12 +270,13 @@ def interpret_value(self,value, dtype=None):
204270 return [self ._convert (x , dtype ) for x in value .split ("," )]
205271 return self ._convert (value , dtype )
206272
207- def write_file (self , outputfile , rawvals ):
273+ def _write_file (self , outputfile , rawvals ):
208274 parser = ConfigParser ()
209275 parser .optionxform = self ._optionxform
210276
211277 for key , rawval in rawvals .items ():
212278 section = key [1 ]
279+ short = key [0 ]
213280
214281 if not parser .has_section (section ):
215282 parser .add_section (section )
@@ -229,4 +296,9 @@ def output_format_value(self,value):
229296 else :
230297 return value
231298
299+ def write_inifile_parameters (self , outputfile ):
300+ return self .write_parameters (outputfile )
301+
302+ def read_inifile_parameters (self , inputfile , add_missing_parameters = False ):
303+ return self .read_parameters (inputfile ,add_missing_parameters )
232304
0 commit comments