Debian Codegraph @

src/imageclasses/fun2method_imagetype.py

raw symbols SCIP
1 # first 20161111 by [email protected]
2
3 def fun2method(inputfile, outputfile_basename, json_path):
4 """converts MIALib C function declarations into JIPLib C++ methods (outputfile_basename.cc file) and C++ method declarations (outputfile_basename.h file). Currently only convert desctuctive functions, i.e., ERROR_TYPE functions, with IMAGE * as first argument (IMAGE ** not yet taken into account).
5
6 :param inputfile: string for input file containing extern declarations
7 :param outputfile_basename: string for output file basename (i.e. without extension)
8 :returns: True on success, False otherwise
9 :rtype:
10
11 """
12
13 import re
14 import json
15 import sys
16 import os
17 #json_path = sys.argv[3] # or adjust based on your arg parsing
18 with open(json_path, 'r') as f:
19 old2newDic = json.load(f)
20
21 #old2newDic = json.load(open("old2NewNames.json"))
22
23 ifp=open(inputfile, 'r')
24
25 f = open(outputfile_basename+'.cc', 'w')
26 fh = open(outputfile_basename+'.h', 'w')
27
28
29 lines=ifp.readlines()
30
31 for line in lines:
32 print(line)
33
34 name=re.match(r'extern IMAGE \*(.*)\((.*)\);',line)
35 args=re.split(',', name.group(2))
36 re.sub('\**', '', re.sub('.* ', '', args[0]))
37
38 arglist = []
39
40 for i in args:
41 atype=re.match(' *(.* \**)', i).group(1)
42 aname=re.sub('\**', '', re.sub('.* ', '', i))
43 arglist.append([atype, aname])
44
45
46 a= { "name" : name.group(1),
47 "arguments" : arglist }
48
49 print(a)
50
51 imDeclare=[]
52 imRasterArray=[]
53
54 GTDeclare=[]
55 GTVars=[]
56
57 GDTypes = ['GDT_Byte', 'GDT_Int16', 'GDT_UInt16', 'GDT_Int32', 'GDT_UInt32', 'GDT_Float32', 'GDT_Float64']
58 MIATypes = ['uc_', 's_', 'us_', 'i32_', 'u32_', 'f_', 'd_']
59 CTypes = ['unsigned char', 'short int', 'unsigned short int', 'int', 'unsigned int', 'float', 'double']
60
61 methodDeclaration='std::shared_ptr<Jim> Jim::'+old2newDic.get(a.get("name"))+'('
62 print(methodDeclaration)
63
64 cSeparator=', '
65 separator = '' # default value in case there are no arguments besides the input image
66
67 if a.get("arguments")[0][0] != 'IMAGE *':
68 print('WARNING: ',line,' does not have IMAGE * as first argument')
69 continue
70 else:
71 imDeclare.append(a.get("arguments")[0][0]+' '+a.get("arguments")[0][1]+'=this->getMIA(iband);')
72 cCall=a.get("arguments")[0][1]
73
74 imCount=1
75 for idx, arg in enumerate(a.get("arguments")[1:len(a.get("arguments"))]):
76 print(methodDeclaration)
77 print(idx)
78 print(idx)
79 print(separator)
80 print(arg)
81 print(arg[0])
82
83 if (arg[0]=='IMAGE *'):
84 methodDeclaration+=separator+'Jim& imRaster_'+arg[1]
85 imRasterArray.append('imRaster_'+arg[1])
86 imDeclare.append(arg[0]+' '+arg[1]+'=imRaster_'+arg[1]+'.getMIA(iband);')
87 elif (arg[0]=='G_TYPE '): # G_TYPE as double in python
88 GTDeclare.append(arg[0]+' '+arg[1]+';')
89 GTVars.append(arg[1])
90 methodDeclaration+=separator+'double '+'d_'+arg[1]
91 else:
92 methodDeclaration+=separator+arg[0]+' '+arg[1]
93
94 cCall+=cSeparator+arg[1]
95 separator=', '
96
97 fh.write(re.sub(r'Jim::','',methodDeclaration+separator+'int iband=0);\n'))
98
99 methodDeclaration+=separator+'int iband)'
100
101 f.write(methodDeclaration+'{')
102 f.write('\n\ttry{')
103 f.write('\n\t\tif(nrOfBand()<=iband){')
104 f.write('\n\t\t\tstd::string errorString=\"Error: band number exceeds number of bands in input image\";')
105 f.write('\n\t\t\tthrow(errorString);')
106 f.write('\n\t\t}')
107 for i in imRasterArray:
108 f.write('\n\t\tif('+i+'.nrOfBand()<=iband){')
109 f.write('\n\t\t\tstd::string errorString=\"Error: band number exceeds number of bands in input image\";')
110 f.write('\n\t\t\tthrow(errorString);')
111 f.write('\n\t\t}')
112 #f.write('\n\t\t'+a.get("arguments")[0][0]+' '+a.get("arguments")[0][1]+' = 0;') # assigned later depending on destructive or not
113 f.write('\n\t\t'+'IMAGE * imout = 0;')
114 llen=len(imDeclare)
115 for i in range(0,llen):
116 f.write('\n\t\t'+imDeclare[i])
117 for i in GTDeclare:
118 f.write('\n\t\t'+i)
119
120 if len(GTDeclare)>0:
121 f.write('\n\t\tswitch(getDataType()){')
122 for idx, GDType in enumerate(GDTypes):
123 f.write('\n\t\tcase('+GDType+'):')
124 for var_idx, GTVar in enumerate(GTVars):
125 f.write('\n\t\t\t'+GTVar+'.'+MIATypes[idx]+'val=static_cast<'+CTypes[idx]+'>(d_'+GTVars[var_idx]+');')
126 if (GDType=='GDT_Byte'):
127 f.write('\n\t\t\t'+GTVar+'.'+'generic_'+'val=static_cast<'+CTypes[idx]+'>(d_'+GTVars[var_idx]+');')
128 f.write('\n\t\t\tbreak;')
129 f.write('''
130 \t\tdefault:
131 \t\t\tstd::string errorString="Error: data type not supported";
132 \t\t\tthrow(errorString);
133 \t\t\tbreak;
134 \t\t}''')
135
136
137 f.write('\n\t\timout =::'+a.get("name")+'('+cCall+');')
138
139 f.write('\n\t\t\tthis->setMIA(iband);')
140 for i in imRasterArray:
141 f.write('\n\t\t\t\tif(this!=&'+i+')')
142 f.write('\n\t\t\t\t\t'+i+'.setMIA(iband);')
143
144 f.write('\n\t\t\tif (imout){')
145 f.write('\n\t\t\t\tstd::shared_ptr<Jim> imgWriter=std::make_shared<Jim>(imout);')
146 f.write('\n\t\t\t\timgWriter->copyGeoTransform(*this);')
147 f.write('\n\t\t\t\timgWriter->setProjection(getProjectionRef());')
148 f.write('\n\t\t\t\treturn(imgWriter);')
149 f.write('\n\t\t\t}')
150
151
152 f.write('\n\t\t\telse{')
153 f.write('\n\t\t\t\tstd::string errorString="Error: '+a.get("name")+'() function in MIA failed, returning NULL pointer";')
154 f.write('\n\t\t\t\tthrow(errorString);')
155 f.write('\n\t\t\t}')
156
157 f.write('\n\t\t}')
158
159
160 f.write('''
161 catch(std::string errorString){
162 \tstd::cerr << errorString << std::endl;
163 throw;
164 }
165 catch(...){
166 throw;
167 }
168 }\n''')
169
170 ifp.close()
171
172 f.close()
173 fh.close()
174
175 return(True)
176
177
178
179 ####################################################################
180
181 import sys, getopt
182
183 def main(argv):
184 inputfile="miallib_imagetype"
185 outputfile="fun2method_imagetype"
186 json_path = "old2NewNames.json"
187 try:
188 opts, args = getopt.getopt(argv,"hi:o:j:",["ifile=","ofile=", "json="])
189 except getopt.GetoptError:
190 print('fun2method.py -i <inputfile> -o <outputfilebasename> -j <json_path>')
191 sys.exit(2)
192 for opt, arg in opts:
193 if opt == '-h':
194 print('fun2method.py -i <inputfile> -o <outputfilebasename> -j <json_path>')
195 sys.exit()
196 elif opt in ("-i", "--ifile"):
197 inputfile = arg
198 elif opt in ("-o", "--ofile"):
199 outputfile = arg
200 elif opt in ("-j", "--json"):
201 json_path = arg
202 print('Input file is "', inputfile)
203 print('Output file is "', outputfile)
204 print('JSON file is "', json_path)
205
206 fun2method(inputfile, outputfile, json_path)
207
208 if __name__ == "__main__":
209 main(sys.argv[1:])
210
211
212 # cat /usr/local/include/miallib/miallib_*.h | grep '^extern IMAGE \*[^\*]' > miallib_image_type
213 # python fun2method_imagetype.py -i miallib_image_type -o fun2method_imagetype
214 # to automatically insert content of fun2method in jim.h within placeholder //start insert from fun2method -> //end insert from fun2method
215 # sed -i -ne '/\/\/start insert from fun2method_imagetype/ {p; r fun2method_imagetype.h' -e ':a; n; /\/\/end insert from fun2method_imagetype/ {p; b}; ba}; p' jim.h