PHYEX 0.9.5
PHYsique EXternalisée
Loading...
Searching...
No Matches
pybinding.py
Go to the documentation of this file.
1#!/usr/bin/env python3
2
3"""
4This script contains a uniq function that reads a FORTRAN file and tries
5to create a new FORTRAN SUBROUTINE that can be used to access the
6original routine from python through the ctypesForFortran utility.
7
8This function is designed to work with PHYEX codes by recognizing
9the name of certain structures. In addition, it performs special
10processing for ini_phyex (adding a file name for the namelist and
11flushing the listing file).
12"""
13
14import argparse
15import os
16import re
17from pyfortool import PYFT
18from pyfortool.util import n2name
19
20class PybindingError(Exception):
21 """
22 Exceptions for pybinding
23 """
24
25def pybinding(fortran_in, scope, fortran_out, python_out, libso,
26 tpfileIsNam=False, Findexing=False):
27 """
28 :param fortran_in: FORTRAN input file
29 :param scope: scope to deal with
30 :param fortran_out: FORTRAN output file
31 :param python_out: python output file
32 :param libso: path to the shared lib (relative to the python_out file)
33 or list of possible paths
34 :param tpfileIsNam: True if tpfile is a namelist
35 :param Findexing: True to keep the same index order as in the FORTRAN subroutine
36 """
37
38 if isinstance(libso, str):
39 libso = [libso]
40
41 def findcomponents(bound):
42 """
43 :param bound: a string representing an array bound
44 :returns: a list of components
45 If bound is '5+(X+3)', result is ['5', 'X', '3']
46 """
47 if bound is None:
48 return []
49 elemlist = bound
50 for op in ('+', '-', '*', '/', '(', ')'):
51 elemlist = elemlist.replace(op, ' ')
52 return elemlist.split(' ')
53
54 #From the original subroutine, two FORTRAN subroutines will be created:
55 # - the main one which receives the dummy arguments from python
56 # transforms them and call the original subroutine
57 # - an helper subroutine to help dealing with kinds and some
58 # dimensions (read in module)
59 #A python code to call the main FORTRAN subroutine is also created.
60
61 #Open input FORTRAN file and get the right scope
62 pftin = PYFT(fortran_in)
63 scopeNode = pftin.getScopeNode(scope, excludeContains=True)
64 kind, name = scope.split('/')[-1].split(':')
65 name = name.upper()
66 kind = {'sub': 'SUBROUTINE',
67 'func': 'FUNCTION'}[kind]
68
69 #Loop on all the dummy arguments and prepare their use
70 argList1 = [] #argument list of the main public interface
71 argList2 = [] #argument list of the existing FORTRAN routine
72 moduleList = [] #declarative module to add to the main subroutine
73 moduleListHelper = [] #declarative module to add to the helper subroutine
74 declList = [] #variable declaration list (dummy var and local var)
75 copyList = [] #Instructions to copy public var to local var
76 # to be used to call the original subroutine
77 extra = [] #additional variables to read in module
78 copyBackList = [] #Instructions to copy local var to public var
79 # after the call to the original subroutine
80 flush = [] #list of unit to flush
81 docstringIN = ["Input arguments:"]
82 docstringOUT = ["Output arguments:"]
83 for N in scopeNode.findall('.//{*}dummy-arg-LT/{*}arg-N/{*}N'):
84 var = scopeNode.varList.findVar(n2name(N), exactScope=True)
85 if var is None:
86 raise PybindingError(n2name(N) + ' seems to be undeclared')
87 vartype = var['t'].replace(' ', '').upper()
88 if vartype == 'TYPE(DIMPHYEX_T)':
89 moduleList.append('USE MODD_DIMPHYEX, ONLY: DIMPHYEX_t')
90 declList.append('TYPE(DIMPHYEX_t) :: D')
91 for v in ['NIT', 'NKT', 'NKL', 'NVEXT']:
92 declList.append('INTEGER, INTENT(IN) :: ' + v)
93 argList1.append((v, 'INTEGER', False, 'IN', None))
94 docstringIN.append(f" {v} (IN) to replace the FORTRAN D structure")
95 copyList.append('D%NIT=NIT')
96 copyList.append('D%NIB=1')
97 copyList.append('D%NIE=NIT')
98 copyList.append('D%NJT=1')
99 copyList.append('D%NJB=1')
100 copyList.append('D%NJE=1')
101 copyList.append('D%NIJT=NIT')
102 copyList.append('D%NIJB=1')
103 copyList.append('D%NIJE=NIT')
104 copyList.append('D%NKL=NKL')
105 copyList.append('D%NKT=NKT')
106 copyList.append('D%NKA=MERGE(1, NKT, NKL==1)')
107 copyList.append('D%NKU=MERGE(NKT, 1, NKL==1)')
108 copyList.append('D%NKB=D%NKA+NKL*NVEXT')
109 copyList.append('D%NKE=D%NKU-NKL*NVEXT')
110 copyList.append('D%NKTB=1+NVEXT')
111 copyList.append('D%NKTE=NKT-NVEXT')
112 copyList.append('D%NIBC=1')
113 copyList.append('D%NJBC=1')
114 copyList.append('D%NIEC=NIT')
115 copyList.append('D%NJEC=1')
116 argList2.append('D')
117 elif vartype == 'TYPE(PHYEX_AERO_T)':
118 moduleList.append('USE MODD_PHYEX_AERO, ONLY: PHYEX_AERO_t')
119 moduleList.append('USE MODD_MISC_OFFLINE, ONLY: MISC_OFFLINE_t')
120 declList.append('TYPE(PHYEX_AERO_t) :: PHYAERO')
121 declList.append('TYPE(MISC_OFFLINE_t), TARGET :: MISC')
122 copyList.append('PHYAERO%LSALT = MISC%LSALT')
123 copyList.append('PHYAERO%NMODE_SLT = MISC%NMODE_SLT')
124 copyList.append('PHYAERO%XINISIG_SLT => MISC%XINISIG_SLT')
125 copyList.append('PHYAERO%CRGUNITS = MISC%CRGUNITS')
126 copyList.append('PHYAERO%XINIRADIUS_SLT=> MISC%XINIRADIUS_SLT')
127 copyList.append('PHYAERO%XDENSITY_SALT = MISC%XDENSITY_SALT')
128 argList2.append('PHYAERO')
129 elif vartype in ['TYPE(NSV_T)',]:
130 moduleList.append('USE MODD_' + vartype[5:-3] + ', ONLY: T' + vartype[5:-3])
131 declList.append('INTEGER, INTENT(IN) :: NSV')
132 argList1.append(('NSV', 'INTEGER', False, 'IN', None))
133 docstringIN.append(" NSV (IN) to replace the FORTRAN TNSV structure")
134 copyList.append('TNSV%NSV=NSV')
135 argList2.append('T'+vartype[5:-3])
136 elif vartype in ['TYPE(CST_T)', 'TYPE(ELEC_PARAM_T)', 'TYPE(ELEC_DESCR_T)',
137 'TYPE(PARAM_LIMA_T)', 'TYPE(PARAM_LIMA_WARM_T)', 'TYPE(PARAM_LIMA_COLD_T)',
138 'TYPE(PARAM_LIMA_MIXED_T)']:
139 moduleList.append('USE MODD_' + vartype[5:-3] + ', ONLY: ' + vartype[5:-3])
140 argList2.append(vartype[5:-3])
141 elif vartype == 'TYPE(ICET_PARAM_T)':
142 moduleList.append('USE MODD_ICET_PARAM, ONLY: ICE_T_PARAMETERS')
143 argList2.append('ICE_T_PARAMETERS')
144 elif vartype in ['TYPE(NEB_T)', 'TYPE(RAIN_ICE_PARAM_T)', 'TYPE(PARAM_ICE_T)',
145 'TYPE(RAIN_ICE_DESCR_T)', 'TYPE(TURB_T)', 'TYPE(PARAM_MFSHALL_T)']:
146 moduleList.append('USE MODD_' + vartype[5:-3] + '_N, ONLY: ' + vartype[5:-3] + 'N')
147 argList2.append(vartype[5:-3] + 'N')
148 elif vartype == 'TYPE(CSTURB_T)':
149 moduleList.append('USE MODD_CTURB, ONLY: CSTURB')
150 argList2.append(vartype[5:-3])
151 elif vartype == 'TYPE(TBUDGETCONF_T)':
152 moduleList.append('USE MODD_BUDGET, ONLY: TBUCONF_ASSOCIATE, TBUCONF')
153 argList2.append('TBUCONF')
154 copyList.append('CALL TBUCONF_ASSOCIATE')
155 elif vartype == 'TYPE(TBUDGETDATA_PTR)':
156 moduleList.append('USE MODD_BUDGET, ONLY: NBUDGET_RH, TBUDGETDATA_PTR')
157 moduleList.append('USE MODE_BUDGET_OFFLINE, ONLY: TBUDGETDATA_OFFLINE')
158 declList.append('TYPE(TBUDGETDATA_PTR), DIMENSION(NBUDGET_RH) :: YLBUDGET')
159 declList.append('TYPE(TBUDGETDATA_OFFLINE), DIMENSION(NBUDGET_RH), TARGET :: YLOFFBUD')
160 declList.append('INTEGER :: JRR')
161 copyList.append('DO JRR=1, NBUDGET_RH\n YLBUDGET(JRR)%PTR => YLOFFBUD(JRR)\n YLBUDGET(JRR)%PTR%NBUDGET=JRR\nENDDO')
162 argList2.append('YLBUDGET')
163 elif vartype == 'TYPE(TFILEDATA)':
164 moduleList.append('USE MODD_IO, ONLY: TFILEDATA')
165 declList.append('TYPE(TFILEDATA) :: TPFILE')
166 declList.append('INTEGER, INTENT(IN) :: KUNIT')
167 argList1.append(('KUNIT', 'INTEGER', False, 'IN', None))
168 docstringIN.append(" KUNIT (IN) to replace the FORTRAN TFILEDATA structure")
169 copyList.append('TPFILE%NLU=KUNIT')
170 argList2.append('TPFILE')
171 if var['n'] == 'TPFILE' and name == "INI_PHYEX":
172 # Maximum length of the namelist file name
173 namfile_len = 512
174 declList.append(f'CHARACTER(LEN={namfile_len}) :: SLOCAL_NAMFILE')
175 declList.append('INTEGER :: ILOOPVAR_NAMFILE')
176 declList.append(f'CHARACTER, DIMENSION({namfile_len}), INTENT(IN) :: NAMFILE')
177 argList1.append(('NAMFILE', 'CHARACTER', False, 'IN', ((None, str(namfile_len)),)))
178 docstringIN.append(" NAMFILE (IN) to replace the FORTRAN TFILEDATA structure")
179 copyList.append(f'DO ILOOPVAR_NAMFILE=1, {namfile_len}\n' + \
180 ' SLOCAL_NAMFILE(ILOOPVAR_NAMFILE:ILOOPVAR_NAMFILE)=' + \
181 'NAMFILE(ILOOPVAR_NAMFILE)\n' + \
182 'ENDDO')
183 copyList.append('IF (KUNIT/=0) OPEN(KUNIT, FILE=SLOCAL_NAMFILE)')
184 elif vartype == 'TYPE(TLES_T)':
185 moduleList.append('USE MODD_LES, ONLY: TLES_t')
186 declList.append('TYPE(TLES_t) :: TLES')
187 copyList.append('TLES%LLES=.FALSE.')
188 copyList.append('TLES%LLES_CALL=.FALSE.')
189 argList2.append('TLES')
190 elif vartype == 'TYPE(PHYEX_T)':
191 pass
192 elif vartype.startswith('TYPE('):
193 raise NotImplementedError('Does not know how to deal with ' +
194 f'argument of type {vartype} ' +
195 f'in {fortran_in}')
196 elif var['n'] == 'KSPLITR':
197 moduleList.append('USE MODD_CLOUDPAR_n, ONLY: KSPLITR => NSPLITR')
198 argList2.append('KSPLITR')
199 elif vartype.startswith('CHARACTER(LEN=') and vartype[14:].split(')')[0] != '1':
200 charlen = int(vartype[14:].split(')')[0])
201 #We must use a one-character length arrays,
202 #we add a dimension to replace the string length
203 #This is the variable we will receive (given by ctypesforfortran)
204 replvar = var.copy()
205 replvar['as'] = [(None, str(charlen))] + var['as']
206 replvar['t'] = 'CHARACTER(KIND=C_CHAR)'
207 argList1.append((replvar['n'], replvar['t'],
208 replvar['opt'], replvar['i'].upper(), replvar['as']))
209 docstr = ', OPTIONAL' if replvar['opt'] else ''
210 docstr = f" {var['n']} ({var['i']}{docstr})"
211 if replvar['i'] in ('IN', 'INOUT'):
212 docstringIN.append(docstr)
213 if replvar['i'] in ('OUT', 'INOUT'):
214 docstringOUT.append(docstr)
215 declList.append(pftin.varSpec2stmt(replvar))
216 #But the original routine wants the same characters but with a multi-character string
217 #We create this local var, and pass it to the routine
218 localvar = var.copy()
219 localvar['n'] = 'SLOCAL_' + var['n']
220 localvar['i'] = None
221 localvar['arg'] = False
222 declList.append(pftin.varSpec2stmt(localvar))
223 argList2.append(localvar['n'])
224 #And we need to copy the received characters into the local var (IN and INOUT)
225 #and, after the call, the local var into the characters to return (OUT and INOUT)
226 if len(var['as']) == 0:
227 declList.append(f"INTEGER :: ILOOPVAR_{var['n']}")
228 arrayElem = '{name}(ILOOPVAR_{name})'.format(name=var['n'])
229 strElem = 'SLOCAL_{name}(ILOOPVAR_{name}:ILOOPVAR_{name})'.format(name=var['n'])
230 loopBegin = 'DO ILOOPVAR_{name}=1, {len}\n'.format(name=var['n'], len=str(charlen))
231 loopEnd = 'ENDDO'
232 else:
233 loopVars = [f"ILOOPVAR_{var['n']}_{i}" for i in range(len(var['as']) + 1)]
234 declList.append('INTEGER :: ' + ', '.join(loopVars))
235 loopBegin = ''
236 for d in range(len(var['as'])):
237 loopBegin += ("DO ILOOPVAR_{varname}_{i}=LBOUND(SLOCAL_{varname}, {i}), " + \
238 "UBOUND(SLOCAL_{varname}, {i})\n"
239 ).format(varname=var['n'], i=str(d + 1))
240 loopBegin += 'DO ILOOPVAR_{name}_0=1, {len}\n'.format(name=var['n'], len=str(charlen))
241 arrayElem = '{name}(ILOOPVAR_{name}_0, {loopv})'.format(
242 name=var['n'], loopv=', '.join(loopVars[1:]))
243 strElem = 'SLOCAL_{name}({loopv})(ILOOPVAR_{name}_0:ILOOPVAR_{name}_0)'.format(
244 name=var['n'], loopv=', '.join(loopVars[1:]))
245 loopEnd = 'ENDDO\n' * len(loopVars)
246 if replvar['i'] in ('IN', 'INOUT'):
247 copyList.append(loopBegin + f' {strElem}={arrayElem}\n' + loopEnd)
248 if replvar['i'] in ('OUT', 'INOUT'):
249 if replvar['opt']:
250 raise NotImplementedError('Optional character strings in OUT/INOUT')
251 copyBackList.append(loopBegin + f' {arrayElem}={strElem}\n' + loopEnd)
252 else:
253 if var['n'] == 'KLUOUT' and name == "INI_PHYEX":
254 flush.append('KLUOUT')
255 replvar = var.copy()
256 localvar = var.copy()
257 if vartype.startswith('LOGICAL'):
258 replvar['t'] = 'LOGICAL(KIND=C_BOOL)'
259 localvar['n'] = 'SLOCAL_' + var['n']
260 localvar['i'] = None
261 localvar['arg'] = False
262 localvar['opt'] = False
263 # The folowing copy is done even if the argument is a missing optional one
264 # It's not correct, but how can it be otherwise? Protecting the copy isn't
265 # enough, we'd also have to call the routine without the argument
266 copyList.append('SLOCAL_{varname}={varname}'.format(varname=var['n']))
267 argList1.append((replvar['n'], replvar['t'].replace(' ', '').upper(),
268 replvar['opt'], replvar['i'].upper(), replvar['as']))
269 docstr = ', OPTIONAL' if replvar['opt'] else ''
270 docstr = f" {var['n']} ({var['i']}{docstr})"
271 if replvar['i'] in ('IN', 'INOUT'):
272 docstringIN.append(docstr)
273 if replvar['i'] in ('OUT', 'INOUT'):
274 docstringOUT.append(docstr)
275 argList2.append(localvar['n'])
276 for d in replvar['as']: # The following code handles MERGE() in declaration
277 if 'NIT' in d[1] or 'NIJT' in d[1]:
278 d[1] = 'NIT'
279 elif 'NJT' in d[1]:
280 d[1] = '1'
281 elif 'NKT' in d[1]:
282 d[1] = 'NKT'
283 elif 'KSV' in d[1]:
284 d[1] = 'KSV'
285 elif 'NSV' in d[1]:
286 d[1] = 'NSV'
287 elif 'KGRADIENTSGOG' in d[1]:
288 d[1] = 'KGRADIENTSGOG'
289 elif 'KGRADIENTSLEO' in d[1]:
290 d[1] = 'KGRADIENTSLEO'
291 elif 'KSOA' in d[1]:
292 d[1] = 'KSOA'
293 declList.append(pftin.varSpec2stmt(replvar))
294 if vartype.startswith('LOGICAL'):
295 declList.append(pftin.varSpec2stmt(localvar))
296 if 'JPSVMAX' not in extra and \
297 'JPSVMAX' in [elem for d in var['as'] for di in d for elem in findcomponents(di)]:
298 extra.append('JPSVMAX')
299 moduleList.append('USE MODD_PARAMETERS, ONLY: JPSVMAX')
300 moduleListHelper.append('USE MODD_PARAMETERS, ONLY: JPSVMAX')
301 #if 'NSV' not in extra and \
302 # 'NSV' in [elem for d in var['as'] for di in d for elem in findcomponents(di)]:
303 # extra.append('NSV')
304 # moduleList.append('USE MODD_NSV, ONLY: NSV')
305 # moduleListHelper.append('USE MODD_NSV, ONLY: NSV')
306 for vv, mod in (('NSP', 'MODD_CH_AEROSOL'), ('NCARB', 'MODD_CH_AEROSOL'),
307 ('NSOA', 'MODD_CH_AEROSOL'), ('NTURB_S', 'MODD_TURB_n')):
308 if vv not in extra and \
309 vv in [elem for d in var['as'] for di in d for elem in findcomponents(di)]:
310 extra.append(vv)
311 moduleList.append(f'USE {mod}, ONLY: {vv}')
312 moduleListHelper.append(f'USE {mod}, ONLY: {vv}')
313
314 pftin.close()
315
316 #Write output FORTRAN file
317 exists = os.path.exists(fortran_out)
318 with open(fortran_out, 'a', encoding="utf-8") as f:
319 if exists:
320 f.write('\n')
321
322 #Main subroutine
323 argList1name = [v[0] for v in argList1]
324 f.write(('{kind} PY{name}({argList}) ' + \
325 'BIND(C, name="PY{name}")\n').format(kind=kind,
326 argList=', &\n '.join(argList1name),
327 name=name))
328 if scope.split('/')[0].split(':')[0] == 'module':
329 f.write(f"\nUSE {scope.split('/')[0].split(':')[1]}\n")
330 else:
331 f.write(f'\nUSE MODI_{name}\n')
332 f.write('\n'.join(moduleList) + '\n')
333 f.write('\nUSE, INTRINSIC :: ISO_C_BINDING, ONLY: C_CHAR, C_BOOL\n')
334 f.write('\nIMPLICIT NONE\n')
335 f.write('\n'.join(declList) + '\n')
336 f.write('\n'.join(copyList) + '\n')
337 f.write(f"CALL {name}(" + ', &\n '.join(argList2) + ")\n")
338 if len(copyBackList) > 0:
339 f.write('\n'.join(copyBackList) + '\n')
340 for unit in flush:
341 f.write(f"FLUSH({unit})\n")
342 f.write(f'END {kind} PY{name}')
343
344 #Helper subroutine
345 f.write('\n')
346 extraname = ['K_' + e for e in extra]
347 f.write(('{kind} HPY{name}({argList}) ' + \
348 'BIND(C, name="HPY{name}")\n').format(kind=kind,
349 argList=', &\n '.join(argList1name + extraname),
350 name=name))
351 f.write('\n'.join(moduleListHelper) + '\n')
352 f.write('\nUSE, INTRINSIC :: ISO_C_BINDING, ONLY: C_CHAR, C_BOOL\n')
353 f.write('INTEGER(KIND=4), INTENT(OUT) :: ' + (', &\n '.join(argList1name + extraname)) + '\n')
354 for varname, vartype, _, _, _ in argList1:
355 f.write(vartype + ' :: ' + 'K_' + varname + '\n')
356 for varname, vartype, _, _, _ in argList1:
357 if vartype.startswith('CHARACTER'):
358 f.write(f'{varname}=0\n')
359 else:
360 f.write('{varname}=KIND(K_{varname})\n'.format(varname=varname))
361 for varname in extra:
362 f.write(f'K_{varname}={varname}\n')
363 f.write(f'END {kind} HPY{name}')
364
365 #Write output pyton file
366 exists = os.path.exists(python_out)
367 with open(python_out, 'a', encoding="utf-8") as f:
368 if not exists:
369 f.write('#!/usr/bin/env python3\n')
370 f.write('import numpy\n')
371 f.write('import ctypesForFortran\n')
372 f.write('from ctypesForFortran import string2array, array2string\n')
373 f.write('import sys\n')
374 f.write('import os\n')
375 f.write('from functools import lru_cache\n')
376 f.write('\n')
377 f.write('IN = ctypesForFortran.IN\n')
378 f.write('OUT = ctypesForFortran.OUT\n')
379 f.write('INOUT = ctypesForFortran.INOUT\n')
380 f.write('MISSING = ctypesForFortran.MISSING\n')
381 f.write('MAO = ctypesForFortran.MANDATORY_AFTER_OPTIONAL\n')
382 f.write('\n')
383 f.write('ctypesFF = None\n')
384 # Shared lib paths are relative to the python module and resolved at
385 # runtime, so that the module can be moved together with the lib
386 f.write('_dirname = os.path.dirname(os.path.realpath(__file__))\n')
387 for libsoname in libso:
388 f.write(f'_libso = os.path.join(_dirname, {libsoname!r})\n')
389 f.write('if ctypesFF is None and os.path.exists(_libso):\n')
390 f.write(' ctypesFF, handle = ctypesForFortran.ctypesForFortranFactory(_libso)\n')
391 f.write('if ctypesFF is None:\n')
392 f.write(f' raise IOError("Shared lib is missing (tested path are: {", ".join(libso)}).")\n')
393 f.write('\n')
394 f.write('def close():\n')
395 f.write(' ctypesForFortran.dlclose(handle)\n')
396 f.write('\n@lru_cache\n')
397 f.write("@ctypesFF(prefix='', suffix='')\n")
398 f.write(f"def HPY{name}():\n")
399 f.write(f" return ([], [(numpy.int32, None, OUT)] * {len(argList1 + extra)}, None)\n")
400 f.write('\n')
401 # Character strings in OUT/INOUT are returned as 1-char arrays: they must be
402 # converted by the array2string decorator, which needs their position among
403 # the returned values
404 strOutPos = []
405 iout = 0
406 optOutBefore = False
407 for _, vartype, opt, intent, _ in argList1:
408 if intent in ('OUT', 'INOUT'):
409 if vartype.startswith('CHARACTER'):
410 if optOutBefore:
411 # position would depend on missingOUT
412 raise NotImplementedError('Character strings in OUT/INOUT after ' + \
413 'an optional OUT/INOUT argument')
414 strOutPos.append(iout)
415 if opt:
416 optOutBefore = True
417 iout += 1
418 if len(strOutPos) > 0:
419 f.write(f"@array2string({strOutPos})\n")
420 f.write("@ctypesFF(prefix='', suffix='', castInput=True, " + \
421 f"indexing='{'F' if Findexing else 'C'}')\n")
422 argList = []
423 missing = False
424 for varname, _, opt, intent, _ in argList1:
425 if intent in ('IN', 'INOUT'):
426 if opt is True:
427 argList.append(varname + '=MISSING')
428 missing = True
429 elif missing:
430 argList.append(varname + '=MAO')
431 else:
432 argList.append(varname)
433 outvar = [varname for (varname, _, _, intent, _) in argList1 if intent in ('OUT', 'INOUT')]
434 argList.append('missingOUT=None')
435 f.write(f"def PY{name}({', '.join(argList)}):\n")
436 f.write( ' """\n')
437 f.write( " Wrapping to provide a python binding using pybinding " + \
438 "from the PHYEX package.\n")
439 f.write(f" Original file is {fortran_in}\n\n")
440 f.write( " Special notes for OPTIONAL variables:\n")
441 f.write( " - To be absent on input, the variable must receive the MISSING\n")
442 f.write( " special value.\n")
443 f.write( " - For a variable with OUT intent, the variable name must be added in the\n")
444 f.write( " missingOUT list to not be returned by the python function.\n")
445 f.write( " - For a variable with INOUT intent, its presence or absence is\n")
446 f.write( " simultaneous at input and output\n\n")
447 f.write( " " + "\n ".join(docstringIN) + "\n")
448 f.write( " " + "\n ".join(docstringOUT) + "\n")
449 f.write( ' """\n')
450 f.write( " missingOUT = [] if missingOUT is None else missingOUT\n")
451 if len(argList1 + extra) == 1:
452 # With only one value, ctypesForFortran does not return a tuple
453 f.write(f" kinds = (HPY{name}(), )\n")
454 else:
455 f.write(f" kinds = HPY{name}()\n")
456 if len(extra) > 0:
457 f.write(f" {', '.join(['_' + e for e in extra])}, = kinds[{len(argList1)}:]\n")
458 inlist = []
459 alllist = []
460 for ivar, (varname, vartype, opt, intent, dim) in enumerate(argList1):
461 if vartype.startswith('INTEGER'):
462 npkind = {4: 'numpy.int32', 8: 'numpy.int64'}
463 elif vartype.startswith('REAL'):
464 npkind = {4: 'numpy.float32', 8: 'numpy.float64'}
465 elif vartype.startswith('LOGICAL(KIND=C_BOOL)'):
466 npkind = {1: 'bool'}
467 elif vartype.startswith('CHARACTER'):
468 npkind = {0: 'str'}
469 else:
470 raise NotImplementedError('Argument type not yet implemented: ' + vartype)
471 if intent in ('IN', 'INOUT'):
472 if vartype.startswith('CHARACTER'):
473 inlist.append(f'string2array({varname}, {dim[0][1]}), #{varname}')
474 else:
475 inlist.append(f'{varname}, #{varname}')
476 strdim = []
477 if not (dim is None or len(dim) == 0):
478 for d in dim:
479 if d[0] is not None:
480 raise NotImplementedError('Array with non-zero indexing not implemented')
481 strdimpart = d[1]
482 for elem in findcomponents(d[1]):
483 if elem in ('NIT', 'NIJT'):
484 strdimpart = re.sub(rf'\b{elem}\b', 'NIT', strdimpart)
485 elif elem == 'NJT':
486 strdimpart = re.sub(rf'\b{elem}\b', '1', strdimpart)
487 elif elem == 'NKT':
488 pass
489 elif elem in argList1name:
490 pass # This dimension is a dummy argument
491 elif elem in ('JPSVMAX', 'NSV', 'NSP', 'NCARB', 'NSOA', 'NTURB_S',
492 'KGRADIENTSLEO', 'KGRADIENTSGOG', 'KSOA'):
493 strdimpart = re.sub(rf'\b{elem}\b', f'_{elem}', strdimpart)
494 else:
495 try:
496 int(elem)
497 except ValueError as verr:
498 raise NotImplementedError(f'Dimension not implemeneted ({elem}) ' + \
499 f'for variable {varname}') from verr
500 strdim.append(strdimpart)
501 if len(strdim) == 0:
502 strdim = 'None'
503 else:
504 if Findexing:
505 strdim = '(' + ', '.join(strdim) + ',)'
506 else:
507 if vartype.startswith('CHARACTER'):
508 strdim = '(' + ', '.join(['1'] + strdim[1:][::-1] + [strdim[0]]) + ',)'
509 else:
510 strdim = '(' + ', '.join(strdim[::-1]) + ',)'
511 kind = repr(npkind).replace("'", "") + f'[kinds[{ivar}]]'
512 if opt and intent == 'OUT':
513 kind = f'MISSING if "{varname.upper()}" in missingOUT else {kind}'
514 alllist.append(f'({kind}, {strdim}, {intent}), #{varname}')
515 f.write((" return ([{inlist}\n" + \
516 " ],\n" + \
517 " [{alllist}\n" + \
518 " ],\n" + \
519 " None)\n").format(inlist='\n '.join(inlist),
520 alllist='\n '.join(alllist)))
521
522def main():
523 parser = argparse.ArgumentParser(description='Python binding maker')
524 parser.add_argument('INPUT', type=str,
525 help='FORTRAN input file')
526 parser.add_argument('SCOPE', type=str,
527 help='scope to deal with')
528 parser.add_argument('FORTRAN', type=str,
529 help='FORTRAN output file')
530 parser.add_argument('PYTHON', type=str,
531 help='PYTHON output file')
532 parser.add_argument('LIBSO', type=str, nargs='+',
533 help='Shared lib path')
534 parser.add_argument('--Findexing', default=False, action='store_true',
535 help='If set, array indexes are in the same order as the FORTRAN routine')
536 args = parser.parse_args()
537 pybinding(args.INPUT, args.SCOPE, args.FORTRAN, args.PYTHON, args.LIBSO, args.Findexing)
538
539if __name__ == '__main__':
540 main()