Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1""" 

2Low-level BLAS functions (:mod:`scipy.linalg.blas`) 

3=================================================== 

4 

5This module contains low-level functions from the BLAS library. 

6 

7.. versionadded:: 0.12.0 

8 

9.. note:: 

10 

11 The common ``overwrite_<>`` option in many routines, allows the 

12 input arrays to be overwritten to avoid extra memory allocation. 

13 However this requires the array to satisfy two conditions 

14 which are memory order and the data type to match exactly the 

15 order and the type expected by the routine. 

16 

17 As an example, if you pass a double precision float array to any 

18 ``S....`` routine which expects single precision arguments, f2py 

19 will create an intermediate array to match the argument types and 

20 overwriting will be performed on that intermediate array. 

21 

22 Similarly, if a C-contiguous array is passed, f2py will pass a 

23 FORTRAN-contiguous array internally. Please make sure that these 

24 details are satisfied. More information can be found in the f2py 

25 documentation. 

26 

27.. warning:: 

28 

29 These functions do little to no error checking. 

30 It is possible to cause crashes by mis-using them, 

31 so prefer using the higher-level routines in `scipy.linalg`. 

32 

33Finding functions 

34----------------- 

35 

36.. autosummary:: 

37 :toctree: generated/ 

38 

39 get_blas_funcs 

40 find_best_blas_type 

41 

42BLAS Level 1 functions 

43---------------------- 

44 

45.. autosummary:: 

46 :toctree: generated/ 

47 

48 caxpy 

49 ccopy 

50 cdotc 

51 cdotu 

52 crotg 

53 cscal 

54 csrot 

55 csscal 

56 cswap 

57 dasum 

58 daxpy 

59 dcopy 

60 ddot 

61 dnrm2 

62 drot 

63 drotg 

64 drotm 

65 drotmg 

66 dscal 

67 dswap 

68 dzasum 

69 dznrm2 

70 icamax 

71 idamax 

72 isamax 

73 izamax 

74 sasum 

75 saxpy 

76 scasum 

77 scnrm2 

78 scopy 

79 sdot 

80 snrm2 

81 srot 

82 srotg 

83 srotm 

84 srotmg 

85 sscal 

86 sswap 

87 zaxpy 

88 zcopy 

89 zdotc 

90 zdotu 

91 zdrot 

92 zdscal 

93 zrotg 

94 zscal 

95 zswap 

96 

97BLAS Level 2 functions 

98---------------------- 

99 

100.. autosummary:: 

101 :toctree: generated/ 

102 

103 sgbmv 

104 sgemv 

105 sger 

106 ssbmv 

107 sspr 

108 sspr2 

109 ssymv 

110 ssyr 

111 ssyr2 

112 stbmv 

113 stpsv 

114 strmv 

115 strsv 

116 dgbmv 

117 dgemv 

118 dger 

119 dsbmv 

120 dspr 

121 dspr2 

122 dsymv 

123 dsyr 

124 dsyr2 

125 dtbmv 

126 dtpsv 

127 dtrmv 

128 dtrsv 

129 cgbmv 

130 cgemv 

131 cgerc 

132 cgeru 

133 chbmv 

134 chemv 

135 cher 

136 cher2 

137 chpmv 

138 chpr 

139 chpr2 

140 ctbmv 

141 ctbsv 

142 ctpmv 

143 ctpsv 

144 ctrmv 

145 ctrsv 

146 csyr 

147 zgbmv 

148 zgemv 

149 zgerc 

150 zgeru 

151 zhbmv 

152 zhemv 

153 zher 

154 zher2 

155 zhpmv 

156 zhpr 

157 zhpr2 

158 ztbmv 

159 ztbsv 

160 ztpmv 

161 ztrmv 

162 ztrsv 

163 zsyr 

164 

165BLAS Level 3 functions 

166---------------------- 

167 

168.. autosummary:: 

169 :toctree: generated/ 

170 

171 sgemm 

172 ssymm 

173 ssyr2k 

174 ssyrk 

175 strmm 

176 strsm 

177 dgemm 

178 dsymm 

179 dsyr2k 

180 dsyrk 

181 dtrmm 

182 dtrsm 

183 cgemm 

184 chemm 

185 cher2k 

186 cherk 

187 csymm 

188 csyr2k 

189 csyrk 

190 ctrmm 

191 ctrsm 

192 zgemm 

193 zhemm 

194 zher2k 

195 zherk 

196 zsymm 

197 zsyr2k 

198 zsyrk 

199 ztrmm 

200 ztrsm 

201 

202""" 

