Debian Codegraph @

src/imageclasses/fun2method_imagetype_multi.py

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