Path: blob/master/ invest-robot-contest_TinkoffBotTwitch-main/venv/lib/python3.8/site-packages/numpy/f2py/auxfuncs.py
7762 views
#!/usr/bin/env python31"""23Auxiliary functions for f2py2e.45Copyright 1999,2000 Pearu Peterson all rights reserved,6Pearu Peterson <[email protected]>7Permission to use, modify, and distribute this software is given under the8terms of the NumPy (BSD style) LICENSE.91011NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.12$Date: 2005/07/24 19:01:55 $13Pearu Peterson1415"""16import pprint17import sys18import types19from functools import reduce2021from . import __version__22from . import cfuncs2324__all__ = [25'applyrules', 'debugcapi', 'dictappend', 'errmess', 'gentitle',26'getargs2', 'getcallprotoargument', 'getcallstatement',27'getfortranname', 'getpymethoddef', 'getrestdoc', 'getusercode',28'getusercode1', 'hasbody', 'hascallstatement', 'hascommon',29'hasexternals', 'hasinitvalue', 'hasnote', 'hasresultnote',30'isallocatable', 'isarray', 'isarrayofstrings', 'iscomplex',31'iscomplexarray', 'iscomplexfunction', 'iscomplexfunction_warn',32'isdouble', 'isdummyroutine', 'isexternal', 'isfunction',33'isfunction_wrap', 'isint1array', 'isinteger', 'isintent_aux',34'isintent_c', 'isintent_callback', 'isintent_copy', 'isintent_dict',35'isintent_hide', 'isintent_in', 'isintent_inout', 'isintent_inplace',36'isintent_nothide', 'isintent_out', 'isintent_overwrite', 'islogical',37'islogicalfunction', 'islong_complex', 'islong_double',38'islong_doublefunction', 'islong_long', 'islong_longfunction',39'ismodule', 'ismoduleroutine', 'isoptional', 'isprivate', 'isrequired',40'isroutine', 'isscalar', 'issigned_long_longarray', 'isstring',41'isstringarray', 'isstringfunction', 'issubroutine',42'issubroutine_wrap', 'isthreadsafe', 'isunsigned', 'isunsigned_char',43'isunsigned_chararray', 'isunsigned_long_long',44'isunsigned_long_longarray', 'isunsigned_short',45'isunsigned_shortarray', 'l_and', 'l_not', 'l_or', 'outmess',46'replace', 'show', 'stripcomma', 'throw_error',47]484950f2py_version = __version__.version515253errmess = sys.stderr.write54show = pprint.pprint5556options = {}57debugoptions = []58wrapfuncs = 1596061def outmess(t):62if options.get('verbose', 1):63sys.stdout.write(t)646566def debugcapi(var):67return 'capi' in debugoptions686970def _isstring(var):71return 'typespec' in var and var['typespec'] == 'character' and \72not isexternal(var)737475def isstring(var):76return _isstring(var) and not isarray(var)777879def ischaracter(var):80return isstring(var) and 'charselector' not in var818283def isstringarray(var):84return isarray(var) and _isstring(var)858687def isarrayofstrings(var):88# leaving out '*' for now so that `character*(*) a(m)` and `character89# a(m,*)` are treated differently. Luckily `character**` is illegal.90return isstringarray(var) and var['dimension'][-1] == '(*)'919293def isarray(var):94return 'dimension' in var and not isexternal(var)959697def isscalar(var):98return not (isarray(var) or isstring(var) or isexternal(var))99100101def iscomplex(var):102return isscalar(var) and \103var.get('typespec') in ['complex', 'double complex']104105106def islogical(var):107return isscalar(var) and var.get('typespec') == 'logical'108109110def isinteger(var):111return isscalar(var) and var.get('typespec') == 'integer'112113114def isreal(var):115return isscalar(var) and var.get('typespec') == 'real'116117118def get_kind(var):119try:120return var['kindselector']['*']121except KeyError:122try:123return var['kindselector']['kind']124except KeyError:125pass126127128def islong_long(var):129if not isscalar(var):130return 0131if var.get('typespec') not in ['integer', 'logical']:132return 0133return get_kind(var) == '8'134135136def isunsigned_char(var):137if not isscalar(var):138return 0139if var.get('typespec') != 'integer':140return 0141return get_kind(var) == '-1'142143144def isunsigned_short(var):145if not isscalar(var):146return 0147if var.get('typespec') != 'integer':148return 0149return get_kind(var) == '-2'150151152def isunsigned(var):153if not isscalar(var):154return 0155if var.get('typespec') != 'integer':156return 0157return get_kind(var) == '-4'158159160def isunsigned_long_long(var):161if not isscalar(var):162return 0163if var.get('typespec') != 'integer':164return 0165return get_kind(var) == '-8'166167168def isdouble(var):169if not isscalar(var):170return 0171if not var.get('typespec') == 'real':172return 0173return get_kind(var) == '8'174175176def islong_double(var):177if not isscalar(var):178return 0179if not var.get('typespec') == 'real':180return 0181return get_kind(var) == '16'182183184def islong_complex(var):185if not iscomplex(var):186return 0187return get_kind(var) == '32'188189190def iscomplexarray(var):191return isarray(var) and \192var.get('typespec') in ['complex', 'double complex']193194195def isint1array(var):196return isarray(var) and var.get('typespec') == 'integer' \197and get_kind(var) == '1'198199200def isunsigned_chararray(var):201return isarray(var) and var.get('typespec') in ['integer', 'logical']\202and get_kind(var) == '-1'203204205def isunsigned_shortarray(var):206return isarray(var) and var.get('typespec') in ['integer', 'logical']\207and get_kind(var) == '-2'208209210def isunsignedarray(var):211return isarray(var) and var.get('typespec') in ['integer', 'logical']\212and get_kind(var) == '-4'213214215def isunsigned_long_longarray(var):216return isarray(var) and var.get('typespec') in ['integer', 'logical']\217and get_kind(var) == '-8'218219220def issigned_chararray(var):221return isarray(var) and var.get('typespec') in ['integer', 'logical']\222and get_kind(var) == '1'223224225def issigned_shortarray(var):226return isarray(var) and var.get('typespec') in ['integer', 'logical']\227and get_kind(var) == '2'228229230def issigned_array(var):231return isarray(var) and var.get('typespec') in ['integer', 'logical']\232and get_kind(var) == '4'233234235def issigned_long_longarray(var):236return isarray(var) and var.get('typespec') in ['integer', 'logical']\237and get_kind(var) == '8'238239240def isallocatable(var):241return 'attrspec' in var and 'allocatable' in var['attrspec']242243244def ismutable(var):245return not ('dimension' not in var or isstring(var))246247248def ismoduleroutine(rout):249return 'modulename' in rout250251252def ismodule(rout):253return 'block' in rout and 'module' == rout['block']254255256def isfunction(rout):257return 'block' in rout and 'function' == rout['block']258259260def isfunction_wrap(rout):261if isintent_c(rout):262return 0263return wrapfuncs and isfunction(rout) and (not isexternal(rout))264265266def issubroutine(rout):267return 'block' in rout and 'subroutine' == rout['block']268269270def issubroutine_wrap(rout):271if isintent_c(rout):272return 0273return issubroutine(rout) and hasassumedshape(rout)274275276def hasassumedshape(rout):277if rout.get('hasassumedshape'):278return True279for a in rout['args']:280for d in rout['vars'].get(a, {}).get('dimension', []):281if d == ':':282rout['hasassumedshape'] = True283return True284return False285286287def requiresf90wrapper(rout):288return ismoduleroutine(rout) or hasassumedshape(rout)289290291def isroutine(rout):292return isfunction(rout) or issubroutine(rout)293294295def islogicalfunction(rout):296if not isfunction(rout):297return 0298if 'result' in rout:299a = rout['result']300else:301a = rout['name']302if a in rout['vars']:303return islogical(rout['vars'][a])304return 0305306307def islong_longfunction(rout):308if not isfunction(rout):309return 0310if 'result' in rout:311a = rout['result']312else:313a = rout['name']314if a in rout['vars']:315return islong_long(rout['vars'][a])316return 0317318319def islong_doublefunction(rout):320if not isfunction(rout):321return 0322if 'result' in rout:323a = rout['result']324else:325a = rout['name']326if a in rout['vars']:327return islong_double(rout['vars'][a])328return 0329330331def iscomplexfunction(rout):332if not isfunction(rout):333return 0334if 'result' in rout:335a = rout['result']336else:337a = rout['name']338if a in rout['vars']:339return iscomplex(rout['vars'][a])340return 0341342343def iscomplexfunction_warn(rout):344if iscomplexfunction(rout):345outmess("""\346**************************************************************347Warning: code with a function returning complex value348may not work correctly with your Fortran compiler.349When using GNU gcc/g77 compilers, codes should work350correctly for callbacks with:351f2py -c -DF2PY_CB_RETURNCOMPLEX352**************************************************************\n""")353return 1354return 0355356357def isstringfunction(rout):358if not isfunction(rout):359return 0360if 'result' in rout:361a = rout['result']362else:363a = rout['name']364if a in rout['vars']:365return isstring(rout['vars'][a])366return 0367368369def hasexternals(rout):370return 'externals' in rout and rout['externals']371372373def isthreadsafe(rout):374return 'f2pyenhancements' in rout and \375'threadsafe' in rout['f2pyenhancements']376377378def hasvariables(rout):379return 'vars' in rout and rout['vars']380381382def isoptional(var):383return ('attrspec' in var and 'optional' in var['attrspec'] and384'required' not in var['attrspec']) and isintent_nothide(var)385386387def isexternal(var):388return 'attrspec' in var and 'external' in var['attrspec']389390391def isrequired(var):392return not isoptional(var) and isintent_nothide(var)393394395def isintent_in(var):396if 'intent' not in var:397return 1398if 'hide' in var['intent']:399return 0400if 'inplace' in var['intent']:401return 0402if 'in' in var['intent']:403return 1404if 'out' in var['intent']:405return 0406if 'inout' in var['intent']:407return 0408if 'outin' in var['intent']:409return 0410return 1411412413def isintent_inout(var):414return ('intent' in var and ('inout' in var['intent'] or415'outin' in var['intent']) and 'in' not in var['intent'] and416'hide' not in var['intent'] and 'inplace' not in var['intent'])417418419def isintent_out(var):420return 'out' in var.get('intent', [])421422423def isintent_hide(var):424return ('intent' in var and ('hide' in var['intent'] or425('out' in var['intent'] and 'in' not in var['intent'] and426(not l_or(isintent_inout, isintent_inplace)(var)))))427428def isintent_nothide(var):429return not isintent_hide(var)430431432def isintent_c(var):433return 'c' in var.get('intent', [])434435436def isintent_cache(var):437return 'cache' in var.get('intent', [])438439440def isintent_copy(var):441return 'copy' in var.get('intent', [])442443444def isintent_overwrite(var):445return 'overwrite' in var.get('intent', [])446447448def isintent_callback(var):449return 'callback' in var.get('intent', [])450451452def isintent_inplace(var):453return 'inplace' in var.get('intent', [])454455456def isintent_aux(var):457return 'aux' in var.get('intent', [])458459460def isintent_aligned4(var):461return 'aligned4' in var.get('intent', [])462463464def isintent_aligned8(var):465return 'aligned8' in var.get('intent', [])466467468def isintent_aligned16(var):469return 'aligned16' in var.get('intent', [])470471isintent_dict = {isintent_in: 'INTENT_IN', isintent_inout: 'INTENT_INOUT',472isintent_out: 'INTENT_OUT', isintent_hide: 'INTENT_HIDE',473isintent_cache: 'INTENT_CACHE',474isintent_c: 'INTENT_C', isoptional: 'OPTIONAL',475isintent_inplace: 'INTENT_INPLACE',476isintent_aligned4: 'INTENT_ALIGNED4',477isintent_aligned8: 'INTENT_ALIGNED8',478isintent_aligned16: 'INTENT_ALIGNED16',479}480481482def isprivate(var):483return 'attrspec' in var and 'private' in var['attrspec']484485486def hasinitvalue(var):487return '=' in var488489490def hasinitvalueasstring(var):491if not hasinitvalue(var):492return 0493return var['='][0] in ['"', "'"]494495496def hasnote(var):497return 'note' in var498499500def hasresultnote(rout):501if not isfunction(rout):502return 0503if 'result' in rout:504a = rout['result']505else:506a = rout['name']507if a in rout['vars']:508return hasnote(rout['vars'][a])509return 0510511512def hascommon(rout):513return 'common' in rout514515516def containscommon(rout):517if hascommon(rout):518return 1519if hasbody(rout):520for b in rout['body']:521if containscommon(b):522return 1523return 0524525526def containsmodule(block):527if ismodule(block):528return 1529if not hasbody(block):530return 0531for b in block['body']:532if containsmodule(b):533return 1534return 0535536537def hasbody(rout):538return 'body' in rout539540541def hascallstatement(rout):542return getcallstatement(rout) is not None543544545def istrue(var):546return 1547548549def isfalse(var):550return 0551552553class F2PYError(Exception):554pass555556557class throw_error:558559def __init__(self, mess):560self.mess = mess561562def __call__(self, var):563mess = '\n\n var = %s\n Message: %s\n' % (var, self.mess)564raise F2PYError(mess)565566567def l_and(*f):568l, l2 = 'lambda v', []569for i in range(len(f)):570l = '%s,f%d=f[%d]' % (l, i, i)571l2.append('f%d(v)' % (i))572return eval('%s:%s' % (l, ' and '.join(l2)))573574575def l_or(*f):576l, l2 = 'lambda v', []577for i in range(len(f)):578l = '%s,f%d=f[%d]' % (l, i, i)579l2.append('f%d(v)' % (i))580return eval('%s:%s' % (l, ' or '.join(l2)))581582583def l_not(f):584return eval('lambda v,f=f:not f(v)')585586587def isdummyroutine(rout):588try:589return rout['f2pyenhancements']['fortranname'] == ''590except KeyError:591return 0592593594def getfortranname(rout):595try:596name = rout['f2pyenhancements']['fortranname']597if name == '':598raise KeyError599if not name:600errmess('Failed to use fortranname from %s\n' %601(rout['f2pyenhancements']))602raise KeyError603except KeyError:604name = rout['name']605return name606607608def getmultilineblock(rout, blockname, comment=1, counter=0):609try:610r = rout['f2pyenhancements'].get(blockname)611except KeyError:612return613if not r:614return615if counter > 0 and isinstance(r, str):616return617if isinstance(r, list):618if counter >= len(r):619return620r = r[counter]621if r[:3] == "'''":622if comment:623r = '\t/* start ' + blockname + \624' multiline (' + repr(counter) + ') */\n' + r[3:]625else:626r = r[3:]627if r[-3:] == "'''":628if comment:629r = r[:-3] + '\n\t/* end multiline (' + repr(counter) + ')*/'630else:631r = r[:-3]632else:633errmess("%s multiline block should end with `'''`: %s\n"634% (blockname, repr(r)))635return r636637638def getcallstatement(rout):639return getmultilineblock(rout, 'callstatement')640641642def getcallprotoargument(rout, cb_map={}):643r = getmultilineblock(rout, 'callprotoargument', comment=0)644if r:645return r646if hascallstatement(rout):647outmess(648'warning: callstatement is defined without callprotoargument\n')649return650from .capi_maps import getctype651arg_types, arg_types2 = [], []652if l_and(isstringfunction, l_not(isfunction_wrap))(rout):653arg_types.extend(['char*', 'size_t'])654for n in rout['args']:655var = rout['vars'][n]656if isintent_callback(var):657continue658if n in cb_map:659ctype = cb_map[n] + '_typedef'660else:661ctype = getctype(var)662if l_and(isintent_c, l_or(isscalar, iscomplex))(var):663pass664elif isstring(var):665pass666else:667ctype = ctype + '*'668if isstring(var) or isarrayofstrings(var):669arg_types2.append('size_t')670arg_types.append(ctype)671672proto_args = ','.join(arg_types + arg_types2)673if not proto_args:674proto_args = 'void'675return proto_args676677678def getusercode(rout):679return getmultilineblock(rout, 'usercode')680681682def getusercode1(rout):683return getmultilineblock(rout, 'usercode', counter=1)684685686def getpymethoddef(rout):687return getmultilineblock(rout, 'pymethoddef')688689690def getargs(rout):691sortargs, args = [], []692if 'args' in rout:693args = rout['args']694if 'sortvars' in rout:695for a in rout['sortvars']:696if a in args:697sortargs.append(a)698for a in args:699if a not in sortargs:700sortargs.append(a)701else:702sortargs = rout['args']703return args, sortargs704705706def getargs2(rout):707sortargs, args = [], rout.get('args', [])708auxvars = [a for a in rout['vars'].keys() if isintent_aux(rout['vars'][a])709and a not in args]710args = auxvars + args711if 'sortvars' in rout:712for a in rout['sortvars']:713if a in args:714sortargs.append(a)715for a in args:716if a not in sortargs:717sortargs.append(a)718else:719sortargs = auxvars + rout['args']720return args, sortargs721722723def getrestdoc(rout):724if 'f2pymultilines' not in rout:725return None726k = None727if rout['block'] == 'python module':728k = rout['block'], rout['name']729return rout['f2pymultilines'].get(k, None)730731732def gentitle(name):733l = (80 - len(name) - 6) // 2734return '/*%s %s %s*/' % (l * '*', name, l * '*')735736737def flatlist(l):738if isinstance(l, list):739return reduce(lambda x, y, f=flatlist: x + f(y), l, [])740return [l]741742743def stripcomma(s):744if s and s[-1] == ',':745return s[:-1]746return s747748749def replace(str, d, defaultsep=''):750if isinstance(d, list):751return [replace(str, _m, defaultsep) for _m in d]752if isinstance(str, list):753return [replace(_m, d, defaultsep) for _m in str]754for k in 2 * list(d.keys()):755if k == 'separatorsfor':756continue757if 'separatorsfor' in d and k in d['separatorsfor']:758sep = d['separatorsfor'][k]759else:760sep = defaultsep761if isinstance(d[k], list):762str = str.replace('#%s#' % (k), sep.join(flatlist(d[k])))763else:764str = str.replace('#%s#' % (k), d[k])765return str766767768def dictappend(rd, ar):769if isinstance(ar, list):770for a in ar:771rd = dictappend(rd, a)772return rd773for k in ar.keys():774if k[0] == '_':775continue776if k in rd:777if isinstance(rd[k], str):778rd[k] = [rd[k]]779if isinstance(rd[k], list):780if isinstance(ar[k], list):781rd[k] = rd[k] + ar[k]782else:783rd[k].append(ar[k])784elif isinstance(rd[k], dict):785if isinstance(ar[k], dict):786if k == 'separatorsfor':787for k1 in ar[k].keys():788if k1 not in rd[k]:789rd[k][k1] = ar[k][k1]790else:791rd[k] = dictappend(rd[k], ar[k])792else:793rd[k] = ar[k]794return rd795796797def applyrules(rules, d, var={}):798ret = {}799if isinstance(rules, list):800for r in rules:801rr = applyrules(r, d, var)802ret = dictappend(ret, rr)803if '_break' in rr:804break805return ret806if '_check' in rules and (not rules['_check'](var)):807return ret808if 'need' in rules:809res = applyrules({'needs': rules['need']}, d, var)810if 'needs' in res:811cfuncs.append_needs(res['needs'])812813for k in rules.keys():814if k == 'separatorsfor':815ret[k] = rules[k]816continue817if isinstance(rules[k], str):818ret[k] = replace(rules[k], d)819elif isinstance(rules[k], list):820ret[k] = []821for i in rules[k]:822ar = applyrules({k: i}, d, var)823if k in ar:824ret[k].append(ar[k])825elif k[0] == '_':826continue827elif isinstance(rules[k], dict):828ret[k] = []829for k1 in rules[k].keys():830if isinstance(k1, types.FunctionType) and k1(var):831if isinstance(rules[k][k1], list):832for i in rules[k][k1]:833if isinstance(i, dict):834res = applyrules({'supertext': i}, d, var)835if 'supertext' in res:836i = res['supertext']837else:838i = ''839ret[k].append(replace(i, d))840else:841i = rules[k][k1]842if isinstance(i, dict):843res = applyrules({'supertext': i}, d)844if 'supertext' in res:845i = res['supertext']846else:847i = ''848ret[k].append(replace(i, d))849else:850errmess('applyrules: ignoring rule %s.\n' % repr(rules[k]))851if isinstance(ret[k], list):852if len(ret[k]) == 1:853ret[k] = ret[k][0]854if ret[k] == []:855del ret[k]856return ret857858859