203# 

204# Author: Pearu Peterson, March 2002 

205# refactoring by Fabian Pedregosa, March 2010 

206# 

207 

208__all__ = ['get_blas_funcs', 'find_best_blas_type'] 

209 

210import numpy as _np 

211import functools 

212 

213from scipy.linalg import _fblas 

214try: 

215 from scipy.linalg import _cblas 

216except ImportError: 

217 _cblas = None 

218 

219# Expose all functions (only fblas --- cblas is an implementation detail) 

220empty_module = None 

221from scipy.linalg._fblas import * 

222del empty_module 

223 

224# all numeric dtypes '?bBhHiIlLqQefdgFDGO' that are safe to be converted to 

225 

226# single precision float : '?bBhH!!!!!!ef!!!!!!' 

227# double precision float : '?bBhHiIlLqQefdg!!!!' 

228# single precision complex : '?bBhH!!!!!!ef!!F!!!' 

229# double precision complex : '?bBhHiIlLqQefdgFDG!' 

230 

231_type_score = {x: 1 for x in '?bBhHef'} 

232_type_score.update({x: 2 for x in 'iIlLqQd'}) 

233 

234# Handle float128(g) and complex256(G) separately in case non-Windows systems. 

235# On Windows, the values will be rewritten to the same key with the same value. 

236_type_score.update({'F': 3, 'D': 4, 'g': 2, 'G': 4}) 

237 

238# Final mapping to the actual prefixes and dtypes 

239_type_conv = {1: ('s', _np.dtype('float32')), 

240 2: ('d', _np.dtype('float64')), 

241 3: ('c', _np.dtype('complex64')), 

242 4: ('z', _np.dtype('complex128'))} 

243 

244# some convenience alias for complex functions 

245_blas_alias = {'cnrm2': 'scnrm2', 'znrm2': 'dznrm2', 

246 'cdot': 'cdotc', 'zdot': 'zdotc', 

247 'cger': 'cgerc', 'zger': 'zgerc', 

248 'sdotc': 'sdot', 'sdotu': 'sdot', 

249 'ddotc': 'ddot', 'ddotu': 'ddot'} 

250 

251 

252def find_best_blas_type(arrays=(), dtype=None): 

253 """Find best-matching BLAS/LAPACK type. 

254 

255 Arrays are used to determine the optimal prefix of BLAS routines. 

256 

257 Parameters 

258 ---------- 

259 arrays : sequence of ndarrays, optional 

260 Arrays can be given to determine optimal prefix of BLAS 

261 routines. If not given, double-precision routines will be 

262 used, otherwise the most generic type in arrays will be used. 

263 dtype : str or dtype, optional 

264 Data-type specifier. Not used if `arrays` is non-empty. 

265 

266 Returns 

267 ------- 

268 prefix : str 

269 BLAS/LAPACK prefix character. 

270 dtype : dtype 

271 Inferred Numpy data type. 

272 prefer_fortran : bool 

273 Whether to prefer Fortran order routines over C order. 

274 

275 Examples 

276 -------- 

277 >>> import scipy.linalg.blas as bla 

278 >>> a = np.random.rand(10,15) 

279 >>> b = np.asfortranarray(a) # Change the memory layout order 

280 >>> bla.find_best_blas_type((a,)) 

281 ('d', dtype('float64'), False) 

282 >>> bla.find_best_blas_type((a*1j,)) 

283 ('z', dtype('complex128'), False) 

284 >>> bla.find_best_blas_type((b,)) 

285 ('d', dtype('float64'), True) 

286 

287 """ 

288 dtype = _np.dtype(dtype) 

289 max_score = _type_score.get(dtype.char, 5) 

290 prefer_fortran = False 

291 

292 if arrays: 

293 # In most cases, single element is passed through, quicker route 

294 if len(arrays) == 1: 

295 max_score = _type_score.get(arrays[0].dtype.char, 5) 

296 prefer_fortran = arrays[0].flags['FORTRAN'] 

297 else: 

298 # use the most generic type in arrays 

299 scores = [_type_score.get(x.dtype.char, 5) for x in arrays] 

300 max_score = max(scores) 

301 ind_max_score = scores.index(max_score) 

302 # safe upcasting for mix of float64 and complex64 --> prefix 'z' 

303 if max_score == 3 and (2 in scores): 

304 max_score = 4 

305 

306 if arrays[ind_max_score].flags['FORTRAN']: 

307 # prefer Fortran for leading array with column major order 

308 prefer_fortran = True 

309 

310 # Get the LAPACK prefix and the corresponding dtype if not fall back 

