Path: blob/master/ invest-robot-contest_TinkoffBotTwitch-main/venv/lib/python3.8/site-packages/numpy/f2py/f2py2e.py
7757 views
#!/usr/bin/env python31"""23f2py2e - Fortran to Python C/API generator. 2nd Edition.4See __usage__ below.56Copyright 1999--2011 Pearu Peterson all rights reserved,7Pearu Peterson <[email protected]>8Permission to use, modify, and distribute this software is given under the9terms of the NumPy License.1011NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.12$Date: 2005/05/06 08:31:19 $13Pearu Peterson1415"""16import sys17import os18import pprint19import re2021from . import crackfortran22from . import rules23from . import cb_rules24from . import auxfuncs25from . import cfuncs26from . import f90mod_rules27from . import __version__28from . import capi_maps2930f2py_version = __version__.version31numpy_version = __version__.version32errmess = sys.stderr.write33# outmess=sys.stdout.write34show = pprint.pprint35outmess = auxfuncs.outmess3637__usage__ =\38f"""Usage:39401) To construct extension module sources:4142f2py [<options>] <fortran files> [[[only:]||[skip:]] \\43<fortran functions> ] \\44[: <fortran files> ...]45462) To compile fortran files and build extension modules:4748f2py -c [<options>, <build_flib options>, <extra options>] <fortran files>49503) To generate signature files:5152f2py -h <filename.pyf> ...< same options as in (1) >5354Description: This program generates a Python C/API file (<modulename>module.c)55that contains wrappers for given fortran functions so that they56can be called from Python. With the -c option the corresponding57extension modules are built.5859Options:6061--2d-numpy Use numpy.f2py tool with NumPy support. [DEFAULT]62--2d-numeric Use f2py2e tool with Numeric support.63--2d-numarray Use f2py2e tool with Numarray support.64--g3-numpy Use 3rd generation f2py from the separate f2py package.65[NOT AVAILABLE YET]6667-h <filename> Write signatures of the fortran routines to file <filename>68and exit. You can then edit <filename> and use it instead69of <fortran files>. If <filename>==stdout then the70signatures are printed to stdout.71<fortran functions> Names of fortran routines for which Python C/API72functions will be generated. Default is all that are found73in <fortran files>.74<fortran files> Paths to fortran/signature files that will be scanned for75<fortran functions> in order to determine their signatures.76skip: Ignore fortran functions that follow until `:'.77only: Use only fortran functions that follow until `:'.78: Get back to <fortran files> mode.7980-m <modulename> Name of the module; f2py generates a Python/C API81file <modulename>module.c or extension module <modulename>.82Default is 'untitled'.8384--[no-]lower Do [not] lower the cases in <fortran files>. By default,85--lower is assumed with -h key, and --no-lower without -h key.8687--build-dir <dirname> All f2py generated files are created in <dirname>.88Default is tempfile.mkdtemp().8990--overwrite-signature Overwrite existing signature file.9192--[no-]latex-doc Create (or not) <modulename>module.tex.93Default is --no-latex-doc.94--short-latex Create 'incomplete' LaTeX document (without commands95\\documentclass, \\tableofcontents, and \\begin{{document}},96\\end{{document}}).9798--[no-]rest-doc Create (or not) <modulename>module.rst.99Default is --no-rest-doc.100101--debug-capi Create C/API code that reports the state of the wrappers102during runtime. Useful for debugging.103104--[no-]wrap-functions Create Fortran subroutine wrappers to Fortran 77105functions. --wrap-functions is default because it ensures106maximum portability/compiler independence.107108--include-paths <path1>:<path2>:... Search include files from the given109directories.110111--help-link [..] List system resources found by system_info.py. See also112--link-<resource> switch below. [..] is optional list113of resources names. E.g. try 'f2py --help-link lapack_opt'.114115--f2cmap <filename> Load Fortran-to-Python KIND specification from the given116file. Default: .f2py_f2cmap in current directory.117118--quiet Run quietly.119--verbose Run with extra verbosity.120-v Print f2py version ID and exit.121122123numpy.distutils options (only effective with -c):124125--fcompiler= Specify Fortran compiler type by vendor126--compiler= Specify C compiler type (as defined by distutils)127128--help-fcompiler List available Fortran compilers and exit129--f77exec= Specify the path to F77 compiler130--f90exec= Specify the path to F90 compiler131--f77flags= Specify F77 compiler flags132--f90flags= Specify F90 compiler flags133--opt= Specify optimization flags134--arch= Specify architecture specific optimization flags135--noopt Compile without optimization136--noarch Compile without arch-dependent optimization137--debug Compile with debugging information138139Extra options (only effective with -c):140141--link-<resource> Link extension module with <resource> as defined142by numpy.distutils/system_info.py. E.g. to link143with optimized LAPACK libraries (vecLib on MacOSX,144ATLAS elsewhere), use --link-lapack_opt.145See also --help-link switch.146147-L/path/to/lib/ -l<libname>148-D<define> -U<name>149-I/path/to/include/150<filename>.o <filename>.so <filename>.a151152Using the following macros may be required with non-gcc Fortran153compilers:154-DPREPEND_FORTRAN -DNO_APPEND_FORTRAN -DUPPERCASE_FORTRAN155-DUNDERSCORE_G77156157When using -DF2PY_REPORT_ATEXIT, a performance report of F2PY158interface is printed out at exit (platforms: Linux).159160When using -DF2PY_REPORT_ON_ARRAY_COPY=<int>, a message is161sent to stderr whenever F2PY interface makes a copy of an162array. Integer <int> sets the threshold for array sizes when163a message should be shown.164165Version: {f2py_version}166numpy Version: {numpy_version}167Requires: Python 3.5 or higher.168License: NumPy license (see LICENSE.txt in the NumPy source code)169Copyright 1999 - 2011 Pearu Peterson all rights reserved.170https://web.archive.org/web/20140822061353/http://cens.ioc.ee/projects/f2py2e"""171172173def scaninputline(inputline):174files, skipfuncs, onlyfuncs, debug = [], [], [], []175f, f2, f3, f5, f6, f7, f8, f9, f10 = 1, 0, 0, 0, 0, 0, 0, 0, 0176verbose = 1177dolc = -1178dolatexdoc = 0179dorestdoc = 0180wrapfuncs = 1181buildpath = '.'182include_paths = []183signsfile, modulename = None, None184options = {'buildpath': buildpath,185'coutput': None,186'f2py_wrapper_output': None}187for l in inputline:188if l == '':189pass190elif l == 'only:':191f = 0192elif l == 'skip:':193f = -1194elif l == ':':195f = 1196elif l[:8] == '--debug-':197debug.append(l[8:])198elif l == '--lower':199dolc = 1200elif l == '--build-dir':201f6 = 1202elif l == '--no-lower':203dolc = 0204elif l == '--quiet':205verbose = 0206elif l == '--verbose':207verbose += 1208elif l == '--latex-doc':209dolatexdoc = 1210elif l == '--no-latex-doc':211dolatexdoc = 0212elif l == '--rest-doc':213dorestdoc = 1214elif l == '--no-rest-doc':215dorestdoc = 0216elif l == '--wrap-functions':217wrapfuncs = 1218elif l == '--no-wrap-functions':219wrapfuncs = 0220elif l == '--short-latex':221options['shortlatex'] = 1222elif l == '--coutput':223f8 = 1224elif l == '--f2py-wrapper-output':225f9 = 1226elif l == '--f2cmap':227f10 = 1228elif l == '--overwrite-signature':229options['h-overwrite'] = 1230elif l == '-h':231f2 = 1232elif l == '-m':233f3 = 1234elif l[:2] == '-v':235print(f2py_version)236sys.exit()237elif l == '--show-compilers':238f5 = 1239elif l[:8] == '-include':240cfuncs.outneeds['userincludes'].append(l[9:-1])241cfuncs.userincludes[l[9:-1]] = '#include ' + l[8:]242elif l[:15] in '--include_paths':243outmess(244'f2py option --include_paths is deprecated, use --include-paths instead.\n')245f7 = 1246elif l[:15] in '--include-paths':247f7 = 1248elif l[0] == '-':249errmess('Unknown option %s\n' % repr(l))250sys.exit()251elif f2:252f2 = 0253signsfile = l254elif f3:255f3 = 0256modulename = l257elif f6:258f6 = 0259buildpath = l260elif f7:261f7 = 0262include_paths.extend(l.split(os.pathsep))263elif f8:264f8 = 0265options["coutput"] = l266elif f9:267f9 = 0268options["f2py_wrapper_output"] = l269elif f10:270f10 = 0271options["f2cmap_file"] = l272elif f == 1:273try:274with open(l):275pass276files.append(l)277except OSError as detail:278errmess(f'OSError: {detail!s}. Skipping file "{l!s}".\n')279elif f == -1:280skipfuncs.append(l)281elif f == 0:282onlyfuncs.append(l)283if not f5 and not files and not modulename:284print(__usage__)285sys.exit()286if not os.path.isdir(buildpath):287if not verbose:288outmess('Creating build directory %s\n' % (buildpath))289os.mkdir(buildpath)290if signsfile:291signsfile = os.path.join(buildpath, signsfile)292if signsfile and os.path.isfile(signsfile) and 'h-overwrite' not in options:293errmess(294'Signature file "%s" exists!!! Use --overwrite-signature to overwrite.\n' % (signsfile))295sys.exit()296297options['debug'] = debug298options['verbose'] = verbose299if dolc == -1 and not signsfile:300options['do-lower'] = 0301else:302options['do-lower'] = dolc303if modulename:304options['module'] = modulename305if signsfile:306options['signsfile'] = signsfile307if onlyfuncs:308options['onlyfuncs'] = onlyfuncs309if skipfuncs:310options['skipfuncs'] = skipfuncs311options['dolatexdoc'] = dolatexdoc312options['dorestdoc'] = dorestdoc313options['wrapfuncs'] = wrapfuncs314options['buildpath'] = buildpath315options['include_paths'] = include_paths316options.setdefault('f2cmap_file', None)317return files, options318319320def callcrackfortran(files, options):321rules.options = options322crackfortran.debug = options['debug']323crackfortran.verbose = options['verbose']324if 'module' in options:325crackfortran.f77modulename = options['module']326if 'skipfuncs' in options:327crackfortran.skipfuncs = options['skipfuncs']328if 'onlyfuncs' in options:329crackfortran.onlyfuncs = options['onlyfuncs']330crackfortran.include_paths[:] = options['include_paths']331crackfortran.dolowercase = options['do-lower']332postlist = crackfortran.crackfortran(files)333if 'signsfile' in options:334outmess('Saving signatures to file "%s"\n' % (options['signsfile']))335pyf = crackfortran.crack2fortran(postlist)336if options['signsfile'][-6:] == 'stdout':337sys.stdout.write(pyf)338else:339with open(options['signsfile'], 'w') as f:340f.write(pyf)341if options["coutput"] is None:342for mod in postlist:343mod["coutput"] = "%smodule.c" % mod["name"]344else:345for mod in postlist:346mod["coutput"] = options["coutput"]347if options["f2py_wrapper_output"] is None:348for mod in postlist:349mod["f2py_wrapper_output"] = "%s-f2pywrappers.f" % mod["name"]350else:351for mod in postlist:352mod["f2py_wrapper_output"] = options["f2py_wrapper_output"]353return postlist354355356def buildmodules(lst):357cfuncs.buildcfuncs()358outmess('Building modules...\n')359modules, mnames, isusedby = [], [], {}360for item in lst:361if '__user__' in item['name']:362cb_rules.buildcallbacks(item)363else:364if 'use' in item:365for u in item['use'].keys():366if u not in isusedby:367isusedby[u] = []368isusedby[u].append(item['name'])369modules.append(item)370mnames.append(item['name'])371ret = {}372for module, name in zip(modules, mnames):373if name in isusedby:374outmess('\tSkipping module "%s" which is used by %s.\n' % (375name, ','.join('"%s"' % s for s in isusedby[name])))376else:377um = []378if 'use' in module:379for u in module['use'].keys():380if u in isusedby and u in mnames:381um.append(modules[mnames.index(u)])382else:383outmess(384f'\tModule "{name}" uses nonexisting "{u}" '385'which will be ignored.\n')386ret[name] = {}387dict_append(ret[name], rules.buildmodule(module, um))388return ret389390391def dict_append(d_out, d_in):392for (k, v) in d_in.items():393if k not in d_out:394d_out[k] = []395if isinstance(v, list):396d_out[k] = d_out[k] + v397else:398d_out[k].append(v)399400401def run_main(comline_list):402"""403Equivalent to running::404405f2py <args>406407where ``<args>=string.join(<list>,' ')``, but in Python. Unless408``-h`` is used, this function returns a dictionary containing409information on generated modules and their dependencies on source410files. For example, the command ``f2py -m scalar scalar.f`` can be411executed from Python as follows412413You cannot build extension modules with this function, that is,414using ``-c`` is not allowed. Use ``compile`` command instead415416Examples417--------418.. literalinclude:: ../../source/f2py/code/results/run_main_session.dat419:language: python420421"""422crackfortran.reset_global_f2py_vars()423f2pydir = os.path.dirname(os.path.abspath(cfuncs.__file__))424fobjhsrc = os.path.join(f2pydir, 'src', 'fortranobject.h')425fobjcsrc = os.path.join(f2pydir, 'src', 'fortranobject.c')426files, options = scaninputline(comline_list)427auxfuncs.options = options428capi_maps.load_f2cmap_file(options['f2cmap_file'])429postlist = callcrackfortran(files, options)430isusedby = {}431for plist in postlist:432if 'use' in plist:433for u in plist['use'].keys():434if u not in isusedby:435isusedby[u] = []436isusedby[u].append(plist['name'])437for plist in postlist:438if plist['block'] == 'python module' and '__user__' in plist['name']:439if plist['name'] in isusedby:440# if not quiet:441outmess(442f'Skipping Makefile build for module "{plist["name"]}" '443'which is used by {}\n'.format(444','.join(f'"{s}"' for s in isusedby[plist['name']])))445if 'signsfile' in options:446if options['verbose'] > 1:447outmess(448'Stopping. Edit the signature file and then run f2py on the signature file: ')449outmess('%s %s\n' %450(os.path.basename(sys.argv[0]), options['signsfile']))451return452for plist in postlist:453if plist['block'] != 'python module':454if 'python module' not in options:455errmess(456'Tip: If your original code is Fortran source then you must use -m option.\n')457raise TypeError('All blocks must be python module blocks but got %s' % (458repr(postlist[i]['block'])))459auxfuncs.debugoptions = options['debug']460f90mod_rules.options = options461auxfuncs.wrapfuncs = options['wrapfuncs']462463ret = buildmodules(postlist)464465for mn in ret.keys():466dict_append(ret[mn], {'csrc': fobjcsrc, 'h': fobjhsrc})467return ret468469470def filter_files(prefix, suffix, files, remove_prefix=None):471"""472Filter files by prefix and suffix.473"""474filtered, rest = [], []475match = re.compile(prefix + r'.*' + suffix + r'\Z').match476if remove_prefix:477ind = len(prefix)478else:479ind = 0480for file in [x.strip() for x in files]:481if match(file):482filtered.append(file[ind:])483else:484rest.append(file)485return filtered, rest486487488def get_prefix(module):489p = os.path.dirname(os.path.dirname(module.__file__))490return p491492493def run_compile():494"""495Do it all in one call!496"""497import tempfile498499i = sys.argv.index('-c')500del sys.argv[i]501502remove_build_dir = 0503try:504i = sys.argv.index('--build-dir')505except ValueError:506i = None507if i is not None:508build_dir = sys.argv[i + 1]509del sys.argv[i + 1]510del sys.argv[i]511else:512remove_build_dir = 1513build_dir = tempfile.mkdtemp()514515_reg1 = re.compile(r'--link-')516sysinfo_flags = [_m for _m in sys.argv[1:] if _reg1.match(_m)]517sys.argv = [_m for _m in sys.argv if _m not in sysinfo_flags]518if sysinfo_flags:519sysinfo_flags = [f[7:] for f in sysinfo_flags]520521_reg2 = re.compile(522r'--((no-|)(wrap-functions|lower)|debug-capi|quiet)|-include')523f2py_flags = [_m for _m in sys.argv[1:] if _reg2.match(_m)]524sys.argv = [_m for _m in sys.argv if _m not in f2py_flags]525f2py_flags2 = []526fl = 0527for a in sys.argv[1:]:528if a in ['only:', 'skip:']:529fl = 1530elif a == ':':531fl = 0532if fl or a == ':':533f2py_flags2.append(a)534if f2py_flags2 and f2py_flags2[-1] != ':':535f2py_flags2.append(':')536f2py_flags.extend(f2py_flags2)537538sys.argv = [_m for _m in sys.argv if _m not in f2py_flags2]539_reg3 = re.compile(540r'--((f(90)?compiler(-exec|)|compiler)=|help-compiler)')541flib_flags = [_m for _m in sys.argv[1:] if _reg3.match(_m)]542sys.argv = [_m for _m in sys.argv if _m not in flib_flags]543_reg4 = re.compile(544r'--((f(77|90)(flags|exec)|opt|arch)=|(debug|noopt|noarch|help-fcompiler))')545fc_flags = [_m for _m in sys.argv[1:] if _reg4.match(_m)]546sys.argv = [_m for _m in sys.argv if _m not in fc_flags]547548del_list = []549for s in flib_flags:550v = '--fcompiler='551if s[:len(v)] == v:552from numpy.distutils import fcompiler553fcompiler.load_all_fcompiler_classes()554allowed_keys = list(fcompiler.fcompiler_class.keys())555nv = ov = s[len(v):].lower()556if ov not in allowed_keys:557vmap = {} # XXX558try:559nv = vmap[ov]560except KeyError:561if ov not in vmap.values():562print('Unknown vendor: "%s"' % (s[len(v):]))563nv = ov564i = flib_flags.index(s)565flib_flags[i] = '--fcompiler=' + nv566continue567for s in del_list:568i = flib_flags.index(s)569del flib_flags[i]570assert len(flib_flags) <= 2, repr(flib_flags)571572_reg5 = re.compile(r'--(verbose)')573setup_flags = [_m for _m in sys.argv[1:] if _reg5.match(_m)]574sys.argv = [_m for _m in sys.argv if _m not in setup_flags]575576if '--quiet' in f2py_flags:577setup_flags.append('--quiet')578579modulename = 'untitled'580sources = sys.argv[1:]581582for optname in ['--include_paths', '--include-paths', '--f2cmap']:583if optname in sys.argv:584i = sys.argv.index(optname)585f2py_flags.extend(sys.argv[i:i + 2])586del sys.argv[i + 1], sys.argv[i]587sources = sys.argv[1:]588589if '-m' in sys.argv:590i = sys.argv.index('-m')591modulename = sys.argv[i + 1]592del sys.argv[i + 1], sys.argv[i]593sources = sys.argv[1:]594else:595from numpy.distutils.command.build_src import get_f2py_modulename596pyf_files, sources = filter_files('', '[.]pyf([.]src|)', sources)597sources = pyf_files + sources598for f in pyf_files:599modulename = get_f2py_modulename(f)600if modulename:601break602603extra_objects, sources = filter_files('', '[.](o|a|so|dylib)', sources)604include_dirs, sources = filter_files('-I', '', sources, remove_prefix=1)605library_dirs, sources = filter_files('-L', '', sources, remove_prefix=1)606libraries, sources = filter_files('-l', '', sources, remove_prefix=1)607undef_macros, sources = filter_files('-U', '', sources, remove_prefix=1)608define_macros, sources = filter_files('-D', '', sources, remove_prefix=1)609for i in range(len(define_macros)):610name_value = define_macros[i].split('=', 1)611if len(name_value) == 1:612name_value.append(None)613if len(name_value) == 2:614define_macros[i] = tuple(name_value)615else:616print('Invalid use of -D:', name_value)617618from numpy.distutils.system_info import get_info619620num_info = {}621if num_info:622include_dirs.extend(num_info.get('include_dirs', []))623624from numpy.distutils.core import setup, Extension625ext_args = {'name': modulename, 'sources': sources,626'include_dirs': include_dirs,627'library_dirs': library_dirs,628'libraries': libraries,629'define_macros': define_macros,630'undef_macros': undef_macros,631'extra_objects': extra_objects,632'f2py_options': f2py_flags,633}634635if sysinfo_flags:636from numpy.distutils.misc_util import dict_append637for n in sysinfo_flags:638i = get_info(n)639if not i:640outmess('No %s resources found in system'641' (try `f2py --help-link`)\n' % (repr(n)))642dict_append(ext_args, **i)643644ext = Extension(**ext_args)645sys.argv = [sys.argv[0]] + setup_flags646sys.argv.extend(['build',647'--build-temp', build_dir,648'--build-base', build_dir,649'--build-platlib', '.',650# disable CCompilerOpt651'--disable-optimization'])652if fc_flags:653sys.argv.extend(['config_fc'] + fc_flags)654if flib_flags:655sys.argv.extend(['build_ext'] + flib_flags)656657setup(ext_modules=[ext])658659if remove_build_dir and os.path.exists(build_dir):660import shutil661outmess('Removing build directory %s\n' % (build_dir))662shutil.rmtree(build_dir)663664665def main():666if '--help-link' in sys.argv[1:]:667sys.argv.remove('--help-link')668from numpy.distutils.system_info import show_all669show_all()670return671672# Probably outdated options that were not working before 1.16673if '--g3-numpy' in sys.argv[1:]:674sys.stderr.write("G3 f2py support is not implemented, yet.\\n")675sys.exit(1)676elif '--2e-numeric' in sys.argv[1:]:677sys.argv.remove('--2e-numeric')678elif '--2e-numarray' in sys.argv[1:]:679# Note that this errors becaust the -DNUMARRAY argument is680# not recognized. Just here for back compatibility and the681# error message.682sys.argv.append("-DNUMARRAY")683sys.argv.remove('--2e-numarray')684elif '--2e-numpy' in sys.argv[1:]:685sys.argv.remove('--2e-numpy')686else:687pass688689if '-c' in sys.argv[1:]:690run_compile()691else:692run_main(sys.argv[1:])693694695