system_info.py 111 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267
  1. """
  2. This file defines a set of system_info classes for getting
  3. information about various resources (libraries, library directories,
  4. include directories, etc.) in the system. Usage:
  5. info_dict = get_info(<name>)
  6. where <name> is a string 'atlas','x11','fftw','lapack','blas',
  7. 'lapack_src', 'blas_src', etc. For a complete list of allowed names,
  8. see the definition of get_info() function below.
  9. Returned info_dict is a dictionary which is compatible with
  10. distutils.setup keyword arguments. If info_dict == {}, then the
  11. asked resource is not available (system_info could not find it).
  12. Several *_info classes specify an environment variable to specify
  13. the locations of software. When setting the corresponding environment
  14. variable to 'None' then the software will be ignored, even when it
  15. is available in system.
  16. Global parameters:
  17. system_info.search_static_first - search static libraries (.a)
  18. in precedence to shared ones (.so, .sl) if enabled.
  19. system_info.verbosity - output the results to stdout if enabled.
  20. The file 'site.cfg' is looked for in
  21. 1) Directory of main setup.py file being run.
  22. 2) Home directory of user running the setup.py file as ~/.numpy-site.cfg
  23. 3) System wide directory (location of this file...)
  24. The first one found is used to get system configuration options The
  25. format is that used by ConfigParser (i.e., Windows .INI style). The
  26. section ALL is not intended for general use.
  27. Appropriate defaults are used if nothing is specified.
  28. The order of finding the locations of resources is the following:
  29. 1. environment variable
  30. 2. section in site.cfg
  31. 3. DEFAULT section in site.cfg
  32. 4. System default search paths (see ``default_*`` variables below).
  33. Only the first complete match is returned.
  34. Currently, the following classes are available, along with their section names:
  35. Numeric_info:Numeric
  36. _numpy_info:Numeric
  37. _pkg_config_info:None
  38. accelerate_info:accelerate
  39. accelerate_lapack_info:accelerate
  40. agg2_info:agg2
  41. amd_info:amd
  42. atlas_3_10_blas_info:atlas
  43. atlas_3_10_blas_threads_info:atlas
  44. atlas_3_10_info:atlas
  45. atlas_3_10_threads_info:atlas
  46. atlas_blas_info:atlas
  47. atlas_blas_threads_info:atlas
  48. atlas_info:atlas
  49. atlas_threads_info:atlas
  50. blas64__opt_info:ALL # usage recommended (general ILP64 BLAS, 64_ symbol suffix)
  51. blas_ilp64_opt_info:ALL # usage recommended (general ILP64 BLAS)
  52. blas_ilp64_plain_opt_info:ALL # usage recommended (general ILP64 BLAS, no symbol suffix)
  53. blas_info:blas
  54. blas_mkl_info:mkl
  55. blas_ssl2_info:ssl2
  56. blas_opt_info:ALL # usage recommended
  57. blas_src_info:blas_src
  58. blis_info:blis
  59. boost_python_info:boost_python
  60. dfftw_info:fftw
  61. dfftw_threads_info:fftw
  62. djbfft_info:djbfft
  63. f2py_info:ALL
  64. fft_opt_info:ALL
  65. fftw2_info:fftw
  66. fftw3_info:fftw3
  67. fftw_info:fftw
  68. fftw_threads_info:fftw
  69. flame_info:flame
  70. freetype2_info:freetype2
  71. gdk_2_info:gdk_2
  72. gdk_info:gdk
  73. gdk_pixbuf_2_info:gdk_pixbuf_2
  74. gdk_pixbuf_xlib_2_info:gdk_pixbuf_xlib_2
  75. gdk_x11_2_info:gdk_x11_2
  76. gtkp_2_info:gtkp_2
  77. gtkp_x11_2_info:gtkp_x11_2
  78. lapack64__opt_info:ALL # usage recommended (general ILP64 LAPACK, 64_ symbol suffix)
  79. lapack_atlas_3_10_info:atlas
  80. lapack_atlas_3_10_threads_info:atlas
  81. lapack_atlas_info:atlas
  82. lapack_atlas_threads_info:atlas
  83. lapack_ilp64_opt_info:ALL # usage recommended (general ILP64 LAPACK)
  84. lapack_ilp64_plain_opt_info:ALL # usage recommended (general ILP64 LAPACK, no symbol suffix)
  85. lapack_info:lapack
  86. lapack_mkl_info:mkl
  87. lapack_ssl2_info:ssl2
  88. lapack_opt_info:ALL # usage recommended
  89. lapack_src_info:lapack_src
  90. mkl_info:mkl
  91. ssl2_info:ssl2
  92. numarray_info:numarray
  93. numerix_info:numerix
  94. numpy_info:numpy
  95. openblas64__info:openblas64_
  96. openblas64__lapack_info:openblas64_
  97. openblas_clapack_info:openblas
  98. openblas_ilp64_info:openblas_ilp64
  99. openblas_ilp64_lapack_info:openblas_ilp64
  100. openblas_info:openblas
  101. openblas_lapack_info:openblas
  102. sfftw_info:fftw
  103. sfftw_threads_info:fftw
  104. system_info:ALL
  105. umfpack_info:umfpack
  106. wx_info:wx
  107. x11_info:x11
  108. xft_info:xft
  109. Note that blas_opt_info and lapack_opt_info honor the NPY_BLAS_ORDER
  110. and NPY_LAPACK_ORDER environment variables to determine the order in which
  111. specific BLAS and LAPACK libraries are searched for.
  112. This search (or autodetection) can be bypassed by defining the environment
  113. variables NPY_BLAS_LIBS and NPY_LAPACK_LIBS, which should then contain the
  114. exact linker flags to use (language will be set to F77). Building against
  115. Netlib BLAS/LAPACK or stub files, in order to be able to switch BLAS and LAPACK
  116. implementations at runtime. If using this to build NumPy itself, it is
  117. recommended to also define NPY_CBLAS_LIBS (assuming your BLAS library has a
  118. CBLAS interface) to enable CBLAS usage for matrix multiplication (unoptimized
  119. otherwise).
  120. Example:
  121. ----------
  122. [DEFAULT]
  123. # default section
  124. library_dirs = /usr/lib:/usr/local/lib:/opt/lib
  125. include_dirs = /usr/include:/usr/local/include:/opt/include
  126. src_dirs = /usr/local/src:/opt/src
  127. # search static libraries (.a) in preference to shared ones (.so)
  128. search_static_first = 0
  129. [fftw]
  130. libraries = rfftw, fftw
  131. [atlas]
  132. library_dirs = /usr/lib/3dnow:/usr/lib/3dnow/atlas
  133. # for overriding the names of the atlas libraries
  134. libraries = lapack, f77blas, cblas, atlas
  135. [x11]
  136. library_dirs = /usr/X11R6/lib
  137. include_dirs = /usr/X11R6/include
  138. ----------
  139. Note that the ``libraries`` key is the default setting for libraries.
  140. Authors:
  141. Pearu Peterson <pearu@cens.ioc.ee>, February 2002
  142. David M. Cooke <cookedm@physics.mcmaster.ca>, April 2002
  143. Copyright 2002 Pearu Peterson all rights reserved,
  144. Pearu Peterson <pearu@cens.ioc.ee>
  145. Permission to use, modify, and distribute this software is given under the
  146. terms of the NumPy (BSD style) license. See LICENSE.txt that came with
  147. this distribution for specifics.
  148. NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
  149. """
  150. import sys
  151. import os
  152. import re
  153. import copy
  154. import warnings
  155. import subprocess
  156. import textwrap
  157. from glob import glob
  158. from functools import reduce
  159. from configparser import NoOptionError
  160. from configparser import RawConfigParser as ConfigParser
  161. # It seems that some people are importing ConfigParser from here so is
  162. # good to keep its class name. Use of RawConfigParser is needed in
  163. # order to be able to load path names with percent in them, like
  164. # `feature%2Fcool` which is common on git flow branch names.
  165. from distutils.errors import DistutilsError
  166. from distutils.dist import Distribution
  167. import sysconfig
  168. from numpy.distutils import log
  169. from distutils.util import get_platform
  170. from numpy.distutils.exec_command import (
  171. find_executable, filepath_from_subprocess_output,
  172. )
  173. from numpy.distutils.misc_util import (is_sequence, is_string,
  174. get_shared_lib_extension)
  175. from numpy.distutils.command.config import config as cmd_config
  176. from numpy.distutils import customized_ccompiler as _customized_ccompiler
  177. from numpy.distutils import _shell_utils
  178. import distutils.ccompiler
  179. import tempfile
  180. import shutil
  181. __all__ = ['system_info']
  182. # Determine number of bits
  183. import platform
  184. _bits = {'32bit': 32, '64bit': 64}
  185. platform_bits = _bits[platform.architecture()[0]]
  186. global_compiler = None
  187. def customized_ccompiler():
  188. global global_compiler
  189. if not global_compiler:
  190. global_compiler = _customized_ccompiler()
  191. return global_compiler
  192. def _c_string_literal(s):
  193. """
  194. Convert a python string into a literal suitable for inclusion into C code
  195. """
  196. # only these three characters are forbidden in C strings
  197. s = s.replace('\\', r'\\')
  198. s = s.replace('"', r'\"')
  199. s = s.replace('\n', r'\n')
  200. return '"{}"'.format(s)
  201. def libpaths(paths, bits):
  202. """Return a list of library paths valid on 32 or 64 bit systems.
  203. Inputs:
  204. paths : sequence
  205. A sequence of strings (typically paths)
  206. bits : int
  207. An integer, the only valid values are 32 or 64. A ValueError exception
  208. is raised otherwise.
  209. Examples:
  210. Consider a list of directories
  211. >>> paths = ['/usr/X11R6/lib','/usr/X11/lib','/usr/lib']
  212. For a 32-bit platform, this is already valid:
  213. >>> np.distutils.system_info.libpaths(paths,32)
  214. ['/usr/X11R6/lib', '/usr/X11/lib', '/usr/lib']
  215. On 64 bits, we prepend the '64' postfix
  216. >>> np.distutils.system_info.libpaths(paths,64)
  217. ['/usr/X11R6/lib64', '/usr/X11R6/lib', '/usr/X11/lib64', '/usr/X11/lib',
  218. '/usr/lib64', '/usr/lib']
  219. """
  220. if bits not in (32, 64):
  221. raise ValueError("Invalid bit size in libpaths: 32 or 64 only")
  222. # Handle 32bit case
  223. if bits == 32:
  224. return paths
  225. # Handle 64bit case
  226. out = []
  227. for p in paths:
  228. out.extend([p + '64', p])
  229. return out
  230. if sys.platform == 'win32':
  231. default_lib_dirs = ['C:\\',
  232. os.path.join(sysconfig.get_config_var('exec_prefix'),
  233. 'libs')]
  234. default_runtime_dirs = []
  235. default_include_dirs = []
  236. default_src_dirs = ['.']
  237. default_x11_lib_dirs = []
  238. default_x11_include_dirs = []
  239. _include_dirs = [
  240. 'include',
  241. 'include/suitesparse',
  242. ]
  243. _lib_dirs = [
  244. 'lib',
  245. ]
  246. _include_dirs = [d.replace('/', os.sep) for d in _include_dirs]
  247. _lib_dirs = [d.replace('/', os.sep) for d in _lib_dirs]
  248. def add_system_root(library_root):
  249. """Add a package manager root to the include directories"""
  250. global default_lib_dirs
  251. global default_include_dirs
  252. library_root = os.path.normpath(library_root)
  253. default_lib_dirs.extend(
  254. os.path.join(library_root, d) for d in _lib_dirs)
  255. default_include_dirs.extend(
  256. os.path.join(library_root, d) for d in _include_dirs)
  257. # VCpkg is the de-facto package manager on windows for C/C++
  258. # libraries. If it is on the PATH, then we append its paths here.
  259. vcpkg = shutil.which('vcpkg')
  260. if vcpkg:
  261. vcpkg_dir = os.path.dirname(vcpkg)
  262. if platform.architecture()[0] == '32bit':
  263. specifier = 'x86'
  264. else:
  265. specifier = 'x64'
  266. vcpkg_installed = os.path.join(vcpkg_dir, 'installed')
  267. for vcpkg_root in [
  268. os.path.join(vcpkg_installed, specifier + '-windows'),
  269. os.path.join(vcpkg_installed, specifier + '-windows-static'),
  270. ]:
  271. add_system_root(vcpkg_root)
  272. # Conda is another popular package manager that provides libraries
  273. conda = shutil.which('conda')
  274. if conda:
  275. conda_dir = os.path.dirname(conda)
  276. add_system_root(os.path.join(conda_dir, '..', 'Library'))
  277. add_system_root(os.path.join(conda_dir, 'Library'))
  278. else:
  279. default_lib_dirs = libpaths(['/usr/local/lib', '/opt/lib', '/usr/lib',
  280. '/opt/local/lib', '/sw/lib'], platform_bits)
  281. default_runtime_dirs = []
  282. default_include_dirs = ['/usr/local/include',
  283. '/opt/include',
  284. # path of umfpack under macports
  285. '/opt/local/include/ufsparse',
  286. '/opt/local/include', '/sw/include',
  287. '/usr/include/suitesparse']
  288. default_src_dirs = ['.', '/usr/local/src', '/opt/src', '/sw/src']
  289. default_x11_lib_dirs = libpaths(['/usr/X11R6/lib', '/usr/X11/lib',
  290. '/usr/lib'], platform_bits)
  291. default_x11_include_dirs = ['/usr/X11R6/include', '/usr/X11/include']
  292. if os.path.exists('/usr/lib/X11'):
  293. globbed_x11_dir = glob('/usr/lib/*/libX11.so')
  294. if globbed_x11_dir:
  295. x11_so_dir = os.path.split(globbed_x11_dir[0])[0]
  296. default_x11_lib_dirs.extend([x11_so_dir, '/usr/lib/X11'])
  297. default_x11_include_dirs.extend(['/usr/lib/X11/include',
  298. '/usr/include/X11'])
  299. with open(os.devnull, 'w') as tmp:
  300. try:
  301. p = subprocess.Popen(["gcc", "-print-multiarch"], stdout=subprocess.PIPE,
  302. stderr=tmp)
  303. except (OSError, DistutilsError):
  304. # OSError if gcc is not installed, or SandboxViolation (DistutilsError
  305. # subclass) if an old setuptools bug is triggered (see gh-3160).
  306. pass
  307. else:
  308. triplet = str(p.communicate()[0].decode().strip())
  309. if p.returncode == 0:
  310. # gcc supports the "-print-multiarch" option
  311. default_x11_lib_dirs += [os.path.join("/usr/lib/", triplet)]
  312. default_lib_dirs += [os.path.join("/usr/lib/", triplet)]
  313. if os.path.join(sys.prefix, 'lib') not in default_lib_dirs:
  314. default_lib_dirs.insert(0, os.path.join(sys.prefix, 'lib'))
  315. default_include_dirs.append(os.path.join(sys.prefix, 'include'))
  316. default_src_dirs.append(os.path.join(sys.prefix, 'src'))
  317. default_lib_dirs = [_m for _m in default_lib_dirs if os.path.isdir(_m)]
  318. default_runtime_dirs = [_m for _m in default_runtime_dirs if os.path.isdir(_m)]
  319. default_include_dirs = [_m for _m in default_include_dirs if os.path.isdir(_m)]
  320. default_src_dirs = [_m for _m in default_src_dirs if os.path.isdir(_m)]
  321. so_ext = get_shared_lib_extension()
  322. def get_standard_file(fname):
  323. """Returns a list of files named 'fname' from
  324. 1) System-wide directory (directory-location of this module)
  325. 2) Users HOME directory (os.environ['HOME'])
  326. 3) Local directory
  327. """
  328. # System-wide file
  329. filenames = []
  330. try:
  331. f = __file__
  332. except NameError:
  333. f = sys.argv[0]
  334. sysfile = os.path.join(os.path.split(os.path.abspath(f))[0],
  335. fname)
  336. if os.path.isfile(sysfile):
  337. filenames.append(sysfile)
  338. # Home directory
  339. # And look for the user config file
  340. try:
  341. f = os.path.expanduser('~')
  342. except KeyError:
  343. pass
  344. else:
  345. user_file = os.path.join(f, fname)
  346. if os.path.isfile(user_file):
  347. filenames.append(user_file)
  348. # Local file
  349. if os.path.isfile(fname):
  350. filenames.append(os.path.abspath(fname))
  351. return filenames
  352. def _parse_env_order(base_order, env):
  353. """ Parse an environment variable `env` by splitting with "," and only returning elements from `base_order`
  354. This method will sequence the environment variable and check for their
  355. individual elements in `base_order`.
  356. The items in the environment variable may be negated via '^item' or '!itema,itemb'.
  357. It must start with ^/! to negate all options.
  358. Raises
  359. ------
  360. ValueError: for mixed negated and non-negated orders or multiple negated orders
  361. Parameters
  362. ----------
  363. base_order : list of str
  364. the base list of orders
  365. env : str
  366. the environment variable to be parsed, if none is found, `base_order` is returned
  367. Returns
  368. -------
  369. allow_order : list of str
  370. allowed orders in lower-case
  371. unknown_order : list of str
  372. for values not overlapping with `base_order`
  373. """
  374. order_str = os.environ.get(env, None)
  375. # ensure all base-orders are lower-case (for easier comparison)
  376. base_order = [order.lower() for order in base_order]
  377. if order_str is None:
  378. return base_order, []
  379. neg = order_str.startswith('^') or order_str.startswith('!')
  380. # Check format
  381. order_str_l = list(order_str)
  382. sum_neg = order_str_l.count('^') + order_str_l.count('!')
  383. if neg:
  384. if sum_neg > 1:
  385. raise ValueError(f"Environment variable '{env}' may only contain a single (prefixed) negation: {order_str}")
  386. # remove prefix
  387. order_str = order_str[1:]
  388. elif sum_neg > 0:
  389. raise ValueError(f"Environment variable '{env}' may not mix negated an non-negated items: {order_str}")
  390. # Split and lower case
  391. orders = order_str.lower().split(',')
  392. # to inform callee about non-overlapping elements
  393. unknown_order = []
  394. # if negated, we have to remove from the order
  395. if neg:
  396. allow_order = base_order.copy()
  397. for order in orders:
  398. if not order:
  399. continue
  400. if order not in base_order:
  401. unknown_order.append(order)
  402. continue
  403. if order in allow_order:
  404. allow_order.remove(order)
  405. else:
  406. allow_order = []
  407. for order in orders:
  408. if not order:
  409. continue
  410. if order not in base_order:
  411. unknown_order.append(order)
  412. continue
  413. if order not in allow_order:
  414. allow_order.append(order)
  415. return allow_order, unknown_order
  416. def get_info(name, notfound_action=0):
  417. """
  418. notfound_action:
  419. 0 - do nothing
  420. 1 - display warning message
  421. 2 - raise error
  422. """
  423. cl = {'armpl': armpl_info,
  424. 'blas_armpl': blas_armpl_info,
  425. 'lapack_armpl': lapack_armpl_info,
  426. 'fftw3_armpl': fftw3_armpl_info,
  427. 'atlas': atlas_info, # use lapack_opt or blas_opt instead
  428. 'atlas_threads': atlas_threads_info, # ditto
  429. 'atlas_blas': atlas_blas_info,
  430. 'atlas_blas_threads': atlas_blas_threads_info,
  431. 'lapack_atlas': lapack_atlas_info, # use lapack_opt instead
  432. 'lapack_atlas_threads': lapack_atlas_threads_info, # ditto
  433. 'atlas_3_10': atlas_3_10_info, # use lapack_opt or blas_opt instead
  434. 'atlas_3_10_threads': atlas_3_10_threads_info, # ditto
  435. 'atlas_3_10_blas': atlas_3_10_blas_info,
  436. 'atlas_3_10_blas_threads': atlas_3_10_blas_threads_info,
  437. 'lapack_atlas_3_10': lapack_atlas_3_10_info, # use lapack_opt instead
  438. 'lapack_atlas_3_10_threads': lapack_atlas_3_10_threads_info, # ditto
  439. 'flame': flame_info, # use lapack_opt instead
  440. 'mkl': mkl_info,
  441. 'ssl2': ssl2_info,
  442. # openblas which may or may not have embedded lapack
  443. 'openblas': openblas_info, # use blas_opt instead
  444. # openblas with embedded lapack
  445. 'openblas_lapack': openblas_lapack_info, # use blas_opt instead
  446. 'openblas_clapack': openblas_clapack_info, # use blas_opt instead
  447. 'blis': blis_info, # use blas_opt instead
  448. 'lapack_mkl': lapack_mkl_info, # use lapack_opt instead
  449. 'blas_mkl': blas_mkl_info, # use blas_opt instead
  450. 'lapack_ssl2': lapack_ssl2_info,
  451. 'blas_ssl2': blas_ssl2_info,
  452. 'accelerate': accelerate_info, # use blas_opt instead
  453. 'accelerate_lapack': accelerate_lapack_info,
  454. 'openblas64_': openblas64__info,
  455. 'openblas64__lapack': openblas64__lapack_info,
  456. 'openblas_ilp64': openblas_ilp64_info,
  457. 'openblas_ilp64_lapack': openblas_ilp64_lapack_info,
  458. 'x11': x11_info,
  459. 'fft_opt': fft_opt_info,
  460. 'fftw': fftw_info,
  461. 'fftw2': fftw2_info,
  462. 'fftw3': fftw3_info,
  463. 'dfftw': dfftw_info,
  464. 'sfftw': sfftw_info,
  465. 'fftw_threads': fftw_threads_info,
  466. 'dfftw_threads': dfftw_threads_info,
  467. 'sfftw_threads': sfftw_threads_info,
  468. 'djbfft': djbfft_info,
  469. 'blas': blas_info, # use blas_opt instead
  470. 'lapack': lapack_info, # use lapack_opt instead
  471. 'lapack_src': lapack_src_info,
  472. 'blas_src': blas_src_info,
  473. 'numpy': numpy_info,
  474. 'f2py': f2py_info,
  475. 'Numeric': Numeric_info,
  476. 'numeric': Numeric_info,
  477. 'numarray': numarray_info,
  478. 'numerix': numerix_info,
  479. 'lapack_opt': lapack_opt_info,
  480. 'lapack_ilp64_opt': lapack_ilp64_opt_info,
  481. 'lapack_ilp64_plain_opt': lapack_ilp64_plain_opt_info,
  482. 'lapack64__opt': lapack64__opt_info,
  483. 'blas_opt': blas_opt_info,
  484. 'blas_ilp64_opt': blas_ilp64_opt_info,
  485. 'blas_ilp64_plain_opt': blas_ilp64_plain_opt_info,
  486. 'blas64__opt': blas64__opt_info,
  487. 'boost_python': boost_python_info,
  488. 'agg2': agg2_info,
  489. 'wx': wx_info,
  490. 'gdk_pixbuf_xlib_2': gdk_pixbuf_xlib_2_info,
  491. 'gdk-pixbuf-xlib-2.0': gdk_pixbuf_xlib_2_info,
  492. 'gdk_pixbuf_2': gdk_pixbuf_2_info,
  493. 'gdk-pixbuf-2.0': gdk_pixbuf_2_info,
  494. 'gdk': gdk_info,
  495. 'gdk_2': gdk_2_info,
  496. 'gdk-2.0': gdk_2_info,
  497. 'gdk_x11_2': gdk_x11_2_info,
  498. 'gdk-x11-2.0': gdk_x11_2_info,
  499. 'gtkp_x11_2': gtkp_x11_2_info,
  500. 'gtk+-x11-2.0': gtkp_x11_2_info,
  501. 'gtkp_2': gtkp_2_info,
  502. 'gtk+-2.0': gtkp_2_info,
  503. 'xft': xft_info,
  504. 'freetype2': freetype2_info,
  505. 'umfpack': umfpack_info,
  506. 'amd': amd_info,
  507. }.get(name.lower(), system_info)
  508. return cl().get_info(notfound_action)
  509. class NotFoundError(DistutilsError):
  510. """Some third-party program or library is not found."""
  511. class AliasedOptionError(DistutilsError):
  512. """
  513. Aliases entries in config files should not be existing.
  514. In section '{section}' we found multiple appearances of options {options}."""
  515. class AtlasNotFoundError(NotFoundError):
  516. """
  517. Atlas (http://github.com/math-atlas/math-atlas) libraries not found.
  518. Directories to search for the libraries can be specified in the
  519. numpy/distutils/site.cfg file (section [atlas]) or by setting
  520. the ATLAS environment variable."""
  521. class FlameNotFoundError(NotFoundError):
  522. """
  523. FLAME (http://www.cs.utexas.edu/~flame/web/) libraries not found.
  524. Directories to search for the libraries can be specified in the
  525. numpy/distutils/site.cfg file (section [flame])."""
  526. class LapackNotFoundError(NotFoundError):
  527. """
  528. Lapack (http://www.netlib.org/lapack/) libraries not found.
  529. Directories to search for the libraries can be specified in the
  530. numpy/distutils/site.cfg file (section [lapack]) or by setting
  531. the LAPACK environment variable."""
  532. class LapackSrcNotFoundError(LapackNotFoundError):
  533. """
  534. Lapack (http://www.netlib.org/lapack/) sources not found.
  535. Directories to search for the sources can be specified in the
  536. numpy/distutils/site.cfg file (section [lapack_src]) or by setting
  537. the LAPACK_SRC environment variable."""
  538. class LapackILP64NotFoundError(NotFoundError):
  539. """
  540. 64-bit Lapack libraries not found.
  541. Known libraries in numpy/distutils/site.cfg file are:
  542. openblas64_, openblas_ilp64
  543. """
  544. class BlasOptNotFoundError(NotFoundError):
  545. """
  546. Optimized (vendor) Blas libraries are not found.
  547. Falls back to netlib Blas library which has worse performance.
  548. A better performance should be easily gained by switching
  549. Blas library."""
  550. class BlasNotFoundError(NotFoundError):
  551. """
  552. Blas (http://www.netlib.org/blas/) libraries not found.
  553. Directories to search for the libraries can be specified in the
  554. numpy/distutils/site.cfg file (section [blas]) or by setting
  555. the BLAS environment variable."""
  556. class BlasILP64NotFoundError(NotFoundError):
  557. """
  558. 64-bit Blas libraries not found.
  559. Known libraries in numpy/distutils/site.cfg file are:
  560. openblas64_, openblas_ilp64
  561. """
  562. class BlasSrcNotFoundError(BlasNotFoundError):
  563. """
  564. Blas (http://www.netlib.org/blas/) sources not found.
  565. Directories to search for the sources can be specified in the
  566. numpy/distutils/site.cfg file (section [blas_src]) or by setting
  567. the BLAS_SRC environment variable."""
  568. class FFTWNotFoundError(NotFoundError):
  569. """
  570. FFTW (http://www.fftw.org/) libraries not found.
  571. Directories to search for the libraries can be specified in the
  572. numpy/distutils/site.cfg file (section [fftw]) or by setting
  573. the FFTW environment variable."""
  574. class DJBFFTNotFoundError(NotFoundError):
  575. """
  576. DJBFFT (https://cr.yp.to/djbfft.html) libraries not found.
  577. Directories to search for the libraries can be specified in the
  578. numpy/distutils/site.cfg file (section [djbfft]) or by setting
  579. the DJBFFT environment variable."""
  580. class NumericNotFoundError(NotFoundError):
  581. """
  582. Numeric (https://www.numpy.org/) module not found.
  583. Get it from above location, install it, and retry setup.py."""
  584. class X11NotFoundError(NotFoundError):
  585. """X11 libraries not found."""
  586. class UmfpackNotFoundError(NotFoundError):
  587. """
  588. UMFPACK sparse solver (https://www.cise.ufl.edu/research/sparse/umfpack/)
  589. not found. Directories to search for the libraries can be specified in the
  590. numpy/distutils/site.cfg file (section [umfpack]) or by setting
  591. the UMFPACK environment variable."""
  592. class system_info:
  593. """ get_info() is the only public method. Don't use others.
  594. """
  595. dir_env_var = None
  596. # XXX: search_static_first is disabled by default, may disappear in
  597. # future unless it is proved to be useful.
  598. search_static_first = 0
  599. # The base-class section name is a random word "ALL" and is not really
  600. # intended for general use. It cannot be None nor can it be DEFAULT as
  601. # these break the ConfigParser. See gh-15338
  602. section = 'ALL'
  603. saved_results = {}
  604. notfounderror = NotFoundError
  605. def __init__(self,
  606. default_lib_dirs=default_lib_dirs,
  607. default_include_dirs=default_include_dirs,
  608. ):
  609. self.__class__.info = {}
  610. self.local_prefixes = []
  611. defaults = {'library_dirs': os.pathsep.join(default_lib_dirs),
  612. 'include_dirs': os.pathsep.join(default_include_dirs),
  613. 'runtime_library_dirs': os.pathsep.join(default_runtime_dirs),
  614. 'rpath': '',
  615. 'src_dirs': os.pathsep.join(default_src_dirs),
  616. 'search_static_first': str(self.search_static_first),
  617. 'extra_compile_args': '', 'extra_link_args': ''}
  618. self.cp = ConfigParser(defaults)
  619. self.files = []
  620. self.files.extend(get_standard_file('.numpy-site.cfg'))
  621. self.files.extend(get_standard_file('site.cfg'))
  622. self.parse_config_files()
  623. if self.section is not None:
  624. self.search_static_first = self.cp.getboolean(
  625. self.section, 'search_static_first')
  626. assert isinstance(self.search_static_first, int)
  627. def parse_config_files(self):
  628. self.cp.read(self.files)
  629. if not self.cp.has_section(self.section):
  630. if self.section is not None:
  631. self.cp.add_section(self.section)
  632. def calc_libraries_info(self):
  633. libs = self.get_libraries()
  634. dirs = self.get_lib_dirs()
  635. # The extensions use runtime_library_dirs
  636. r_dirs = self.get_runtime_lib_dirs()
  637. # Intrinsic distutils use rpath, we simply append both entries
  638. # as though they were one entry
  639. r_dirs.extend(self.get_runtime_lib_dirs(key='rpath'))
  640. info = {}
  641. for lib in libs:
  642. i = self.check_libs(dirs, [lib])
  643. if i is not None:
  644. dict_append(info, **i)
  645. else:
  646. log.info('Library %s was not found. Ignoring' % (lib))
  647. if r_dirs:
  648. i = self.check_libs(r_dirs, [lib])
  649. if i is not None:
  650. # Swap library keywords found to runtime_library_dirs
  651. # the libraries are insisting on the user having defined
  652. # them using the library_dirs, and not necessarily by
  653. # runtime_library_dirs
  654. del i['libraries']
  655. i['runtime_library_dirs'] = i.pop('library_dirs')
  656. dict_append(info, **i)
  657. else:
  658. log.info('Runtime library %s was not found. Ignoring' % (lib))
  659. return info
  660. def set_info(self, **info):
  661. if info:
  662. lib_info = self.calc_libraries_info()
  663. dict_append(info, **lib_info)
  664. # Update extra information
  665. extra_info = self.calc_extra_info()
  666. dict_append(info, **extra_info)
  667. self.saved_results[self.__class__.__name__] = info
  668. def get_option_single(self, *options):
  669. """ Ensure that only one of `options` are found in the section
  670. Parameters
  671. ----------
  672. *options : list of str
  673. a list of options to be found in the section (``self.section``)
  674. Returns
  675. -------
  676. str :
  677. the option that is uniquely found in the section
  678. Raises
  679. ------
  680. AliasedOptionError :
  681. in case more than one of the options are found
  682. """
  683. found = [self.cp.has_option(self.section, opt) for opt in options]
  684. if sum(found) == 1:
  685. return options[found.index(True)]
  686. elif sum(found) == 0:
  687. # nothing is found anyways
  688. return options[0]
  689. # Else we have more than 1 key found
  690. if AliasedOptionError.__doc__ is None:
  691. raise AliasedOptionError()
  692. raise AliasedOptionError(AliasedOptionError.__doc__.format(
  693. section=self.section, options='[{}]'.format(', '.join(options))))
  694. def has_info(self):
  695. return self.__class__.__name__ in self.saved_results
  696. def calc_extra_info(self):
  697. """ Updates the information in the current information with
  698. respect to these flags:
  699. extra_compile_args
  700. extra_link_args
  701. """
  702. info = {}
  703. for key in ['extra_compile_args', 'extra_link_args']:
  704. # Get values
  705. opt = self.cp.get(self.section, key)
  706. opt = _shell_utils.NativeParser.split(opt)
  707. if opt:
  708. tmp = {key: opt}
  709. dict_append(info, **tmp)
  710. return info
  711. def get_info(self, notfound_action=0):
  712. """ Return a dictionary with items that are compatible
  713. with numpy.distutils.setup keyword arguments.
  714. """
  715. flag = 0
  716. if not self.has_info():
  717. flag = 1
  718. log.info(self.__class__.__name__ + ':')
  719. if hasattr(self, 'calc_info'):
  720. self.calc_info()
  721. if notfound_action:
  722. if not self.has_info():
  723. if notfound_action == 1:
  724. warnings.warn(self.notfounderror.__doc__, stacklevel=2)
  725. elif notfound_action == 2:
  726. raise self.notfounderror(self.notfounderror.__doc__)
  727. else:
  728. raise ValueError(repr(notfound_action))
  729. if not self.has_info():
  730. log.info(' NOT AVAILABLE')
  731. self.set_info()
  732. else:
  733. log.info(' FOUND:')
  734. res = self.saved_results.get(self.__class__.__name__)
  735. if log.get_threshold() <= log.INFO and flag:
  736. for k, v in res.items():
  737. v = str(v)
  738. if k in ['sources', 'libraries'] and len(v) > 270:
  739. v = v[:120] + '...\n...\n...' + v[-120:]
  740. log.info(' %s = %s', k, v)
  741. log.info('')
  742. return copy.deepcopy(res)
  743. def get_paths(self, section, key):
  744. dirs = self.cp.get(section, key).split(os.pathsep)
  745. env_var = self.dir_env_var
  746. if env_var:
  747. if is_sequence(env_var):
  748. e0 = env_var[-1]
  749. for e in env_var:
  750. if e in os.environ:
  751. e0 = e
  752. break
  753. if not env_var[0] == e0:
  754. log.info('Setting %s=%s' % (env_var[0], e0))
  755. env_var = e0
  756. if env_var and env_var in os.environ:
  757. d = os.environ[env_var]
  758. if d == 'None':
  759. log.info('Disabled %s: %s',
  760. self.__class__.__name__, '(%s is None)'
  761. % (env_var,))
  762. return []
  763. if os.path.isfile(d):
  764. dirs = [os.path.dirname(d)] + dirs
  765. l = getattr(self, '_lib_names', [])
  766. if len(l) == 1:
  767. b = os.path.basename(d)
  768. b = os.path.splitext(b)[0]
  769. if b[:3] == 'lib':
  770. log.info('Replacing _lib_names[0]==%r with %r' \
  771. % (self._lib_names[0], b[3:]))
  772. self._lib_names[0] = b[3:]
  773. else:
  774. ds = d.split(os.pathsep)
  775. ds2 = []
  776. for d in ds:
  777. if os.path.isdir(d):
  778. ds2.append(d)
  779. for dd in ['include', 'lib']:
  780. d1 = os.path.join(d, dd)
  781. if os.path.isdir(d1):
  782. ds2.append(d1)
  783. dirs = ds2 + dirs
  784. default_dirs = self.cp.get(self.section, key).split(os.pathsep)
  785. dirs.extend(default_dirs)
  786. ret = []
  787. for d in dirs:
  788. if len(d) > 0 and not os.path.isdir(d):
  789. warnings.warn('Specified path %s is invalid.' % d, stacklevel=2)
  790. continue
  791. if d not in ret:
  792. ret.append(d)
  793. log.debug('( %s = %s )', key, ':'.join(ret))
  794. return ret
  795. def get_lib_dirs(self, key='library_dirs'):
  796. return self.get_paths(self.section, key)
  797. def get_runtime_lib_dirs(self, key='runtime_library_dirs'):
  798. path = self.get_paths(self.section, key)
  799. if path == ['']:
  800. path = []
  801. return path
  802. def get_include_dirs(self, key='include_dirs'):
  803. return self.get_paths(self.section, key)
  804. def get_src_dirs(self, key='src_dirs'):
  805. return self.get_paths(self.section, key)
  806. def get_libs(self, key, default):
  807. try:
  808. libs = self.cp.get(self.section, key)
  809. except NoOptionError:
  810. if not default:
  811. return []
  812. if is_string(default):
  813. return [default]
  814. return default
  815. return [b for b in [a.strip() for a in libs.split(',')] if b]
  816. def get_libraries(self, key='libraries'):
  817. if hasattr(self, '_lib_names'):
  818. return self.get_libs(key, default=self._lib_names)
  819. else:
  820. return self.get_libs(key, '')
  821. def library_extensions(self):
  822. c = customized_ccompiler()
  823. static_exts = []
  824. if c.compiler_type != 'msvc':
  825. # MSVC doesn't understand binutils
  826. static_exts.append('.a')
  827. if sys.platform == 'win32':
  828. static_exts.append('.lib') # .lib is used by MSVC and others
  829. if self.search_static_first:
  830. exts = static_exts + [so_ext]
  831. else:
  832. exts = [so_ext] + static_exts
  833. if sys.platform == 'cygwin':
  834. exts.append('.dll.a')
  835. if sys.platform == 'darwin':
  836. exts.append('.dylib')
  837. return exts
  838. def check_libs(self, lib_dirs, libs, opt_libs=[]):
  839. """If static or shared libraries are available then return
  840. their info dictionary.
  841. Checks for all libraries as shared libraries first, then
  842. static (or vice versa if self.search_static_first is True).
  843. """
  844. exts = self.library_extensions()
  845. info = None
  846. for ext in exts:
  847. info = self._check_libs(lib_dirs, libs, opt_libs, [ext])
  848. if info is not None:
  849. break
  850. if not info:
  851. log.info(' libraries %s not found in %s', ','.join(libs),
  852. lib_dirs)
  853. return info
  854. def check_libs2(self, lib_dirs, libs, opt_libs=[]):
  855. """If static or shared libraries are available then return
  856. their info dictionary.
  857. Checks each library for shared or static.
  858. """
  859. exts = self.library_extensions()
  860. info = self._check_libs(lib_dirs, libs, opt_libs, exts)
  861. if not info:
  862. log.info(' libraries %s not found in %s', ','.join(libs),
  863. lib_dirs)
  864. return info
  865. def _find_lib(self, lib_dir, lib, exts):
  866. assert is_string(lib_dir)
  867. # under windows first try without 'lib' prefix
  868. if sys.platform == 'win32':
  869. lib_prefixes = ['', 'lib']
  870. else:
  871. lib_prefixes = ['lib']
  872. # for each library name, see if we can find a file for it.
  873. for ext in exts:
  874. for prefix in lib_prefixes:
  875. p = self.combine_paths(lib_dir, prefix + lib + ext)
  876. if p:
  877. break
  878. if p:
  879. assert len(p) == 1
  880. # ??? splitext on p[0] would do this for cygwin
  881. # doesn't seem correct
  882. if ext == '.dll.a':
  883. lib += '.dll'
  884. if ext == '.lib':
  885. lib = prefix + lib
  886. return lib
  887. return False
  888. def _find_libs(self, lib_dirs, libs, exts):
  889. # make sure we preserve the order of libs, as it can be important
  890. found_dirs, found_libs = [], []
  891. for lib in libs:
  892. for lib_dir in lib_dirs:
  893. found_lib = self._find_lib(lib_dir, lib, exts)
  894. if found_lib:
  895. found_libs.append(found_lib)
  896. if lib_dir not in found_dirs:
  897. found_dirs.append(lib_dir)
  898. break
  899. return found_dirs, found_libs
  900. def _check_libs(self, lib_dirs, libs, opt_libs, exts):
  901. """Find mandatory and optional libs in expected paths.
  902. Missing optional libraries are silently forgotten.
  903. """
  904. if not is_sequence(lib_dirs):
  905. lib_dirs = [lib_dirs]
  906. # First, try to find the mandatory libraries
  907. found_dirs, found_libs = self._find_libs(lib_dirs, libs, exts)
  908. if len(found_libs) > 0 and len(found_libs) == len(libs):
  909. # Now, check for optional libraries
  910. opt_found_dirs, opt_found_libs = self._find_libs(lib_dirs, opt_libs, exts)
  911. found_libs.extend(opt_found_libs)
  912. for lib_dir in opt_found_dirs:
  913. if lib_dir not in found_dirs:
  914. found_dirs.append(lib_dir)
  915. info = {'libraries': found_libs, 'library_dirs': found_dirs}
  916. return info
  917. else:
  918. return None
  919. def combine_paths(self, *args):
  920. """Return a list of existing paths composed by all combinations
  921. of items from the arguments.
  922. """
  923. return combine_paths(*args)
  924. class fft_opt_info(system_info):
  925. def calc_info(self):
  926. info = {}
  927. fftw_info = get_info('fftw3') or get_info('fftw2') or get_info('dfftw')
  928. djbfft_info = get_info('djbfft')
  929. if fftw_info:
  930. dict_append(info, **fftw_info)
  931. if djbfft_info:
  932. dict_append(info, **djbfft_info)
  933. self.set_info(**info)
  934. return
  935. class fftw_info(system_info):
  936. #variables to override
  937. section = 'fftw'
  938. dir_env_var = 'FFTW'
  939. notfounderror = FFTWNotFoundError
  940. ver_info = [{'name':'fftw3',
  941. 'libs':['fftw3'],
  942. 'includes':['fftw3.h'],
  943. 'macros':[('SCIPY_FFTW3_H', None)]},
  944. {'name':'fftw2',
  945. 'libs':['rfftw', 'fftw'],
  946. 'includes':['fftw.h', 'rfftw.h'],
  947. 'macros':[('SCIPY_FFTW_H', None)]}]
  948. def calc_ver_info(self, ver_param):
  949. """Returns True on successful version detection, else False"""
  950. lib_dirs = self.get_lib_dirs()
  951. incl_dirs = self.get_include_dirs()
  952. opt = self.get_option_single(self.section + '_libs', 'libraries')
  953. libs = self.get_libs(opt, ver_param['libs'])
  954. info = self.check_libs(lib_dirs, libs)
  955. if info is not None:
  956. flag = 0
  957. for d in incl_dirs:
  958. if len(self.combine_paths(d, ver_param['includes'])) \
  959. == len(ver_param['includes']):
  960. dict_append(info, include_dirs=[d])
  961. flag = 1
  962. break
  963. if flag:
  964. dict_append(info, define_macros=ver_param['macros'])
  965. else:
  966. info = None
  967. if info is not None:
  968. self.set_info(**info)
  969. return True
  970. else:
  971. log.info(' %s not found' % (ver_param['name']))
  972. return False
  973. def calc_info(self):
  974. for i in self.ver_info:
  975. if self.calc_ver_info(i):
  976. break
  977. class fftw2_info(fftw_info):
  978. #variables to override
  979. section = 'fftw'
  980. dir_env_var = 'FFTW'
  981. notfounderror = FFTWNotFoundError
  982. ver_info = [{'name':'fftw2',
  983. 'libs':['rfftw', 'fftw'],
  984. 'includes':['fftw.h', 'rfftw.h'],
  985. 'macros':[('SCIPY_FFTW_H', None)]}
  986. ]
  987. class fftw3_info(fftw_info):
  988. #variables to override
  989. section = 'fftw3'
  990. dir_env_var = 'FFTW3'
  991. notfounderror = FFTWNotFoundError
  992. ver_info = [{'name':'fftw3',
  993. 'libs':['fftw3'],
  994. 'includes':['fftw3.h'],
  995. 'macros':[('SCIPY_FFTW3_H', None)]},
  996. ]
  997. class fftw3_armpl_info(fftw_info):
  998. section = 'fftw3'
  999. dir_env_var = 'ARMPL_DIR'
  1000. notfounderror = FFTWNotFoundError
  1001. ver_info = [{'name': 'fftw3',
  1002. 'libs': ['armpl_lp64_mp'],
  1003. 'includes': ['fftw3.h'],
  1004. 'macros': [('SCIPY_FFTW3_H', None)]}]
  1005. class dfftw_info(fftw_info):
  1006. section = 'fftw'
  1007. dir_env_var = 'FFTW'
  1008. ver_info = [{'name':'dfftw',
  1009. 'libs':['drfftw', 'dfftw'],
  1010. 'includes':['dfftw.h', 'drfftw.h'],
  1011. 'macros':[('SCIPY_DFFTW_H', None)]}]
  1012. class sfftw_info(fftw_info):
  1013. section = 'fftw'
  1014. dir_env_var = 'FFTW'
  1015. ver_info = [{'name':'sfftw',
  1016. 'libs':['srfftw', 'sfftw'],
  1017. 'includes':['sfftw.h', 'srfftw.h'],
  1018. 'macros':[('SCIPY_SFFTW_H', None)]}]
  1019. class fftw_threads_info(fftw_info):
  1020. section = 'fftw'
  1021. dir_env_var = 'FFTW'
  1022. ver_info = [{'name':'fftw threads',
  1023. 'libs':['rfftw_threads', 'fftw_threads'],
  1024. 'includes':['fftw_threads.h', 'rfftw_threads.h'],
  1025. 'macros':[('SCIPY_FFTW_THREADS_H', None)]}]
  1026. class dfftw_threads_info(fftw_info):
  1027. section = 'fftw'
  1028. dir_env_var = 'FFTW'
  1029. ver_info = [{'name':'dfftw threads',
  1030. 'libs':['drfftw_threads', 'dfftw_threads'],
  1031. 'includes':['dfftw_threads.h', 'drfftw_threads.h'],
  1032. 'macros':[('SCIPY_DFFTW_THREADS_H', None)]}]
  1033. class sfftw_threads_info(fftw_info):
  1034. section = 'fftw'
  1035. dir_env_var = 'FFTW'
  1036. ver_info = [{'name':'sfftw threads',
  1037. 'libs':['srfftw_threads', 'sfftw_threads'],
  1038. 'includes':['sfftw_threads.h', 'srfftw_threads.h'],
  1039. 'macros':[('SCIPY_SFFTW_THREADS_H', None)]}]
  1040. class djbfft_info(system_info):
  1041. section = 'djbfft'
  1042. dir_env_var = 'DJBFFT'
  1043. notfounderror = DJBFFTNotFoundError
  1044. def get_paths(self, section, key):
  1045. pre_dirs = system_info.get_paths(self, section, key)
  1046. dirs = []
  1047. for d in pre_dirs:
  1048. dirs.extend(self.combine_paths(d, ['djbfft']) + [d])
  1049. return [d for d in dirs if os.path.isdir(d)]
  1050. def calc_info(self):
  1051. lib_dirs = self.get_lib_dirs()
  1052. incl_dirs = self.get_include_dirs()
  1053. info = None
  1054. for d in lib_dirs:
  1055. p = self.combine_paths(d, ['djbfft.a'])
  1056. if p:
  1057. info = {'extra_objects': p}
  1058. break
  1059. p = self.combine_paths(d, ['libdjbfft.a', 'libdjbfft' + so_ext])
  1060. if p:
  1061. info = {'libraries': ['djbfft'], 'library_dirs': [d]}
  1062. break
  1063. if info is None:
  1064. return
  1065. for d in incl_dirs:
  1066. if len(self.combine_paths(d, ['fftc8.h', 'fftfreq.h'])) == 2:
  1067. dict_append(info, include_dirs=[d],
  1068. define_macros=[('SCIPY_DJBFFT_H', None)])
  1069. self.set_info(**info)
  1070. return
  1071. return
  1072. class mkl_info(system_info):
  1073. section = 'mkl'
  1074. dir_env_var = 'MKLROOT'
  1075. _lib_mkl = ['mkl_rt']
  1076. def get_mkl_rootdir(self):
  1077. mklroot = os.environ.get('MKLROOT', None)
  1078. if mklroot is not None:
  1079. return mklroot
  1080. paths = os.environ.get('LD_LIBRARY_PATH', '').split(os.pathsep)
  1081. ld_so_conf = '/etc/ld.so.conf'
  1082. if os.path.isfile(ld_so_conf):
  1083. with open(ld_so_conf) as f:
  1084. for d in f:
  1085. d = d.strip()
  1086. if d:
  1087. paths.append(d)
  1088. intel_mkl_dirs = []
  1089. for path in paths:
  1090. path_atoms = path.split(os.sep)
  1091. for m in path_atoms:
  1092. if m.startswith('mkl'):
  1093. d = os.sep.join(path_atoms[:path_atoms.index(m) + 2])
  1094. intel_mkl_dirs.append(d)
  1095. break
  1096. for d in paths:
  1097. dirs = glob(os.path.join(d, 'mkl', '*'))
  1098. dirs += glob(os.path.join(d, 'mkl*'))
  1099. for sub_dir in dirs:
  1100. if os.path.isdir(os.path.join(sub_dir, 'lib')):
  1101. return sub_dir
  1102. return None
  1103. def __init__(self):
  1104. mklroot = self.get_mkl_rootdir()
  1105. if mklroot is None:
  1106. system_info.__init__(self)
  1107. else:
  1108. from .cpuinfo import cpu
  1109. if cpu.is_Itanium():
  1110. plt = '64'
  1111. elif cpu.is_Intel() and cpu.is_64bit():
  1112. plt = 'intel64'
  1113. else:
  1114. plt = '32'
  1115. system_info.__init__(
  1116. self,
  1117. default_lib_dirs=[os.path.join(mklroot, 'lib', plt)],
  1118. default_include_dirs=[os.path.join(mklroot, 'include')])
  1119. def calc_info(self):
  1120. lib_dirs = self.get_lib_dirs()
  1121. incl_dirs = self.get_include_dirs()
  1122. opt = self.get_option_single('mkl_libs', 'libraries')
  1123. mkl_libs = self.get_libs(opt, self._lib_mkl)
  1124. info = self.check_libs2(lib_dirs, mkl_libs)
  1125. if info is None:
  1126. return
  1127. dict_append(info,
  1128. define_macros=[('SCIPY_MKL_H', None),
  1129. ('HAVE_CBLAS', None)],
  1130. include_dirs=incl_dirs)
  1131. if sys.platform == 'win32':
  1132. pass # win32 has no pthread library
  1133. else:
  1134. dict_append(info, libraries=['pthread'])
  1135. self.set_info(**info)
  1136. class lapack_mkl_info(mkl_info):
  1137. pass
  1138. class blas_mkl_info(mkl_info):
  1139. pass
  1140. class ssl2_info(system_info):
  1141. section = 'ssl2'
  1142. dir_env_var = 'SSL2_DIR'
  1143. # Multi-threaded version. Python itself must be built by Fujitsu compiler.
  1144. _lib_ssl2 = ['fjlapackexsve']
  1145. # Single-threaded version
  1146. #_lib_ssl2 = ['fjlapacksve']
  1147. def get_tcsds_rootdir(self):
  1148. tcsdsroot = os.environ.get('TCSDS_PATH', None)
  1149. if tcsdsroot is not None:
  1150. return tcsdsroot
  1151. return None
  1152. def __init__(self):
  1153. tcsdsroot = self.get_tcsds_rootdir()
  1154. if tcsdsroot is None:
  1155. system_info.__init__(self)
  1156. else:
  1157. system_info.__init__(
  1158. self,
  1159. default_lib_dirs=[os.path.join(tcsdsroot, 'lib64')],
  1160. default_include_dirs=[os.path.join(tcsdsroot,
  1161. 'clang-comp/include')])
  1162. def calc_info(self):
  1163. tcsdsroot = self.get_tcsds_rootdir()
  1164. lib_dirs = self.get_lib_dirs()
  1165. if lib_dirs is None:
  1166. lib_dirs = os.path.join(tcsdsroot, 'lib64')
  1167. incl_dirs = self.get_include_dirs()
  1168. if incl_dirs is None:
  1169. incl_dirs = os.path.join(tcsdsroot, 'clang-comp/include')
  1170. ssl2_libs = self.get_libs('ssl2_libs', self._lib_ssl2)
  1171. info = self.check_libs2(lib_dirs, ssl2_libs)
  1172. if info is None:
  1173. return
  1174. dict_append(info,
  1175. define_macros=[('HAVE_CBLAS', None),
  1176. ('HAVE_SSL2', 1)],
  1177. include_dirs=incl_dirs,)
  1178. self.set_info(**info)
  1179. class lapack_ssl2_info(ssl2_info):
  1180. pass
  1181. class blas_ssl2_info(ssl2_info):
  1182. pass
  1183. class armpl_info(system_info):
  1184. section = 'armpl'
  1185. dir_env_var = 'ARMPL_DIR'
  1186. _lib_armpl = ['armpl_lp64_mp']
  1187. def calc_info(self):
  1188. lib_dirs = self.get_lib_dirs()
  1189. incl_dirs = self.get_include_dirs()
  1190. armpl_libs = self.get_libs('armpl_libs', self._lib_armpl)
  1191. info = self.check_libs2(lib_dirs, armpl_libs)
  1192. if info is None:
  1193. return
  1194. dict_append(info,
  1195. define_macros=[('SCIPY_MKL_H', None),
  1196. ('HAVE_CBLAS', None)],
  1197. include_dirs=incl_dirs)
  1198. self.set_info(**info)
  1199. class lapack_armpl_info(armpl_info):
  1200. pass
  1201. class blas_armpl_info(armpl_info):
  1202. pass
  1203. class atlas_info(system_info):
  1204. section = 'atlas'
  1205. dir_env_var = 'ATLAS'
  1206. _lib_names = ['f77blas', 'cblas']
  1207. if sys.platform[:7] == 'freebsd':
  1208. _lib_atlas = ['atlas_r']
  1209. _lib_lapack = ['alapack_r']
  1210. else:
  1211. _lib_atlas = ['atlas']
  1212. _lib_lapack = ['lapack']
  1213. notfounderror = AtlasNotFoundError
  1214. def get_paths(self, section, key):
  1215. pre_dirs = system_info.get_paths(self, section, key)
  1216. dirs = []
  1217. for d in pre_dirs:
  1218. dirs.extend(self.combine_paths(d, ['atlas*', 'ATLAS*',
  1219. 'sse', '3dnow', 'sse2']) + [d])
  1220. return [d for d in dirs if os.path.isdir(d)]
  1221. def calc_info(self):
  1222. lib_dirs = self.get_lib_dirs()
  1223. info = {}
  1224. opt = self.get_option_single('atlas_libs', 'libraries')
  1225. atlas_libs = self.get_libs(opt, self._lib_names + self._lib_atlas)
  1226. lapack_libs = self.get_libs('lapack_libs', self._lib_lapack)
  1227. atlas = None
  1228. lapack = None
  1229. atlas_1 = None
  1230. for d in lib_dirs:
  1231. atlas = self.check_libs2(d, atlas_libs, [])
  1232. if atlas is not None:
  1233. lib_dirs2 = [d] + self.combine_paths(d, ['atlas*', 'ATLAS*'])
  1234. lapack = self.check_libs2(lib_dirs2, lapack_libs, [])
  1235. if lapack is not None:
  1236. break
  1237. if atlas:
  1238. atlas_1 = atlas
  1239. log.info(self.__class__)
  1240. if atlas is None:
  1241. atlas = atlas_1
  1242. if atlas is None:
  1243. return
  1244. include_dirs = self.get_include_dirs()
  1245. h = (self.combine_paths(lib_dirs + include_dirs, 'cblas.h') or [None])
  1246. h = h[0]
  1247. if h:
  1248. h = os.path.dirname(h)
  1249. dict_append(info, include_dirs=[h])
  1250. info['language'] = 'c'
  1251. if lapack is not None:
  1252. dict_append(info, **lapack)
  1253. dict_append(info, **atlas)
  1254. elif 'lapack_atlas' in atlas['libraries']:
  1255. dict_append(info, **atlas)
  1256. dict_append(info,
  1257. define_macros=[('ATLAS_WITH_LAPACK_ATLAS', None)])
  1258. self.set_info(**info)
  1259. return
  1260. else:
  1261. dict_append(info, **atlas)
  1262. dict_append(info, define_macros=[('ATLAS_WITHOUT_LAPACK', None)])
  1263. message = textwrap.dedent("""
  1264. *********************************************************************
  1265. Could not find lapack library within the ATLAS installation.
  1266. *********************************************************************
  1267. """)
  1268. warnings.warn(message, stacklevel=2)
  1269. self.set_info(**info)
  1270. return
  1271. # Check if lapack library is complete, only warn if it is not.
  1272. lapack_dir = lapack['library_dirs'][0]
  1273. lapack_name = lapack['libraries'][0]
  1274. lapack_lib = None
  1275. lib_prefixes = ['lib']
  1276. if sys.platform == 'win32':
  1277. lib_prefixes.append('')
  1278. for e in self.library_extensions():
  1279. for prefix in lib_prefixes:
  1280. fn = os.path.join(lapack_dir, prefix + lapack_name + e)
  1281. if os.path.exists(fn):
  1282. lapack_lib = fn
  1283. break
  1284. if lapack_lib:
  1285. break
  1286. if lapack_lib is not None:
  1287. sz = os.stat(lapack_lib)[6]
  1288. if sz <= 4000 * 1024:
  1289. message = textwrap.dedent("""
  1290. *********************************************************************
  1291. Lapack library (from ATLAS) is probably incomplete:
  1292. size of %s is %sk (expected >4000k)
  1293. Follow the instructions in the KNOWN PROBLEMS section of the file
  1294. numpy/INSTALL.txt.
  1295. *********************************************************************
  1296. """) % (lapack_lib, sz / 1024)
  1297. warnings.warn(message, stacklevel=2)
  1298. else:
  1299. info['language'] = 'f77'
  1300. atlas_version, atlas_extra_info = get_atlas_version(**atlas)
  1301. dict_append(info, **atlas_extra_info)
  1302. self.set_info(**info)
  1303. class atlas_blas_info(atlas_info):
  1304. _lib_names = ['f77blas', 'cblas']
  1305. def calc_info(self):
  1306. lib_dirs = self.get_lib_dirs()
  1307. info = {}
  1308. opt = self.get_option_single('atlas_libs', 'libraries')
  1309. atlas_libs = self.get_libs(opt, self._lib_names + self._lib_atlas)
  1310. atlas = self.check_libs2(lib_dirs, atlas_libs, [])
  1311. if atlas is None:
  1312. return
  1313. include_dirs = self.get_include_dirs()
  1314. h = (self.combine_paths(lib_dirs + include_dirs, 'cblas.h') or [None])
  1315. h = h[0]
  1316. if h:
  1317. h = os.path.dirname(h)
  1318. dict_append(info, include_dirs=[h])
  1319. info['language'] = 'c'
  1320. info['define_macros'] = [('HAVE_CBLAS', None)]
  1321. atlas_version, atlas_extra_info = get_atlas_version(**atlas)
  1322. dict_append(atlas, **atlas_extra_info)
  1323. dict_append(info, **atlas)
  1324. self.set_info(**info)
  1325. return
  1326. class atlas_threads_info(atlas_info):
  1327. dir_env_var = ['PTATLAS', 'ATLAS']
  1328. _lib_names = ['ptf77blas', 'ptcblas']
  1329. class atlas_blas_threads_info(atlas_blas_info):
  1330. dir_env_var = ['PTATLAS', 'ATLAS']
  1331. _lib_names = ['ptf77blas', 'ptcblas']
  1332. class lapack_atlas_info(atlas_info):
  1333. _lib_names = ['lapack_atlas'] + atlas_info._lib_names
  1334. class lapack_atlas_threads_info(atlas_threads_info):
  1335. _lib_names = ['lapack_atlas'] + atlas_threads_info._lib_names
  1336. class atlas_3_10_info(atlas_info):
  1337. _lib_names = ['satlas']
  1338. _lib_atlas = _lib_names
  1339. _lib_lapack = _lib_names
  1340. class atlas_3_10_blas_info(atlas_3_10_info):
  1341. _lib_names = ['satlas']
  1342. def calc_info(self):
  1343. lib_dirs = self.get_lib_dirs()
  1344. info = {}
  1345. opt = self.get_option_single('atlas_lib', 'libraries')
  1346. atlas_libs = self.get_libs(opt, self._lib_names)
  1347. atlas = self.check_libs2(lib_dirs, atlas_libs, [])
  1348. if atlas is None:
  1349. return
  1350. include_dirs = self.get_include_dirs()
  1351. h = (self.combine_paths(lib_dirs + include_dirs, 'cblas.h') or [None])
  1352. h = h[0]
  1353. if h:
  1354. h = os.path.dirname(h)
  1355. dict_append(info, include_dirs=[h])
  1356. info['language'] = 'c'
  1357. info['define_macros'] = [('HAVE_CBLAS', None)]
  1358. atlas_version, atlas_extra_info = get_atlas_version(**atlas)
  1359. dict_append(atlas, **atlas_extra_info)
  1360. dict_append(info, **atlas)
  1361. self.set_info(**info)
  1362. return
  1363. class atlas_3_10_threads_info(atlas_3_10_info):
  1364. dir_env_var = ['PTATLAS', 'ATLAS']
  1365. _lib_names = ['tatlas']
  1366. _lib_atlas = _lib_names
  1367. _lib_lapack = _lib_names
  1368. class atlas_3_10_blas_threads_info(atlas_3_10_blas_info):
  1369. dir_env_var = ['PTATLAS', 'ATLAS']
  1370. _lib_names = ['tatlas']
  1371. class lapack_atlas_3_10_info(atlas_3_10_info):
  1372. pass
  1373. class lapack_atlas_3_10_threads_info(atlas_3_10_threads_info):
  1374. pass
  1375. class lapack_info(system_info):
  1376. section = 'lapack'
  1377. dir_env_var = 'LAPACK'
  1378. _lib_names = ['lapack']
  1379. notfounderror = LapackNotFoundError
  1380. def calc_info(self):
  1381. lib_dirs = self.get_lib_dirs()
  1382. opt = self.get_option_single('lapack_libs', 'libraries')
  1383. lapack_libs = self.get_libs(opt, self._lib_names)
  1384. info = self.check_libs(lib_dirs, lapack_libs, [])
  1385. if info is None:
  1386. return
  1387. info['language'] = 'f77'
  1388. self.set_info(**info)
  1389. class lapack_src_info(system_info):
  1390. # LAPACK_SRC is deprecated, please do not use this!
  1391. # Build or install a BLAS library via your package manager or from
  1392. # source separately.
  1393. section = 'lapack_src'
  1394. dir_env_var = 'LAPACK_SRC'
  1395. notfounderror = LapackSrcNotFoundError
  1396. def get_paths(self, section, key):
  1397. pre_dirs = system_info.get_paths(self, section, key)
  1398. dirs = []
  1399. for d in pre_dirs:
  1400. dirs.extend([d] + self.combine_paths(d, ['LAPACK*/SRC', 'SRC']))
  1401. return [d for d in dirs if os.path.isdir(d)]
  1402. def calc_info(self):
  1403. src_dirs = self.get_src_dirs()
  1404. src_dir = ''
  1405. for d in src_dirs:
  1406. if os.path.isfile(os.path.join(d, 'dgesv.f')):
  1407. src_dir = d
  1408. break
  1409. if not src_dir:
  1410. #XXX: Get sources from netlib. May be ask first.
  1411. return
  1412. # The following is extracted from LAPACK-3.0/SRC/Makefile.
  1413. # Added missing names from lapack-lite-3.1.1/SRC/Makefile
  1414. # while keeping removed names for Lapack-3.0 compatibility.
  1415. allaux = '''
  1416. ilaenv ieeeck lsame lsamen xerbla
  1417. iparmq
  1418. ''' # *.f
  1419. laux = '''
  1420. bdsdc bdsqr disna labad lacpy ladiv lae2 laebz laed0 laed1
  1421. laed2 laed3 laed4 laed5 laed6 laed7 laed8 laed9 laeda laev2
  1422. lagtf lagts lamch lamrg lanst lapy2 lapy3 larnv larrb larre
  1423. larrf lartg laruv las2 lascl lasd0 lasd1 lasd2 lasd3 lasd4
  1424. lasd5 lasd6 lasd7 lasd8 lasd9 lasda lasdq lasdt laset lasq1
  1425. lasq2 lasq3 lasq4 lasq5 lasq6 lasr lasrt lassq lasv2 pttrf
  1426. stebz stedc steqr sterf
  1427. larra larrc larrd larr larrk larrj larrr laneg laisnan isnan
  1428. lazq3 lazq4
  1429. ''' # [s|d]*.f
  1430. lasrc = '''
  1431. gbbrd gbcon gbequ gbrfs gbsv gbsvx gbtf2 gbtrf gbtrs gebak
  1432. gebal gebd2 gebrd gecon geequ gees geesx geev geevx gegs gegv
  1433. gehd2 gehrd gelq2 gelqf gels gelsd gelss gelsx gelsy geql2
  1434. geqlf geqp3 geqpf geqr2 geqrf gerfs gerq2 gerqf gesc2 gesdd
  1435. gesv gesvd gesvx getc2 getf2 getrf getri getrs ggbak ggbal
  1436. gges ggesx ggev ggevx ggglm gghrd gglse ggqrf ggrqf ggsvd
  1437. ggsvp gtcon gtrfs gtsv gtsvx gttrf gttrs gtts2 hgeqz hsein
  1438. hseqr labrd lacon laein lags2 lagtm lahqr lahrd laic1 lals0
  1439. lalsa lalsd langb lange langt lanhs lansb lansp lansy lantb
  1440. lantp lantr lapll lapmt laqgb laqge laqp2 laqps laqsb laqsp
  1441. laqsy lar1v lar2v larf larfb larfg larft larfx largv larrv
  1442. lartv larz larzb larzt laswp lasyf latbs latdf latps latrd
  1443. latrs latrz latzm lauu2 lauum pbcon pbequ pbrfs pbstf pbsv
  1444. pbsvx pbtf2 pbtrf pbtrs pocon poequ porfs posv posvx potf2
  1445. potrf potri potrs ppcon ppequ pprfs ppsv ppsvx pptrf pptri
  1446. pptrs ptcon pteqr ptrfs ptsv ptsvx pttrs ptts2 spcon sprfs
  1447. spsv spsvx sptrf sptri sptrs stegr stein sycon syrfs sysv
  1448. sysvx sytf2 sytrf sytri sytrs tbcon tbrfs tbtrs tgevc tgex2
  1449. tgexc tgsen tgsja tgsna tgsy2 tgsyl tpcon tprfs tptri tptrs
  1450. trcon trevc trexc trrfs trsen trsna trsyl trti2 trtri trtrs
  1451. tzrqf tzrzf
  1452. lacn2 lahr2 stemr laqr0 laqr1 laqr2 laqr3 laqr4 laqr5
  1453. ''' # [s|c|d|z]*.f
  1454. sd_lasrc = '''
  1455. laexc lag2 lagv2 laln2 lanv2 laqtr lasy2 opgtr opmtr org2l
  1456. org2r orgbr orghr orgl2 orglq orgql orgqr orgr2 orgrq orgtr
  1457. orm2l orm2r ormbr ormhr orml2 ormlq ormql ormqr ormr2 ormr3
  1458. ormrq ormrz ormtr rscl sbev sbevd sbevx sbgst sbgv sbgvd sbgvx
  1459. sbtrd spev spevd spevx spgst spgv spgvd spgvx sptrd stev stevd
  1460. stevr stevx syev syevd syevr syevx sygs2 sygst sygv sygvd
  1461. sygvx sytd2 sytrd
  1462. ''' # [s|d]*.f
  1463. cz_lasrc = '''
  1464. bdsqr hbev hbevd hbevx hbgst hbgv hbgvd hbgvx hbtrd hecon heev
  1465. heevd heevr heevx hegs2 hegst hegv hegvd hegvx herfs hesv
  1466. hesvx hetd2 hetf2 hetrd hetrf hetri hetrs hpcon hpev hpevd
  1467. hpevx hpgst hpgv hpgvd hpgvx hprfs hpsv hpsvx hptrd hptrf
  1468. hptri hptrs lacgv lacp2 lacpy lacrm lacrt ladiv laed0 laed7
  1469. laed8 laesy laev2 lahef lanhb lanhe lanhp lanht laqhb laqhe
  1470. laqhp larcm larnv lartg lascl laset lasr lassq pttrf rot spmv
  1471. spr stedc steqr symv syr ung2l ung2r ungbr unghr ungl2 unglq
  1472. ungql ungqr ungr2 ungrq ungtr unm2l unm2r unmbr unmhr unml2
  1473. unmlq unmql unmqr unmr2 unmr3 unmrq unmrz unmtr upgtr upmtr
  1474. ''' # [c|z]*.f
  1475. #######
  1476. sclaux = laux + ' econd ' # s*.f
  1477. dzlaux = laux + ' secnd ' # d*.f
  1478. slasrc = lasrc + sd_lasrc # s*.f
  1479. dlasrc = lasrc + sd_lasrc # d*.f
  1480. clasrc = lasrc + cz_lasrc + ' srot srscl ' # c*.f
  1481. zlasrc = lasrc + cz_lasrc + ' drot drscl ' # z*.f
  1482. oclasrc = ' icmax1 scsum1 ' # *.f
  1483. ozlasrc = ' izmax1 dzsum1 ' # *.f
  1484. sources = ['s%s.f' % f for f in (sclaux + slasrc).split()] \
  1485. + ['d%s.f' % f for f in (dzlaux + dlasrc).split()] \
  1486. + ['c%s.f' % f for f in (clasrc).split()] \
  1487. + ['z%s.f' % f for f in (zlasrc).split()] \
  1488. + ['%s.f' % f for f in (allaux + oclasrc + ozlasrc).split()]
  1489. sources = [os.path.join(src_dir, f) for f in sources]
  1490. # Lapack 3.1:
  1491. src_dir2 = os.path.join(src_dir, '..', 'INSTALL')
  1492. sources += [os.path.join(src_dir2, p + 'lamch.f') for p in 'sdcz']
  1493. # Lapack 3.2.1:
  1494. sources += [os.path.join(src_dir, p + 'larfp.f') for p in 'sdcz']
  1495. sources += [os.path.join(src_dir, 'ila' + p + 'lr.f') for p in 'sdcz']
  1496. sources += [os.path.join(src_dir, 'ila' + p + 'lc.f') for p in 'sdcz']
  1497. # Should we check here actual existence of source files?
  1498. # Yes, the file listing is different between 3.0 and 3.1
  1499. # versions.
  1500. sources = [f for f in sources if os.path.isfile(f)]
  1501. info = {'sources': sources, 'language': 'f77'}
  1502. self.set_info(**info)
  1503. atlas_version_c_text = r'''
  1504. /* This file is generated from numpy/distutils/system_info.py */
  1505. void ATL_buildinfo(void);
  1506. int main(void) {
  1507. ATL_buildinfo();
  1508. return 0;
  1509. }
  1510. '''
  1511. _cached_atlas_version = {}
  1512. def get_atlas_version(**config):
  1513. libraries = config.get('libraries', [])
  1514. library_dirs = config.get('library_dirs', [])
  1515. key = (tuple(libraries), tuple(library_dirs))
  1516. if key in _cached_atlas_version:
  1517. return _cached_atlas_version[key]
  1518. c = cmd_config(Distribution())
  1519. atlas_version = None
  1520. info = {}
  1521. try:
  1522. s, o = c.get_output(atlas_version_c_text,
  1523. libraries=libraries, library_dirs=library_dirs,
  1524. )
  1525. if s and re.search(r'undefined reference to `_gfortran', o, re.M):
  1526. s, o = c.get_output(atlas_version_c_text,
  1527. libraries=libraries + ['gfortran'],
  1528. library_dirs=library_dirs,
  1529. )
  1530. if not s:
  1531. warnings.warn(textwrap.dedent("""
  1532. *****************************************************
  1533. Linkage with ATLAS requires gfortran. Use
  1534. python setup.py config_fc --fcompiler=gnu95 ...
  1535. when building extension libraries that use ATLAS.
  1536. Make sure that -lgfortran is used for C++ extensions.
  1537. *****************************************************
  1538. """), stacklevel=2)
  1539. dict_append(info, language='f90',
  1540. define_macros=[('ATLAS_REQUIRES_GFORTRAN', None)])
  1541. except Exception: # failed to get version from file -- maybe on Windows
  1542. # look at directory name
  1543. for o in library_dirs:
  1544. m = re.search(r'ATLAS_(?P<version>\d+[.]\d+[.]\d+)_', o)
  1545. if m:
  1546. atlas_version = m.group('version')
  1547. if atlas_version is not None:
  1548. break
  1549. # final choice --- look at ATLAS_VERSION environment
  1550. # variable
  1551. if atlas_version is None:
  1552. atlas_version = os.environ.get('ATLAS_VERSION', None)
  1553. if atlas_version:
  1554. dict_append(info, define_macros=[(
  1555. 'ATLAS_INFO', _c_string_literal(atlas_version))
  1556. ])
  1557. else:
  1558. dict_append(info, define_macros=[('NO_ATLAS_INFO', -1)])
  1559. return atlas_version or '?.?.?', info
  1560. if not s:
  1561. m = re.search(r'ATLAS version (?P<version>\d+[.]\d+[.]\d+)', o)
  1562. if m:
  1563. atlas_version = m.group('version')
  1564. if atlas_version is None:
  1565. if re.search(r'undefined symbol: ATL_buildinfo', o, re.M):
  1566. atlas_version = '3.2.1_pre3.3.6'
  1567. else:
  1568. log.info('Status: %d', s)
  1569. log.info('Output: %s', o)
  1570. elif atlas_version == '3.2.1_pre3.3.6':
  1571. dict_append(info, define_macros=[('NO_ATLAS_INFO', -2)])
  1572. else:
  1573. dict_append(info, define_macros=[(
  1574. 'ATLAS_INFO', _c_string_literal(atlas_version))
  1575. ])
  1576. result = _cached_atlas_version[key] = atlas_version, info
  1577. return result
  1578. class lapack_opt_info(system_info):
  1579. notfounderror = LapackNotFoundError
  1580. # List of all known LAPACK libraries, in the default order
  1581. lapack_order = ['armpl', 'mkl', 'ssl2', 'openblas', 'flame',
  1582. 'accelerate', 'atlas', 'lapack']
  1583. order_env_var_name = 'NPY_LAPACK_ORDER'
  1584. def _calc_info_armpl(self):
  1585. info = get_info('lapack_armpl')
  1586. if info:
  1587. self.set_info(**info)
  1588. return True
  1589. return False
  1590. def _calc_info_mkl(self):
  1591. info = get_info('lapack_mkl')
  1592. if info:
  1593. self.set_info(**info)
  1594. return True
  1595. return False
  1596. def _calc_info_ssl2(self):
  1597. info = get_info('lapack_ssl2')
  1598. if info:
  1599. self.set_info(**info)
  1600. return True
  1601. return False
  1602. def _calc_info_openblas(self):
  1603. info = get_info('openblas_lapack')
  1604. if info:
  1605. self.set_info(**info)
  1606. return True
  1607. info = get_info('openblas_clapack')
  1608. if info:
  1609. self.set_info(**info)
  1610. return True
  1611. return False
  1612. def _calc_info_flame(self):
  1613. info = get_info('flame')
  1614. if info:
  1615. self.set_info(**info)
  1616. return True
  1617. return False
  1618. def _calc_info_atlas(self):
  1619. info = get_info('atlas_3_10_threads')
  1620. if not info:
  1621. info = get_info('atlas_3_10')
  1622. if not info:
  1623. info = get_info('atlas_threads')
  1624. if not info:
  1625. info = get_info('atlas')
  1626. if info:
  1627. # Figure out if ATLAS has lapack...
  1628. # If not we need the lapack library, but not BLAS!
  1629. l = info.get('define_macros', [])
  1630. if ('ATLAS_WITH_LAPACK_ATLAS', None) in l \
  1631. or ('ATLAS_WITHOUT_LAPACK', None) in l:
  1632. # Get LAPACK (with possible warnings)
  1633. # If not found we don't accept anything
  1634. # since we can't use ATLAS with LAPACK!
  1635. lapack_info = self._get_info_lapack()
  1636. if not lapack_info:
  1637. return False
  1638. dict_append(info, **lapack_info)
  1639. self.set_info(**info)
  1640. return True
  1641. return False
  1642. def _calc_info_accelerate(self):
  1643. info = get_info('accelerate')
  1644. if info:
  1645. self.set_info(**info)
  1646. return True
  1647. return False
  1648. def _get_info_blas(self):
  1649. # Default to get the optimized BLAS implementation
  1650. info = get_info('blas_opt')
  1651. if not info:
  1652. warnings.warn(BlasNotFoundError.__doc__ or '', stacklevel=3)
  1653. info_src = get_info('blas_src')
  1654. if not info_src:
  1655. warnings.warn(BlasSrcNotFoundError.__doc__ or '', stacklevel=3)
  1656. return {}
  1657. dict_append(info, libraries=[('fblas_src', info_src)])
  1658. return info
  1659. def _get_info_lapack(self):
  1660. info = get_info('lapack')
  1661. if not info:
  1662. warnings.warn(LapackNotFoundError.__doc__ or '', stacklevel=3)
  1663. info_src = get_info('lapack_src')
  1664. if not info_src:
  1665. warnings.warn(LapackSrcNotFoundError.__doc__ or '', stacklevel=3)
  1666. return {}
  1667. dict_append(info, libraries=[('flapack_src', info_src)])
  1668. return info
  1669. def _calc_info_lapack(self):
  1670. info = self._get_info_lapack()
  1671. if info:
  1672. info_blas = self._get_info_blas()
  1673. dict_append(info, **info_blas)
  1674. dict_append(info, define_macros=[('NO_ATLAS_INFO', 1)])
  1675. self.set_info(**info)
  1676. return True
  1677. return False
  1678. def _calc_info_from_envvar(self):
  1679. info = {}
  1680. info['language'] = 'f77'
  1681. info['libraries'] = []
  1682. info['include_dirs'] = []
  1683. info['define_macros'] = []
  1684. info['extra_link_args'] = os.environ['NPY_LAPACK_LIBS'].split()
  1685. self.set_info(**info)
  1686. return True
  1687. def _calc_info(self, name):
  1688. return getattr(self, '_calc_info_{}'.format(name))()
  1689. def calc_info(self):
  1690. lapack_order, unknown_order = _parse_env_order(self.lapack_order, self.order_env_var_name)
  1691. if len(unknown_order) > 0:
  1692. raise ValueError("lapack_opt_info user defined "
  1693. "LAPACK order has unacceptable "
  1694. "values: {}".format(unknown_order))
  1695. if 'NPY_LAPACK_LIBS' in os.environ:
  1696. # Bypass autodetection, set language to F77 and use env var linker
  1697. # flags directly
  1698. self._calc_info_from_envvar()
  1699. return
  1700. for lapack in lapack_order:
  1701. if self._calc_info(lapack):
  1702. return
  1703. if 'lapack' not in lapack_order:
  1704. # Since the user may request *not* to use any library, we still need
  1705. # to raise warnings to signal missing packages!
  1706. warnings.warn(LapackNotFoundError.__doc__ or '', stacklevel=2)
  1707. warnings.warn(LapackSrcNotFoundError.__doc__ or '', stacklevel=2)
  1708. class _ilp64_opt_info_mixin:
  1709. symbol_suffix = None
  1710. symbol_prefix = None
  1711. def _check_info(self, info):
  1712. macros = dict(info.get('define_macros', []))
  1713. prefix = macros.get('BLAS_SYMBOL_PREFIX', '')
  1714. suffix = macros.get('BLAS_SYMBOL_SUFFIX', '')
  1715. if self.symbol_prefix not in (None, prefix):
  1716. return False
  1717. if self.symbol_suffix not in (None, suffix):
  1718. return False
  1719. return bool(info)
  1720. class lapack_ilp64_opt_info(lapack_opt_info, _ilp64_opt_info_mixin):
  1721. notfounderror = LapackILP64NotFoundError
  1722. lapack_order = ['openblas64_', 'openblas_ilp64', 'accelerate']
  1723. order_env_var_name = 'NPY_LAPACK_ILP64_ORDER'
  1724. def _calc_info(self, name):
  1725. print('lapack_ilp64_opt_info._calc_info(name=%s)' % (name))
  1726. info = get_info(name + '_lapack')
  1727. if self._check_info(info):
  1728. self.set_info(**info)
  1729. return True
  1730. else:
  1731. print('%s_lapack does not exist' % (name))
  1732. return False
  1733. class lapack_ilp64_plain_opt_info(lapack_ilp64_opt_info):
  1734. # Same as lapack_ilp64_opt_info, but fix symbol names
  1735. symbol_prefix = ''
  1736. symbol_suffix = ''
  1737. class lapack64__opt_info(lapack_ilp64_opt_info):
  1738. symbol_prefix = ''
  1739. symbol_suffix = '64_'
  1740. class blas_opt_info(system_info):
  1741. notfounderror = BlasNotFoundError
  1742. # List of all known BLAS libraries, in the default order
  1743. blas_order = ['armpl', 'mkl', 'ssl2', 'blis', 'openblas',
  1744. 'accelerate', 'atlas', 'blas']
  1745. order_env_var_name = 'NPY_BLAS_ORDER'
  1746. def _calc_info_armpl(self):
  1747. info = get_info('blas_armpl')
  1748. if info:
  1749. self.set_info(**info)
  1750. return True
  1751. return False
  1752. def _calc_info_mkl(self):
  1753. info = get_info('blas_mkl')
  1754. if info:
  1755. self.set_info(**info)
  1756. return True
  1757. return False
  1758. def _calc_info_ssl2(self):
  1759. info = get_info('blas_ssl2')
  1760. if info:
  1761. self.set_info(**info)
  1762. return True
  1763. return False
  1764. def _calc_info_blis(self):
  1765. info = get_info('blis')
  1766. if info:
  1767. self.set_info(**info)
  1768. return True
  1769. return False
  1770. def _calc_info_openblas(self):
  1771. info = get_info('openblas')
  1772. if info:
  1773. self.set_info(**info)
  1774. return True
  1775. return False
  1776. def _calc_info_atlas(self):
  1777. info = get_info('atlas_3_10_blas_threads')
  1778. if not info:
  1779. info = get_info('atlas_3_10_blas')
  1780. if not info:
  1781. info = get_info('atlas_blas_threads')
  1782. if not info:
  1783. info = get_info('atlas_blas')
  1784. if info:
  1785. self.set_info(**info)
  1786. return True
  1787. return False
  1788. def _calc_info_accelerate(self):
  1789. info = get_info('accelerate')
  1790. if info:
  1791. self.set_info(**info)
  1792. return True
  1793. return False
  1794. def _calc_info_blas(self):
  1795. # Warn about a non-optimized BLAS library
  1796. warnings.warn(BlasOptNotFoundError.__doc__ or '', stacklevel=3)
  1797. info = {}
  1798. dict_append(info, define_macros=[('NO_ATLAS_INFO', 1)])
  1799. blas = get_info('blas')
  1800. if blas:
  1801. dict_append(info, **blas)
  1802. else:
  1803. # Not even BLAS was found!
  1804. warnings.warn(BlasNotFoundError.__doc__ or '', stacklevel=3)
  1805. blas_src = get_info('blas_src')
  1806. if not blas_src:
  1807. warnings.warn(BlasSrcNotFoundError.__doc__ or '', stacklevel=3)
  1808. return False
  1809. dict_append(info, libraries=[('fblas_src', blas_src)])
  1810. self.set_info(**info)
  1811. return True
  1812. def _calc_info_from_envvar(self):
  1813. info = {}
  1814. info['language'] = 'f77'
  1815. info['libraries'] = []
  1816. info['include_dirs'] = []
  1817. info['define_macros'] = []
  1818. info['extra_link_args'] = os.environ['NPY_BLAS_LIBS'].split()
  1819. if 'NPY_CBLAS_LIBS' in os.environ:
  1820. info['define_macros'].append(('HAVE_CBLAS', None))
  1821. info['extra_link_args'].extend(
  1822. os.environ['NPY_CBLAS_LIBS'].split())
  1823. self.set_info(**info)
  1824. return True
  1825. def _calc_info(self, name):
  1826. return getattr(self, '_calc_info_{}'.format(name))()
  1827. def calc_info(self):
  1828. blas_order, unknown_order = _parse_env_order(self.blas_order, self.order_env_var_name)
  1829. if len(unknown_order) > 0:
  1830. raise ValueError("blas_opt_info user defined BLAS order has unacceptable values: {}".format(unknown_order))
  1831. if 'NPY_BLAS_LIBS' in os.environ:
  1832. # Bypass autodetection, set language to F77 and use env var linker
  1833. # flags directly
  1834. self._calc_info_from_envvar()
  1835. return
  1836. for blas in blas_order:
  1837. if self._calc_info(blas):
  1838. return
  1839. if 'blas' not in blas_order:
  1840. # Since the user may request *not* to use any library, we still need
  1841. # to raise warnings to signal missing packages!
  1842. warnings.warn(BlasNotFoundError.__doc__ or '', stacklevel=2)
  1843. warnings.warn(BlasSrcNotFoundError.__doc__ or '', stacklevel=2)
  1844. class blas_ilp64_opt_info(blas_opt_info, _ilp64_opt_info_mixin):
  1845. notfounderror = BlasILP64NotFoundError
  1846. blas_order = ['openblas64_', 'openblas_ilp64', 'accelerate']
  1847. order_env_var_name = 'NPY_BLAS_ILP64_ORDER'
  1848. def _calc_info(self, name):
  1849. info = get_info(name)
  1850. if self._check_info(info):
  1851. self.set_info(**info)
  1852. return True
  1853. return False
  1854. class blas_ilp64_plain_opt_info(blas_ilp64_opt_info):
  1855. symbol_prefix = ''
  1856. symbol_suffix = ''
  1857. class blas64__opt_info(blas_ilp64_opt_info):
  1858. symbol_prefix = ''
  1859. symbol_suffix = '64_'
  1860. class cblas_info(system_info):
  1861. section = 'cblas'
  1862. dir_env_var = 'CBLAS'
  1863. # No default as it's used only in blas_info
  1864. _lib_names = []
  1865. notfounderror = BlasNotFoundError
  1866. class blas_info(system_info):
  1867. section = 'blas'
  1868. dir_env_var = 'BLAS'
  1869. _lib_names = ['blas']
  1870. notfounderror = BlasNotFoundError
  1871. def calc_info(self):
  1872. lib_dirs = self.get_lib_dirs()
  1873. opt = self.get_option_single('blas_libs', 'libraries')
  1874. blas_libs = self.get_libs(opt, self._lib_names)
  1875. info = self.check_libs(lib_dirs, blas_libs, [])
  1876. if info is None:
  1877. return
  1878. else:
  1879. info['include_dirs'] = self.get_include_dirs()
  1880. if platform.system() == 'Windows':
  1881. # The check for windows is needed because get_cblas_libs uses the
  1882. # same compiler that was used to compile Python and msvc is
  1883. # often not installed when mingw is being used. This rough
  1884. # treatment is not desirable, but windows is tricky.
  1885. info['language'] = 'f77' # XXX: is it generally true?
  1886. # If cblas is given as an option, use those
  1887. cblas_info_obj = cblas_info()
  1888. cblas_opt = cblas_info_obj.get_option_single('cblas_libs', 'libraries')
  1889. cblas_libs = cblas_info_obj.get_libs(cblas_opt, None)
  1890. if cblas_libs:
  1891. info['libraries'] = cblas_libs + blas_libs
  1892. info['define_macros'] = [('HAVE_CBLAS', None)]
  1893. else:
  1894. lib = self.get_cblas_libs(info)
  1895. if lib is not None:
  1896. info['language'] = 'c'
  1897. info['libraries'] = lib
  1898. info['define_macros'] = [('HAVE_CBLAS', None)]
  1899. self.set_info(**info)
  1900. def get_cblas_libs(self, info):
  1901. """ Check whether we can link with CBLAS interface
  1902. This method will search through several combinations of libraries
  1903. to check whether CBLAS is present:
  1904. 1. Libraries in ``info['libraries']``, as is
  1905. 2. As 1. but also explicitly adding ``'cblas'`` as a library
  1906. 3. As 1. but also explicitly adding ``'blas'`` as a library
  1907. 4. Check only library ``'cblas'``
  1908. 5. Check only library ``'blas'``
  1909. Parameters
  1910. ----------
  1911. info : dict
  1912. system information dictionary for compilation and linking
  1913. Returns
  1914. -------
  1915. libraries : list of str or None
  1916. a list of libraries that enables the use of CBLAS interface.
  1917. Returns None if not found or a compilation error occurs.
  1918. Since 1.17 returns a list.
  1919. """
  1920. # primitive cblas check by looking for the header and trying to link
  1921. # cblas or blas
  1922. c = customized_ccompiler()
  1923. tmpdir = tempfile.mkdtemp()
  1924. s = textwrap.dedent("""\
  1925. #include <cblas.h>
  1926. int main(int argc, const char *argv[])
  1927. {
  1928. double a[4] = {1,2,3,4};
  1929. double b[4] = {5,6,7,8};
  1930. return cblas_ddot(4, a, 1, b, 1) > 10;
  1931. }""")
  1932. src = os.path.join(tmpdir, 'source.c')
  1933. try:
  1934. with open(src, 'w') as f:
  1935. f.write(s)
  1936. try:
  1937. # check we can compile (find headers)
  1938. obj = c.compile([src], output_dir=tmpdir,
  1939. include_dirs=self.get_include_dirs())
  1940. except (distutils.ccompiler.CompileError, distutils.ccompiler.LinkError):
  1941. return None
  1942. # check we can link (find library)
  1943. # some systems have separate cblas and blas libs.
  1944. for libs in [info['libraries'], ['cblas'] + info['libraries'],
  1945. ['blas'] + info['libraries'], ['cblas'], ['blas']]:
  1946. try:
  1947. c.link_executable(obj, os.path.join(tmpdir, "a.out"),
  1948. libraries=libs,
  1949. library_dirs=info['library_dirs'],
  1950. extra_postargs=info.get('extra_link_args', []))
  1951. return libs
  1952. except distutils.ccompiler.LinkError:
  1953. pass
  1954. finally:
  1955. shutil.rmtree(tmpdir)
  1956. return None
  1957. class openblas_info(blas_info):
  1958. section = 'openblas'
  1959. dir_env_var = 'OPENBLAS'
  1960. _lib_names = ['openblas']
  1961. _require_symbols = []
  1962. notfounderror = BlasNotFoundError
  1963. @property
  1964. def symbol_prefix(self):
  1965. try:
  1966. return self.cp.get(self.section, 'symbol_prefix')
  1967. except NoOptionError:
  1968. return ''
  1969. @property
  1970. def symbol_suffix(self):
  1971. try:
  1972. return self.cp.get(self.section, 'symbol_suffix')
  1973. except NoOptionError:
  1974. return ''
  1975. def _calc_info(self):
  1976. c = customized_ccompiler()
  1977. lib_dirs = self.get_lib_dirs()
  1978. # Prefer to use libraries over openblas_libs
  1979. opt = self.get_option_single('openblas_libs', 'libraries')
  1980. openblas_libs = self.get_libs(opt, self._lib_names)
  1981. info = self.check_libs(lib_dirs, openblas_libs, [])
  1982. if c.compiler_type == "msvc" and info is None:
  1983. from numpy.distutils.fcompiler import new_fcompiler
  1984. f = new_fcompiler(c_compiler=c)
  1985. if f and f.compiler_type == 'gnu95':
  1986. # Try gfortran-compatible library files
  1987. info = self.check_msvc_gfortran_libs(lib_dirs, openblas_libs)
  1988. # Skip lapack check, we'd need build_ext to do it
  1989. skip_symbol_check = True
  1990. elif info:
  1991. skip_symbol_check = False
  1992. info['language'] = 'c'
  1993. if info is None:
  1994. return None
  1995. # Add extra info for OpenBLAS
  1996. extra_info = self.calc_extra_info()
  1997. dict_append(info, **extra_info)
  1998. if not (skip_symbol_check or self.check_symbols(info)):
  1999. return None
  2000. info['define_macros'] = [('HAVE_CBLAS', None)]
  2001. if self.symbol_prefix:
  2002. info['define_macros'] += [('BLAS_SYMBOL_PREFIX', self.symbol_prefix)]
  2003. if self.symbol_suffix:
  2004. info['define_macros'] += [('BLAS_SYMBOL_SUFFIX', self.symbol_suffix)]
  2005. return info
  2006. def calc_info(self):
  2007. info = self._calc_info()
  2008. if info is not None:
  2009. self.set_info(**info)
  2010. def check_msvc_gfortran_libs(self, library_dirs, libraries):
  2011. # First, find the full path to each library directory
  2012. library_paths = []
  2013. for library in libraries:
  2014. for library_dir in library_dirs:
  2015. # MinGW static ext will be .a
  2016. fullpath = os.path.join(library_dir, library + '.a')
  2017. if os.path.isfile(fullpath):
  2018. library_paths.append(fullpath)
  2019. break
  2020. else:
  2021. return None
  2022. # Generate numpy.distutils virtual static library file
  2023. basename = self.__class__.__name__
  2024. tmpdir = os.path.join(os.getcwd(), 'build', basename)
  2025. if not os.path.isdir(tmpdir):
  2026. os.makedirs(tmpdir)
  2027. info = {'library_dirs': [tmpdir],
  2028. 'libraries': [basename],
  2029. 'language': 'f77'}
  2030. fake_lib_file = os.path.join(tmpdir, basename + '.fobjects')
  2031. fake_clib_file = os.path.join(tmpdir, basename + '.cobjects')
  2032. with open(fake_lib_file, 'w') as f:
  2033. f.write("\n".join(library_paths))
  2034. with open(fake_clib_file, 'w') as f:
  2035. pass
  2036. return info
  2037. def check_symbols(self, info):
  2038. res = False
  2039. c = customized_ccompiler()
  2040. tmpdir = tempfile.mkdtemp()
  2041. prototypes = "\n".join("void %s%s%s();" % (self.symbol_prefix,
  2042. symbol_name,
  2043. self.symbol_suffix)
  2044. for symbol_name in self._require_symbols)
  2045. calls = "\n".join("%s%s%s();" % (self.symbol_prefix,
  2046. symbol_name,
  2047. self.symbol_suffix)
  2048. for symbol_name in self._require_symbols)
  2049. s = textwrap.dedent("""\
  2050. %(prototypes)s
  2051. int main(int argc, const char *argv[])
  2052. {
  2053. %(calls)s
  2054. return 0;
  2055. }""") % dict(prototypes=prototypes, calls=calls)
  2056. src = os.path.join(tmpdir, 'source.c')
  2057. out = os.path.join(tmpdir, 'a.out')
  2058. # Add the additional "extra" arguments
  2059. try:
  2060. extra_args = info['extra_link_args']
  2061. except Exception:
  2062. extra_args = []
  2063. try:
  2064. with open(src, 'w') as f:
  2065. f.write(s)
  2066. obj = c.compile([src], output_dir=tmpdir)
  2067. try:
  2068. c.link_executable(obj, out, libraries=info['libraries'],
  2069. library_dirs=info['library_dirs'],
  2070. extra_postargs=extra_args)
  2071. res = True
  2072. except distutils.ccompiler.LinkError:
  2073. res = False
  2074. finally:
  2075. shutil.rmtree(tmpdir)
  2076. return res
  2077. class openblas_lapack_info(openblas_info):
  2078. section = 'openblas'
  2079. dir_env_var = 'OPENBLAS'
  2080. _lib_names = ['openblas']
  2081. _require_symbols = ['zungqr_']
  2082. notfounderror = BlasNotFoundError
  2083. class openblas_clapack_info(openblas_lapack_info):
  2084. _lib_names = ['openblas', 'lapack']
  2085. class openblas_ilp64_info(openblas_info):
  2086. section = 'openblas_ilp64'
  2087. dir_env_var = 'OPENBLAS_ILP64'
  2088. _lib_names = ['openblas64']
  2089. _require_symbols = ['dgemm_', 'cblas_dgemm']
  2090. notfounderror = BlasILP64NotFoundError
  2091. def _calc_info(self):
  2092. info = super()._calc_info()
  2093. if info is not None:
  2094. info['define_macros'] += [('HAVE_BLAS_ILP64', None)]
  2095. return info
  2096. class openblas_ilp64_lapack_info(openblas_ilp64_info):
  2097. _require_symbols = ['dgemm_', 'cblas_dgemm', 'zungqr_', 'LAPACKE_zungqr']
  2098. def _calc_info(self):
  2099. info = super()._calc_info()
  2100. if info:
  2101. info['define_macros'] += [('HAVE_LAPACKE', None)]
  2102. return info
  2103. class openblas64__info(openblas_ilp64_info):
  2104. # ILP64 Openblas, with default symbol suffix
  2105. section = 'openblas64_'
  2106. dir_env_var = 'OPENBLAS64_'
  2107. _lib_names = ['openblas64_']
  2108. symbol_suffix = '64_'
  2109. symbol_prefix = ''
  2110. class openblas64__lapack_info(openblas_ilp64_lapack_info, openblas64__info):
  2111. pass
  2112. class blis_info(blas_info):
  2113. section = 'blis'
  2114. dir_env_var = 'BLIS'
  2115. _lib_names = ['blis']
  2116. notfounderror = BlasNotFoundError
  2117. def calc_info(self):
  2118. lib_dirs = self.get_lib_dirs()
  2119. opt = self.get_option_single('blis_libs', 'libraries')
  2120. blis_libs = self.get_libs(opt, self._lib_names)
  2121. info = self.check_libs2(lib_dirs, blis_libs, [])
  2122. if info is None:
  2123. return
  2124. # Add include dirs
  2125. incl_dirs = self.get_include_dirs()
  2126. dict_append(info,
  2127. language='c',
  2128. define_macros=[('HAVE_CBLAS', None)],
  2129. include_dirs=incl_dirs)
  2130. self.set_info(**info)
  2131. class flame_info(system_info):
  2132. """ Usage of libflame for LAPACK operations
  2133. This requires libflame to be compiled with lapack wrappers:
  2134. ./configure --enable-lapack2flame ...
  2135. Be aware that libflame 5.1.0 has some missing names in the shared library, so
  2136. if you have problems, try the static flame library.
  2137. """
  2138. section = 'flame'
  2139. _lib_names = ['flame']
  2140. notfounderror = FlameNotFoundError
  2141. def check_embedded_lapack(self, info):
  2142. """ libflame does not necessarily have a wrapper for fortran LAPACK, we need to check """
  2143. c = customized_ccompiler()
  2144. tmpdir = tempfile.mkdtemp()
  2145. s = textwrap.dedent("""\
  2146. void zungqr_();
  2147. int main(int argc, const char *argv[])
  2148. {
  2149. zungqr_();
  2150. return 0;
  2151. }""")
  2152. src = os.path.join(tmpdir, 'source.c')
  2153. out = os.path.join(tmpdir, 'a.out')
  2154. # Add the additional "extra" arguments
  2155. extra_args = info.get('extra_link_args', [])
  2156. try:
  2157. with open(src, 'w') as f:
  2158. f.write(s)
  2159. obj = c.compile([src], output_dir=tmpdir)
  2160. try:
  2161. c.link_executable(obj, out, libraries=info['libraries'],
  2162. library_dirs=info['library_dirs'],
  2163. extra_postargs=extra_args)
  2164. return True
  2165. except distutils.ccompiler.LinkError:
  2166. return False
  2167. finally:
  2168. shutil.rmtree(tmpdir)
  2169. def calc_info(self):
  2170. lib_dirs = self.get_lib_dirs()
  2171. flame_libs = self.get_libs('libraries', self._lib_names)
  2172. info = self.check_libs2(lib_dirs, flame_libs, [])
  2173. if info is None:
  2174. return
  2175. # Add the extra flag args to info
  2176. extra_info = self.calc_extra_info()
  2177. dict_append(info, **extra_info)
  2178. if self.check_embedded_lapack(info):
  2179. # check if the user has supplied all information required
  2180. self.set_info(**info)
  2181. else:
  2182. # Try and get the BLAS lib to see if we can get it to work
  2183. blas_info = get_info('blas_opt')
  2184. if not blas_info:
  2185. # since we already failed once, this ain't going to work either
  2186. return
  2187. # Now we need to merge the two dictionaries
  2188. for key in blas_info:
  2189. if isinstance(blas_info[key], list):
  2190. info[key] = info.get(key, []) + blas_info[key]
  2191. elif isinstance(blas_info[key], tuple):
  2192. info[key] = info.get(key, ()) + blas_info[key]
  2193. else:
  2194. info[key] = info.get(key, '') + blas_info[key]
  2195. # Now check again
  2196. if self.check_embedded_lapack(info):
  2197. self.set_info(**info)
  2198. class accelerate_info(system_info):
  2199. section = 'accelerate'
  2200. _lib_names = ['accelerate', 'veclib']
  2201. notfounderror = BlasNotFoundError
  2202. def calc_info(self):
  2203. # Make possible to enable/disable from config file/env var
  2204. libraries = os.environ.get('ACCELERATE')
  2205. if libraries:
  2206. libraries = [libraries]
  2207. else:
  2208. libraries = self.get_libs('libraries', self._lib_names)
  2209. libraries = [lib.strip().lower() for lib in libraries]
  2210. if (sys.platform == 'darwin' and
  2211. not os.getenv('_PYTHON_HOST_PLATFORM', None)):
  2212. # Use the system BLAS from Accelerate or vecLib under OSX
  2213. args = []
  2214. link_args = []
  2215. if get_platform()[-4:] == 'i386' or 'intel' in get_platform() or \
  2216. 'x86_64' in get_platform() or \
  2217. 'i386' in platform.platform():
  2218. intel = 1
  2219. else:
  2220. intel = 0
  2221. if (os.path.exists('/System/Library/Frameworks'
  2222. '/Accelerate.framework/') and
  2223. 'accelerate' in libraries):
  2224. if intel:
  2225. args.extend(['-msse3'])
  2226. args.extend([
  2227. '-I/System/Library/Frameworks/vecLib.framework/Headers'])
  2228. link_args.extend(['-Wl,-framework', '-Wl,Accelerate'])
  2229. elif (os.path.exists('/System/Library/Frameworks'
  2230. '/vecLib.framework/') and
  2231. 'veclib' in libraries):
  2232. if intel:
  2233. args.extend(['-msse3'])
  2234. args.extend([
  2235. '-I/System/Library/Frameworks/vecLib.framework/Headers'])
  2236. link_args.extend(['-Wl,-framework', '-Wl,vecLib'])
  2237. if args:
  2238. macros = [
  2239. ('NO_ATLAS_INFO', 3),
  2240. ('HAVE_CBLAS', None),
  2241. ('ACCELERATE_NEW_LAPACK', None),
  2242. ]
  2243. if(os.getenv('NPY_USE_BLAS_ILP64', None)):
  2244. print('Setting HAVE_BLAS_ILP64')
  2245. macros += [
  2246. ('HAVE_BLAS_ILP64', None),
  2247. ('ACCELERATE_LAPACK_ILP64', None),
  2248. ]
  2249. self.set_info(extra_compile_args=args,
  2250. extra_link_args=link_args,
  2251. define_macros=macros)
  2252. return
  2253. class accelerate_lapack_info(accelerate_info):
  2254. def _calc_info(self):
  2255. return super()._calc_info()
  2256. class blas_src_info(system_info):
  2257. # BLAS_SRC is deprecated, please do not use this!
  2258. # Build or install a BLAS library via your package manager or from
  2259. # source separately.
  2260. section = 'blas_src'
  2261. dir_env_var = 'BLAS_SRC'
  2262. notfounderror = BlasSrcNotFoundError
  2263. def get_paths(self, section, key):
  2264. pre_dirs = system_info.get_paths(self, section, key)
  2265. dirs = []
  2266. for d in pre_dirs:
  2267. dirs.extend([d] + self.combine_paths(d, ['blas']))
  2268. return [d for d in dirs if os.path.isdir(d)]
  2269. def calc_info(self):
  2270. src_dirs = self.get_src_dirs()
  2271. src_dir = ''
  2272. for d in src_dirs:
  2273. if os.path.isfile(os.path.join(d, 'daxpy.f')):
  2274. src_dir = d
  2275. break
  2276. if not src_dir:
  2277. #XXX: Get sources from netlib. May be ask first.
  2278. return
  2279. blas1 = '''
  2280. caxpy csscal dnrm2 dzasum saxpy srotg zdotc ccopy cswap drot
  2281. dznrm2 scasum srotm zdotu cdotc dasum drotg icamax scnrm2
  2282. srotmg zdrot cdotu daxpy drotm idamax scopy sscal zdscal crotg
  2283. dcabs1 drotmg isamax sdot sswap zrotg cscal dcopy dscal izamax
  2284. snrm2 zaxpy zscal csrot ddot dswap sasum srot zcopy zswap
  2285. scabs1
  2286. '''
  2287. blas2 = '''
  2288. cgbmv chpmv ctrsv dsymv dtrsv sspr2 strmv zhemv ztpmv cgemv
  2289. chpr dgbmv dsyr lsame ssymv strsv zher ztpsv cgerc chpr2 dgemv
  2290. dsyr2 sgbmv ssyr xerbla zher2 ztrmv cgeru ctbmv dger dtbmv
  2291. sgemv ssyr2 zgbmv zhpmv ztrsv chbmv ctbsv dsbmv dtbsv sger
  2292. stbmv zgemv zhpr chemv ctpmv dspmv dtpmv ssbmv stbsv zgerc
  2293. zhpr2 cher ctpsv dspr dtpsv sspmv stpmv zgeru ztbmv cher2
  2294. ctrmv dspr2 dtrmv sspr stpsv zhbmv ztbsv
  2295. '''
  2296. blas3 = '''
  2297. cgemm csymm ctrsm dsyrk sgemm strmm zhemm zsyr2k chemm csyr2k
  2298. dgemm dtrmm ssymm strsm zher2k zsyrk cher2k csyrk dsymm dtrsm
  2299. ssyr2k zherk ztrmm cherk ctrmm dsyr2k ssyrk zgemm zsymm ztrsm
  2300. '''
  2301. sources = [os.path.join(src_dir, f + '.f') \
  2302. for f in (blas1 + blas2 + blas3).split()]
  2303. #XXX: should we check here actual existence of source files?
  2304. sources = [f for f in sources if os.path.isfile(f)]
  2305. info = {'sources': sources, 'language': 'f77'}
  2306. self.set_info(**info)
  2307. class x11_info(system_info):
  2308. section = 'x11'
  2309. notfounderror = X11NotFoundError
  2310. _lib_names = ['X11']
  2311. def __init__(self):
  2312. system_info.__init__(self,
  2313. default_lib_dirs=default_x11_lib_dirs,
  2314. default_include_dirs=default_x11_include_dirs)
  2315. def calc_info(self):
  2316. if sys.platform in ['win32']:
  2317. return
  2318. lib_dirs = self.get_lib_dirs()
  2319. include_dirs = self.get_include_dirs()
  2320. opt = self.get_option_single('x11_libs', 'libraries')
  2321. x11_libs = self.get_libs(opt, self._lib_names)
  2322. info = self.check_libs(lib_dirs, x11_libs, [])
  2323. if info is None:
  2324. return
  2325. inc_dir = None
  2326. for d in include_dirs:
  2327. if self.combine_paths(d, 'X11/X.h'):
  2328. inc_dir = d
  2329. break
  2330. if inc_dir is not None:
  2331. dict_append(info, include_dirs=[inc_dir])
  2332. self.set_info(**info)
  2333. class _numpy_info(system_info):
  2334. section = 'Numeric'
  2335. modulename = 'Numeric'
  2336. notfounderror = NumericNotFoundError
  2337. def __init__(self):
  2338. include_dirs = []
  2339. try:
  2340. module = __import__(self.modulename)
  2341. prefix = []
  2342. for name in module.__file__.split(os.sep):
  2343. if name == 'lib':
  2344. break
  2345. prefix.append(name)
  2346. # Ask numpy for its own include path before attempting
  2347. # anything else
  2348. try:
  2349. include_dirs.append(getattr(module, 'get_include')())
  2350. except AttributeError:
  2351. pass
  2352. include_dirs.append(sysconfig.get_path('include'))
  2353. except ImportError:
  2354. pass
  2355. py_incl_dir = sysconfig.get_path('include')
  2356. include_dirs.append(py_incl_dir)
  2357. py_pincl_dir = sysconfig.get_path('platinclude')
  2358. if py_pincl_dir not in include_dirs:
  2359. include_dirs.append(py_pincl_dir)
  2360. for d in default_include_dirs:
  2361. d = os.path.join(d, os.path.basename(py_incl_dir))
  2362. if d not in include_dirs:
  2363. include_dirs.append(d)
  2364. system_info.__init__(self,
  2365. default_lib_dirs=[],
  2366. default_include_dirs=include_dirs)
  2367. def calc_info(self):
  2368. try:
  2369. module = __import__(self.modulename)
  2370. except ImportError:
  2371. return
  2372. info = {}
  2373. macros = []
  2374. for v in ['__version__', 'version']:
  2375. vrs = getattr(module, v, None)
  2376. if vrs is None:
  2377. continue
  2378. macros = [(self.modulename.upper() + '_VERSION',
  2379. _c_string_literal(vrs)),
  2380. (self.modulename.upper(), None)]
  2381. break
  2382. dict_append(info, define_macros=macros)
  2383. include_dirs = self.get_include_dirs()
  2384. inc_dir = None
  2385. for d in include_dirs:
  2386. if self.combine_paths(d,
  2387. os.path.join(self.modulename,
  2388. 'arrayobject.h')):
  2389. inc_dir = d
  2390. break
  2391. if inc_dir is not None:
  2392. dict_append(info, include_dirs=[inc_dir])
  2393. if info:
  2394. self.set_info(**info)
  2395. return
  2396. class numarray_info(_numpy_info):
  2397. section = 'numarray'
  2398. modulename = 'numarray'
  2399. class Numeric_info(_numpy_info):
  2400. section = 'Numeric'
  2401. modulename = 'Numeric'
  2402. class numpy_info(_numpy_info):
  2403. section = 'numpy'
  2404. modulename = 'numpy'
  2405. class numerix_info(system_info):
  2406. section = 'numerix'
  2407. def calc_info(self):
  2408. which = None, None
  2409. if os.getenv("NUMERIX"):
  2410. which = os.getenv("NUMERIX"), "environment var"
  2411. # If all the above fail, default to numpy.
  2412. if which[0] is None:
  2413. which = "numpy", "defaulted"
  2414. try:
  2415. import numpy # noqa: F401
  2416. which = "numpy", "defaulted"
  2417. except ImportError as e:
  2418. msg1 = str(e)
  2419. try:
  2420. import Numeric # noqa: F401
  2421. which = "numeric", "defaulted"
  2422. except ImportError as e:
  2423. msg2 = str(e)
  2424. try:
  2425. import numarray # noqa: F401
  2426. which = "numarray", "defaulted"
  2427. except ImportError as e:
  2428. msg3 = str(e)
  2429. log.info(msg1)
  2430. log.info(msg2)
  2431. log.info(msg3)
  2432. which = which[0].strip().lower(), which[1]
  2433. if which[0] not in ["numeric", "numarray", "numpy"]:
  2434. raise ValueError("numerix selector must be either 'Numeric' "
  2435. "or 'numarray' or 'numpy' but the value obtained"
  2436. " from the %s was '%s'." % (which[1], which[0]))
  2437. os.environ['NUMERIX'] = which[0]
  2438. self.set_info(**get_info(which[0]))
  2439. class f2py_info(system_info):
  2440. def calc_info(self):
  2441. try:
  2442. import numpy.f2py as f2py
  2443. except ImportError:
  2444. return
  2445. f2py_dir = os.path.join(os.path.dirname(f2py.__file__), 'src')
  2446. self.set_info(sources=[os.path.join(f2py_dir, 'fortranobject.c')],
  2447. include_dirs=[f2py_dir])
  2448. return
  2449. class boost_python_info(system_info):
  2450. section = 'boost_python'
  2451. dir_env_var = 'BOOST'
  2452. def get_paths(self, section, key):
  2453. pre_dirs = system_info.get_paths(self, section, key)
  2454. dirs = []
  2455. for d in pre_dirs:
  2456. dirs.extend([d] + self.combine_paths(d, ['boost*']))
  2457. return [d for d in dirs if os.path.isdir(d)]
  2458. def calc_info(self):
  2459. src_dirs = self.get_src_dirs()
  2460. src_dir = ''
  2461. for d in src_dirs:
  2462. if os.path.isfile(os.path.join(d, 'libs', 'python', 'src',
  2463. 'module.cpp')):
  2464. src_dir = d
  2465. break
  2466. if not src_dir:
  2467. return
  2468. py_incl_dirs = [sysconfig.get_path('include')]
  2469. py_pincl_dir = sysconfig.get_path('platinclude')
  2470. if py_pincl_dir not in py_incl_dirs:
  2471. py_incl_dirs.append(py_pincl_dir)
  2472. srcs_dir = os.path.join(src_dir, 'libs', 'python', 'src')
  2473. bpl_srcs = glob(os.path.join(srcs_dir, '*.cpp'))
  2474. bpl_srcs += glob(os.path.join(srcs_dir, '*', '*.cpp'))
  2475. info = {'libraries': [('boost_python_src',
  2476. {'include_dirs': [src_dir] + py_incl_dirs,
  2477. 'sources':bpl_srcs}
  2478. )],
  2479. 'include_dirs': [src_dir],
  2480. }
  2481. if info:
  2482. self.set_info(**info)
  2483. return
  2484. class agg2_info(system_info):
  2485. section = 'agg2'
  2486. dir_env_var = 'AGG2'
  2487. def get_paths(self, section, key):
  2488. pre_dirs = system_info.get_paths(self, section, key)
  2489. dirs = []
  2490. for d in pre_dirs:
  2491. dirs.extend([d] + self.combine_paths(d, ['agg2*']))
  2492. return [d for d in dirs if os.path.isdir(d)]
  2493. def calc_info(self):
  2494. src_dirs = self.get_src_dirs()
  2495. src_dir = ''
  2496. for d in src_dirs:
  2497. if os.path.isfile(os.path.join(d, 'src', 'agg_affine_matrix.cpp')):
  2498. src_dir = d
  2499. break
  2500. if not src_dir:
  2501. return
  2502. if sys.platform == 'win32':
  2503. agg2_srcs = glob(os.path.join(src_dir, 'src', 'platform',
  2504. 'win32', 'agg_win32_bmp.cpp'))
  2505. else:
  2506. agg2_srcs = glob(os.path.join(src_dir, 'src', '*.cpp'))
  2507. agg2_srcs += [os.path.join(src_dir, 'src', 'platform',
  2508. 'X11',
  2509. 'agg_platform_support.cpp')]
  2510. info = {'libraries':
  2511. [('agg2_src',
  2512. {'sources': agg2_srcs,
  2513. 'include_dirs': [os.path.join(src_dir, 'include')],
  2514. }
  2515. )],
  2516. 'include_dirs': [os.path.join(src_dir, 'include')],
  2517. }
  2518. if info:
  2519. self.set_info(**info)
  2520. return
  2521. class _pkg_config_info(system_info):
  2522. section = None
  2523. config_env_var = 'PKG_CONFIG'
  2524. default_config_exe = 'pkg-config'
  2525. append_config_exe = ''
  2526. version_macro_name = None
  2527. release_macro_name = None
  2528. version_flag = '--modversion'
  2529. cflags_flag = '--cflags'
  2530. def get_config_exe(self):
  2531. if self.config_env_var in os.environ:
  2532. return os.environ[self.config_env_var]
  2533. return self.default_config_exe
  2534. def get_config_output(self, config_exe, option):
  2535. cmd = config_exe + ' ' + self.append_config_exe + ' ' + option
  2536. try:
  2537. o = subprocess.check_output(cmd)
  2538. except (OSError, subprocess.CalledProcessError):
  2539. pass
  2540. else:
  2541. o = filepath_from_subprocess_output(o)
  2542. return o
  2543. def calc_info(self):
  2544. config_exe = find_executable(self.get_config_exe())
  2545. if not config_exe:
  2546. log.warn('File not found: %s. Cannot determine %s info.' \
  2547. % (config_exe, self.section))
  2548. return
  2549. info = {}
  2550. macros = []
  2551. libraries = []
  2552. library_dirs = []
  2553. include_dirs = []
  2554. extra_link_args = []
  2555. extra_compile_args = []
  2556. version = self.get_config_output(config_exe, self.version_flag)
  2557. if version:
  2558. macros.append((self.__class__.__name__.split('.')[-1].upper(),
  2559. _c_string_literal(version)))
  2560. if self.version_macro_name:
  2561. macros.append((self.version_macro_name + '_%s'
  2562. % (version.replace('.', '_')), None))
  2563. if self.release_macro_name:
  2564. release = self.get_config_output(config_exe, '--release')
  2565. if release:
  2566. macros.append((self.release_macro_name + '_%s'
  2567. % (release.replace('.', '_')), None))
  2568. opts = self.get_config_output(config_exe, '--libs')
  2569. if opts:
  2570. for opt in opts.split():
  2571. if opt[:2] == '-l':
  2572. libraries.append(opt[2:])
  2573. elif opt[:2] == '-L':
  2574. library_dirs.append(opt[2:])
  2575. else:
  2576. extra_link_args.append(opt)
  2577. opts = self.get_config_output(config_exe, self.cflags_flag)
  2578. if opts:
  2579. for opt in opts.split():
  2580. if opt[:2] == '-I':
  2581. include_dirs.append(opt[2:])
  2582. elif opt[:2] == '-D':
  2583. if '=' in opt:
  2584. n, v = opt[2:].split('=')
  2585. macros.append((n, v))
  2586. else:
  2587. macros.append((opt[2:], None))
  2588. else:
  2589. extra_compile_args.append(opt)
  2590. if macros:
  2591. dict_append(info, define_macros=macros)
  2592. if libraries:
  2593. dict_append(info, libraries=libraries)
  2594. if library_dirs:
  2595. dict_append(info, library_dirs=library_dirs)
  2596. if include_dirs:
  2597. dict_append(info, include_dirs=include_dirs)
  2598. if extra_link_args:
  2599. dict_append(info, extra_link_args=extra_link_args)
  2600. if extra_compile_args:
  2601. dict_append(info, extra_compile_args=extra_compile_args)
  2602. if info:
  2603. self.set_info(**info)
  2604. return
  2605. class wx_info(_pkg_config_info):
  2606. section = 'wx'
  2607. config_env_var = 'WX_CONFIG'
  2608. default_config_exe = 'wx-config'
  2609. append_config_exe = ''
  2610. version_macro_name = 'WX_VERSION'
  2611. release_macro_name = 'WX_RELEASE'
  2612. version_flag = '--version'
  2613. cflags_flag = '--cxxflags'
  2614. class gdk_pixbuf_xlib_2_info(_pkg_config_info):
  2615. section = 'gdk_pixbuf_xlib_2'
  2616. append_config_exe = 'gdk-pixbuf-xlib-2.0'
  2617. version_macro_name = 'GDK_PIXBUF_XLIB_VERSION'
  2618. class gdk_pixbuf_2_info(_pkg_config_info):
  2619. section = 'gdk_pixbuf_2'
  2620. append_config_exe = 'gdk-pixbuf-2.0'
  2621. version_macro_name = 'GDK_PIXBUF_VERSION'
  2622. class gdk_x11_2_info(_pkg_config_info):
  2623. section = 'gdk_x11_2'
  2624. append_config_exe = 'gdk-x11-2.0'
  2625. version_macro_name = 'GDK_X11_VERSION'
  2626. class gdk_2_info(_pkg_config_info):
  2627. section = 'gdk_2'
  2628. append_config_exe = 'gdk-2.0'
  2629. version_macro_name = 'GDK_VERSION'
  2630. class gdk_info(_pkg_config_info):
  2631. section = 'gdk'
  2632. append_config_exe = 'gdk'
  2633. version_macro_name = 'GDK_VERSION'
  2634. class gtkp_x11_2_info(_pkg_config_info):
  2635. section = 'gtkp_x11_2'
  2636. append_config_exe = 'gtk+-x11-2.0'
  2637. version_macro_name = 'GTK_X11_VERSION'
  2638. class gtkp_2_info(_pkg_config_info):
  2639. section = 'gtkp_2'
  2640. append_config_exe = 'gtk+-2.0'
  2641. version_macro_name = 'GTK_VERSION'
  2642. class xft_info(_pkg_config_info):
  2643. section = 'xft'
  2644. append_config_exe = 'xft'
  2645. version_macro_name = 'XFT_VERSION'
  2646. class freetype2_info(_pkg_config_info):
  2647. section = 'freetype2'
  2648. append_config_exe = 'freetype2'
  2649. version_macro_name = 'FREETYPE2_VERSION'
  2650. class amd_info(system_info):
  2651. section = 'amd'
  2652. dir_env_var = 'AMD'
  2653. _lib_names = ['amd']
  2654. def calc_info(self):
  2655. lib_dirs = self.get_lib_dirs()
  2656. opt = self.get_option_single('amd_libs', 'libraries')
  2657. amd_libs = self.get_libs(opt, self._lib_names)
  2658. info = self.check_libs(lib_dirs, amd_libs, [])
  2659. if info is None:
  2660. return
  2661. include_dirs = self.get_include_dirs()
  2662. inc_dir = None
  2663. for d in include_dirs:
  2664. p = self.combine_paths(d, 'amd.h')
  2665. if p:
  2666. inc_dir = os.path.dirname(p[0])
  2667. break
  2668. if inc_dir is not None:
  2669. dict_append(info, include_dirs=[inc_dir],
  2670. define_macros=[('SCIPY_AMD_H', None)],
  2671. swig_opts=['-I' + inc_dir])
  2672. self.set_info(**info)
  2673. return
  2674. class umfpack_info(system_info):
  2675. section = 'umfpack'
  2676. dir_env_var = 'UMFPACK'
  2677. notfounderror = UmfpackNotFoundError
  2678. _lib_names = ['umfpack']
  2679. def calc_info(self):
  2680. lib_dirs = self.get_lib_dirs()
  2681. opt = self.get_option_single('umfpack_libs', 'libraries')
  2682. umfpack_libs = self.get_libs(opt, self._lib_names)
  2683. info = self.check_libs(lib_dirs, umfpack_libs, [])
  2684. if info is None:
  2685. return
  2686. include_dirs = self.get_include_dirs()
  2687. inc_dir = None
  2688. for d in include_dirs:
  2689. p = self.combine_paths(d, ['', 'umfpack'], 'umfpack.h')
  2690. if p:
  2691. inc_dir = os.path.dirname(p[0])
  2692. break
  2693. if inc_dir is not None:
  2694. dict_append(info, include_dirs=[inc_dir],
  2695. define_macros=[('SCIPY_UMFPACK_H', None)],
  2696. swig_opts=['-I' + inc_dir])
  2697. dict_append(info, **get_info('amd'))
  2698. self.set_info(**info)
  2699. return
  2700. def combine_paths(*args, **kws):
  2701. """ Return a list of existing paths composed by all combinations of
  2702. items from arguments.
  2703. """
  2704. r = []
  2705. for a in args:
  2706. if not a:
  2707. continue
  2708. if is_string(a):
  2709. a = [a]
  2710. r.append(a)
  2711. args = r
  2712. if not args:
  2713. return []
  2714. if len(args) == 1:
  2715. result = reduce(lambda a, b: a + b, map(glob, args[0]), [])
  2716. elif len(args) == 2:
  2717. result = []
  2718. for a0 in args[0]:
  2719. for a1 in args[1]:
  2720. result.extend(glob(os.path.join(a0, a1)))
  2721. else:
  2722. result = combine_paths(*(combine_paths(args[0], args[1]) + args[2:]))
  2723. log.debug('(paths: %s)', ','.join(result))
  2724. return result
  2725. language_map = {'c': 0, 'c++': 1, 'f77': 2, 'f90': 3}
  2726. inv_language_map = {0: 'c', 1: 'c++', 2: 'f77', 3: 'f90'}
  2727. def dict_append(d, **kws):
  2728. languages = []
  2729. for k, v in kws.items():
  2730. if k == 'language':
  2731. languages.append(v)
  2732. continue
  2733. if k in d:
  2734. if k in ['library_dirs', 'include_dirs',
  2735. 'extra_compile_args', 'extra_link_args',
  2736. 'runtime_library_dirs', 'define_macros']:
  2737. [d[k].append(vv) for vv in v if vv not in d[k]]
  2738. else:
  2739. d[k].extend(v)
  2740. else:
  2741. d[k] = v
  2742. if languages:
  2743. l = inv_language_map[max([language_map.get(l, 0) for l in languages])]
  2744. d['language'] = l
  2745. return
  2746. def parseCmdLine(argv=(None,)):
  2747. import optparse
  2748. parser = optparse.OptionParser("usage: %prog [-v] [info objs]")
  2749. parser.add_option('-v', '--verbose', action='store_true', dest='verbose',
  2750. default=False,
  2751. help='be verbose and print more messages')
  2752. opts, args = parser.parse_args(args=argv[1:])
  2753. return opts, args
  2754. def show_all(argv=None):
  2755. import inspect
  2756. if argv is None:
  2757. argv = sys.argv
  2758. opts, args = parseCmdLine(argv)
  2759. if opts.verbose:
  2760. log.set_threshold(log.DEBUG)
  2761. else:
  2762. log.set_threshold(log.INFO)
  2763. show_only = []
  2764. for n in args:
  2765. if n[-5:] != '_info':
  2766. n = n + '_info'
  2767. show_only.append(n)
  2768. show_all = not show_only
  2769. _gdict_ = globals().copy()
  2770. for name, c in _gdict_.items():
  2771. if not inspect.isclass(c):
  2772. continue
  2773. if not issubclass(c, system_info) or c is system_info:
  2774. continue
  2775. if not show_all:
  2776. if name not in show_only:
  2777. continue
  2778. del show_only[show_only.index(name)]
  2779. conf = c()
  2780. conf.verbosity = 2
  2781. # we don't need the result, but we want
  2782. # the side effect of printing diagnostics
  2783. conf.get_info()
  2784. if show_only:
  2785. log.info('Info classes not defined: %s', ','.join(show_only))
  2786. if __name__ == "__main__":
  2787. show_all()