311 # to 'd' and double precision float. 

312 prefix, dtype = _type_conv.get(max_score, ('d', _np.dtype('float64'))) 

313 

314 return prefix, dtype, prefer_fortran 

315 

316 

317def _get_funcs(names, arrays, dtype, 

318 lib_name, fmodule, cmodule, 

319 fmodule_name, cmodule_name, alias): 

320 """ 

321 Return available BLAS/LAPACK functions. 

322 

323 Used also in lapack.py. See get_blas_funcs for docstring. 

324 """ 

325 

326 funcs = [] 

327 unpack = False 

328 dtype = _np.dtype(dtype) 

329 module1 = (cmodule, cmodule_name) 

330 module2 = (fmodule, fmodule_name) 

331 

332 if isinstance(names, str): 

333 names = (names,) 

334 unpack = True 

335 

336 prefix, dtype, prefer_fortran = find_best_blas_type(arrays, dtype) 

337 

338 if prefer_fortran: 

339 module1, module2 = module2, module1 

340 

341 for name in names: 

342 func_name = prefix + name 

343 func_name = alias.get(func_name, func_name) 

344 func = getattr(module1[0], func_name, None) 

345 module_name = module1[1] 

346 if func is None: 

347 func = getattr(module2[0], func_name, None) 

348 module_name = module2[1] 

349 if func is None: 

350 raise ValueError( 

351 '%s function %s could not be found' % (lib_name, func_name)) 

352 func.module_name, func.typecode = module_name, prefix 

353 func.dtype = dtype 

354 func.prefix = prefix # Backward compatibility 

355 funcs.append(func) 

356 

357 if unpack: 

358 return funcs[0] 

359 else: 

360 return funcs 

361 

362 

363def _memoize_get_funcs(func): 

364 """ 

365 Memoized fast path for _get_funcs instances 

366 """ 

367 memo = {} 

368 func.memo = memo 

369 

370 @functools.wraps(func) 

371 def getter(names, arrays=(), dtype=None): 

372 key = (names, dtype) 

373 for array in arrays: 

374 # cf. find_blas_funcs 

375 key += (array.dtype.char, array.flags.fortran) 

376 

377 try: 

378 value = memo.get(key) 

379 except TypeError: 

380 # unhashable key etc. 

381 key = None 

382 value = None 

383 

384 if value is not None: 

385 return value 

386 

387 value = func(names, arrays, dtype) 

388 

389 if key is not None: 

390 memo[key] = value 

391 

392 return value 

393 

394 return getter 

395 

396 

397@_memoize_get_funcs 

398def get_blas_funcs(names, arrays=(), dtype=None): 

399 """Return available BLAS function objects from names. 

400 

401 Arrays are used to determine the optimal prefix of BLAS routines. 

402 

403 Parameters 

404 ---------- 

405 names : str or sequence of str 

406 Name(s) of BLAS functions without type prefix. 

407 

408 arrays : sequence of ndarrays, optional 

409 Arrays can be given to determine optimal prefix of BLAS 

410 routines. If not given, double-precision routines will be 

411 used, otherwise the most generic type in arrays will be used. 

412 

413 dtype : str or dtype, optional 

414 Data-type specifier. Not used if `arrays` is non-empty. 

415 

416 

417 Returns 

418 ------- 

419 funcs : list 

420 List containing the found function(s). 

421 

422 

423 Notes 

424 ----- 

425 This routine automatically chooses between Fortran/C 

426 interfaces. Fortran code is used whenever possible for arrays with 

427 column major order. In all other cases, C code is preferred. 

428 

429 In BLAS, the naming convention is that all functions start with a 

430 type prefix, which depends on the type of the principal 

431 matrix. These can be one of {'s', 'd', 'c', 'z'} for the NumPy 

432 types {float32, float64, complex64, complex128} respectively. 

433 The code and the dtype are stored in attributes `typecode` and `dtype` 

434 of the returned functions. 

435 

436 Examples 

437 -------- 

438 >>> import scipy.linalg as LA 

439 >>> a = np.random.rand(3,2) 

440 >>> x_gemv = LA.get_blas_funcs('gemv', (a,)) 

441 >>> x_gemv.typecode 

442 'd' 

443 >>> x_gemv = LA.get_blas_funcs('gemv',(a*1j,)) 

444 >>> x_gemv.typecode 

445 'z' 

446 

447 """ 

448 return _get_funcs(names, arrays, dtype, 

449 "BLAS", _fblas, _cblas, "fblas", "cblas", 

450 _blas_alias)