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"""Automatically adapted for numpy Sep 19, 2005 by convertcode.py 

2 

3""" 

4import functools 

5import warnings 

6 

7__all__ = ['iscomplexobj', 'isrealobj', 'imag', 'iscomplex', 

8 'isreal', 'nan_to_num', 'real', 'real_if_close', 

9 'typename', 'asfarray', 'mintypecode', 'asscalar', 

10 'common_type'] 

11 

12import numpy.core.numeric as _nx 

13from numpy.core.numeric import asarray, asanyarray, isnan, zeros 

14from numpy.core.overrides import set_module 

15from numpy.core import overrides 

16from .ufunclike import isneginf, isposinf 

17 

18 

19array_function_dispatch = functools.partial( 

20 overrides.array_function_dispatch, module='numpy') 

21 

22 

23_typecodes_by_elsize = 'GDFgdfQqLlIiHhBb?' 

24 

25 

26@set_module('numpy') 

27def mintypecode(typechars, typeset='GDFgdf', default='d'): 

28 """ 

29 Return the character for the minimum-size type to which given types can 

30 be safely cast. 

31 

32 The returned type character must represent the smallest size dtype such 

33 that an array of the returned type can handle the data from an array of 

34 all types in `typechars` (or if `typechars` is an array, then its 

35 dtype.char). 

36 

37 Parameters 

38 ---------- 

39 typechars : list of str or array_like 

40 If a list of strings, each string should represent a dtype. 

41 If array_like, the character representation of the array dtype is used. 

42 typeset : str or list of str, optional 

43 The set of characters that the returned character is chosen from. 

44 The default set is 'GDFgdf'. 

45 default : str, optional 

46 The default character, this is returned if none of the characters in 

47 `typechars` matches a character in `typeset`. 

48 

49 Returns 

50 ------- 

51 typechar : str 

52 The character representing the minimum-size type that was found. 

53 

54 See Also 

55 -------- 

56 dtype, sctype2char, maximum_sctype 

57 

58 Examples 

59 -------- 

60 >>> np.mintypecode(['d', 'f', 'S']) 

61 'd' 

62 >>> x = np.array([1.1, 2-3.j]) 

63 >>> np.mintypecode(x) 

64 'D' 

65 

66 >>> np.mintypecode('abceh', default='G') 

67 'G' 

68 

69 """ 

70 typecodes = ((isinstance(t, str) and t) or asarray(t).dtype.char 

71 for t in typechars) 

72 intersection = set(t for t in typecodes if t in typeset) 

73 if not intersection: 

74 return default 

75 if 'F' in intersection and 'd' in intersection: 

76 return 'D' 

77 return min(intersection, key=_typecodes_by_elsize.index) 

78 

79 

80def _asfarray_dispatcher(a, dtype=None): 

81 return (a,) 

82 

83 

84@array_function_dispatch(_asfarray_dispatcher) 

85def asfarray(a, dtype=_nx.float_): 

86 """ 

87 Return an array converted to a float type. 

88 

89 Parameters 

90 ---------- 

91 a : array_like 

92 The input array. 

93 dtype : str or dtype object, optional 

94 Float type code to coerce input array `a`. If `dtype` is one of the 

95 'int' dtypes, it is replaced with float64. 

96 

97 Returns 

98 ------- 

99 out : ndarray 

100 The input `a` as a float ndarray. 

101 

102 Examples 

103 -------- 

104 >>> np.asfarray([2, 3]) 

105 array([2., 3.]) 

106 >>> np.asfarray([2, 3], dtype='float') 

107 array([2., 3.]) 

108 >>> np.asfarray([2, 3], dtype='int8') 

109 array([2., 3.]) 

110 

111 """ 

112 if not _nx.issubdtype(dtype, _nx.inexact): 

113 dtype = _nx.float_ 

114 return asarray(a, dtype=dtype) 

115 

116 

117def _real_dispatcher(val): 

118 return (val,) 

119 

120 

121@array_function_dispatch(_real_dispatcher) 

122def real(val): 

123 """ 

124 Return the real part of the complex argument. 

125 

126 Parameters 

127 ---------- 

128 val : array_like 

129 Input array. 

130 

131 Returns 

132 ------- 

133 out : ndarray or scalar 

134 The real component of the complex argument. If `val` is real, the type 

135 of `val` is used for the output. If `val` has complex elements, the 

136 returned type is float. 

137 

138 See Also 

139 -------- 

140 real_if_close, imag, angle 

141 

142 Examples 

143 -------- 

144 >>> a = np.array([1+2j, 3+4j, 5+6j]) 

145 >>> a.real 

146 array([1., 3., 5.]) 

147 >>> a.real = 9 

148 >>> a 

149 array([9.+2.j, 9.+4.j, 9.+6.j]) 

150 >>> a.real = np.array([9, 8, 7]) 

151 >>> a 

152 array([9.+2.j, 8.+4.j, 7.+6.j]) 

153 >>> np.real(1 + 1j) 

154 1.0 

155 

156 """ 

157 try: 

158 return val.real 

159 except AttributeError: 

160 return asanyarray(val).real 

161 

162 

163def _imag_dispatcher(val): 

164 return (val,) 

165 

166 

167@array_function_dispatch(_imag_dispatcher) 

168def imag(val): 

169 """ 

170 Return the imaginary part of the complex argument. 

171 

172 Parameters 

173 ---------- 

174 val : array_like 

175 Input array. 

176 

177 Returns 

178 ------- 

179 out : ndarray or scalar 

180 The imaginary component of the complex argument. If `val` is real, 

181 the type of `val` is used for the output. If `val` has complex 

182 elements, the returned type is float. 

183 

184 See Also 

185 -------- 

186 real, angle, real_if_close 

187 

188 Examples 

189 -------- 

190 >>> a = np.array([1+2j, 3+4j, 5+6j]) 

191 >>> a.imag 

192 array([2., 4., 6.]) 

193 >>> a.imag = np.array([8, 10, 12]) 

194 >>> a 

195 array([1. +8.j, 3.+10.j, 5.+12.j]) 

196 >>> np.imag(1 + 1j) 

197 1.0 

198 

199 """ 

200 try: 

201 return val.imag 

202 except AttributeError: 

203 return asanyarray(val).imag 

204 

205 

206def _is_type_dispatcher(x): 

207 return (x,) 

208 

209 

210@array_function_dispatch(_is_type_dispatcher) 

211def iscomplex(x): 

212 """ 

213 Returns a bool array, where True if input element is complex. 

214 

215 What is tested is whether the input has a non-zero imaginary part, not if 

216 the input type is complex. 

217 

218 Parameters 

219 ---------- 

220 x : array_like 

221 Input array. 

222 

223 Returns 

224 ------- 

225 out : ndarray of bools 

226 Output array. 

227 

228 See Also 

229 -------- 

230 isreal 

231 iscomplexobj : Return True if x is a complex type or an array of complex 

232 numbers. 

233 

234 Examples 

235 -------- 

236 >>> np.iscomplex([1+1j, 1+0j, 4.5, 3, 2, 2j]) 

237 array([ True, False, False, False, False, True]) 

238 

239 """ 

240 ax = asanyarray(x) 

241 if issubclass(ax.dtype.type, _nx.complexfloating): 

242 return ax.imag != 0 

243 res = zeros(ax.shape, bool) 

244 return res[()] # convert to scalar if needed 

245 

246 

247@array_function_dispatch(_is_type_dispatcher) 

248def isreal(x): 

249 """ 

250 Returns a bool array, where True if input element is real. 

251 

252 If element has complex type with zero complex part, the return value 

253 for that element is True. 

254 

255 Parameters 

256 ---------- 

257 x : array_like 

258 Input array. 

259 

260 Returns 

261 ------- 

262 out : ndarray, bool 

263 Boolean array of same shape as `x`. 

264 

265 See Also 

266 -------- 

267 iscomplex 

268 isrealobj : Return True if x is not a complex type. 

269 

270 Examples 

271 -------- 

272 >>> np.isreal([1+1j, 1+0j, 4.5, 3, 2, 2j]) 

273 array([False, True, True, True, True, False]) 

274 

275 """ 

276 return imag(x) == 0 

277 

278 

279@array_function_dispatch(_is_type_dispatcher) 

280def iscomplexobj(x): 

281 """ 

282 Check for a complex type or an array of complex numbers. 

283 

284 The type of the input is checked, not the value. Even if the input 

285 has an imaginary part equal to zero, `iscomplexobj` evaluates to True. 

286 

287 Parameters 

288 ---------- 

289 x : any 

290 The input can be of any type and shape. 

291 

292 Returns 

293 ------- 

294 iscomplexobj : bool 

295 The return value, True if `x` is of a complex type or has at least 

296 one complex element. 

297 

298 See Also 

299 -------- 

300 isrealobj, iscomplex 

301 

302 Examples 

303 -------- 

304 >>> np.iscomplexobj(1) 

305 False 

306 >>> np.iscomplexobj(1+0j) 

307 True 

308 >>> np.iscomplexobj([3, 1+0j, True]) 

309 True 

310 

311 """ 

312 try: 

313 dtype = x.dtype 

314 type_ = dtype.type 

315 except AttributeError: 

316 type_ = asarray(x).dtype.type 

317 return issubclass(type_, _nx.complexfloating) 

318 

319 

320@array_function_dispatch(_is_type_dispatcher) 

321def isrealobj(x): 

322 """ 

323 Return True if x is a not complex type or an array of complex numbers. 

324 

325 The type of the input is checked, not the value. So even if the input 

326 has an imaginary part equal to zero, `isrealobj` evaluates to False 

327 if the data type is complex. 

328 

329 Parameters 

330 ---------- 

331 x : any 

332 The input can be of any type and shape. 

333 

334 Returns 

335 ------- 

336 y : bool 

337 The return value, False if `x` is of a complex type. 

338 

339 See Also 

340 -------- 

341 iscomplexobj, isreal 

342 

343 Examples 

344 -------- 

345 >>> np.isrealobj(1) 

346 True 

347 >>> np.isrealobj(1+0j) 

348 False 

349 >>> np.isrealobj([3, 1+0j, True]) 

350 False 

351 

352 """ 

353 return not iscomplexobj(x) 

354 

355#----------------------------------------------------------------------------- 

356 

357def _getmaxmin(t): 

358 from numpy.core import getlimits 

359 f = getlimits.finfo(t) 

360 return f.max, f.min 

361 

362 

363def _nan_to_num_dispatcher(x, copy=None, nan=None, posinf=None, neginf=None): 

364 return (x,) 

365 

366 

367@array_function_dispatch(_nan_to_num_dispatcher) 

368def nan_to_num(x, copy=True, nan=0.0, posinf=None, neginf=None): 

369 """ 

370 Replace NaN with zero and infinity with large finite numbers (default 

371 behaviour) or with the numbers defined by the user using the `nan`,  

372 `posinf` and/or `neginf` keywords. 

373 

374 If `x` is inexact, NaN is replaced by zero or by the user defined value in 

375 `nan` keyword, infinity is replaced by the largest finite floating point  

376 values representable by ``x.dtype`` or by the user defined value in  

377 `posinf` keyword and -infinity is replaced by the most negative finite  

378 floating point values representable by ``x.dtype`` or by the user defined  

379 value in `neginf` keyword. 

380 

381 For complex dtypes, the above is applied to each of the real and 

382 imaginary components of `x` separately. 

383 

384 If `x` is not inexact, then no replacements are made. 

385 

386 Parameters 

387 ---------- 

388 x : scalar or array_like 

389 Input data. 

390 copy : bool, optional 

391 Whether to create a copy of `x` (True) or to replace values 

392 in-place (False). The in-place operation only occurs if 

393 casting to an array does not require a copy. 

394 Default is True. 

395  

396 .. versionadded:: 1.13 

397 nan : int, float, optional 

398 Value to be used to fill NaN values. If no value is passed  

399 then NaN values will be replaced with 0.0. 

400  

401 .. versionadded:: 1.17 

402 posinf : int, float, optional 

403 Value to be used to fill positive infinity values. If no value is  

404 passed then positive infinity values will be replaced with a very 

405 large number. 

406  

407 .. versionadded:: 1.17 

408 neginf : int, float, optional 

409 Value to be used to fill negative infinity values. If no value is  

410 passed then negative infinity values will be replaced with a very 

411 small (or negative) number. 

412  

413 .. versionadded:: 1.17 

414 

415  

416 

417 Returns 

418 ------- 

419 out : ndarray 

420 `x`, with the non-finite values replaced. If `copy` is False, this may 

421 be `x` itself. 

422 

423 See Also 

424 -------- 

425 isinf : Shows which elements are positive or negative infinity. 

426 isneginf : Shows which elements are negative infinity. 

427 isposinf : Shows which elements are positive infinity. 

428 isnan : Shows which elements are Not a Number (NaN). 

429 isfinite : Shows which elements are finite (not NaN, not infinity) 

430 

431 Notes 

432 ----- 

433 NumPy uses the IEEE Standard for Binary Floating-Point for Arithmetic 

434 (IEEE 754). This means that Not a Number is not equivalent to infinity. 

435 

436 Examples 

437 -------- 

438 >>> np.nan_to_num(np.inf) 

439 1.7976931348623157e+308 

440 >>> np.nan_to_num(-np.inf) 

441 -1.7976931348623157e+308 

442 >>> np.nan_to_num(np.nan) 

443 0.0 

444 >>> x = np.array([np.inf, -np.inf, np.nan, -128, 128]) 

445 >>> np.nan_to_num(x) 

446 array([ 1.79769313e+308, -1.79769313e+308, 0.00000000e+000, # may vary 

447 -1.28000000e+002, 1.28000000e+002]) 

448 >>> np.nan_to_num(x, nan=-9999, posinf=33333333, neginf=33333333) 

449 array([ 3.3333333e+07, 3.3333333e+07, -9.9990000e+03,  

450 -1.2800000e+02, 1.2800000e+02]) 

451 >>> y = np.array([complex(np.inf, np.nan), np.nan, complex(np.nan, np.inf)]) 

452 array([ 1.79769313e+308, -1.79769313e+308, 0.00000000e+000, # may vary 

453 -1.28000000e+002, 1.28000000e+002]) 

454 >>> np.nan_to_num(y) 

455 array([ 1.79769313e+308 +0.00000000e+000j, # may vary 

456 0.00000000e+000 +0.00000000e+000j, 

457 0.00000000e+000 +1.79769313e+308j]) 

458 >>> np.nan_to_num(y, nan=111111, posinf=222222) 

459 array([222222.+111111.j, 111111. +0.j, 111111.+222222.j]) 

460 """ 

461 x = _nx.array(x, subok=True, copy=copy) 

462 xtype = x.dtype.type 

463 

464 isscalar = (x.ndim == 0) 

465 

466 if not issubclass(xtype, _nx.inexact): 

467 return x[()] if isscalar else x 

468 

469 iscomplex = issubclass(xtype, _nx.complexfloating) 

470 

471 dest = (x.real, x.imag) if iscomplex else (x,) 

472 maxf, minf = _getmaxmin(x.real.dtype) 

473 if posinf is not None: 

474 maxf = posinf 

475 if neginf is not None: 

476 minf = neginf 

477 for d in dest: 

478 idx_nan = isnan(d) 

479 idx_posinf = isposinf(d) 

480 idx_neginf = isneginf(d) 

481 _nx.copyto(d, nan, where=idx_nan) 

482 _nx.copyto(d, maxf, where=idx_posinf) 

483 _nx.copyto(d, minf, where=idx_neginf) 

484 return x[()] if isscalar else x 

485 

486#----------------------------------------------------------------------------- 

487 

488def _real_if_close_dispatcher(a, tol=None): 

489 return (a,) 

490 

491 

492@array_function_dispatch(_real_if_close_dispatcher) 

493def real_if_close(a, tol=100): 

494 """ 

495 If input is complex with all imaginary parts close to zero, return  

496 real parts. 

497 

498 "Close to zero" is defined as `tol` * (machine epsilon of the type for 

499 `a`). 

500 

501 Parameters 

502 ---------- 

503 a : array_like 

504 Input array. 

505 tol : float 

506 Tolerance in machine epsilons for the complex part of the elements 

507 in the array. 

508 

509 Returns 

510 ------- 

511 out : ndarray 

512 If `a` is real, the type of `a` is used for the output. If `a` 

513 has complex elements, the returned type is float. 

514 

515 See Also 

516 -------- 

517 real, imag, angle 

518 

519 Notes 

520 ----- 

521 Machine epsilon varies from machine to machine and between data types 

522 but Python floats on most platforms have a machine epsilon equal to 

523 2.2204460492503131e-16. You can use 'np.finfo(float).eps' to print 

524 out the machine epsilon for floats. 

525 

526 Examples 

527 -------- 

528 >>> np.finfo(float).eps 

529 2.2204460492503131e-16 # may vary 

530 

531 >>> np.real_if_close([2.1 + 4e-14j, 5.2 + 3e-15j], tol=1000) 

532 array([2.1, 5.2]) 

533 >>> np.real_if_close([2.1 + 4e-13j, 5.2 + 3e-15j], tol=1000) 

534 array([2.1+4.e-13j, 5.2 + 3e-15j]) 

535 

536 """ 

537 a = asanyarray(a) 

538 if not issubclass(a.dtype.type, _nx.complexfloating): 

539 return a 

540 if tol > 1: 

541 from numpy.core import getlimits 

542 f = getlimits.finfo(a.dtype.type) 

543 tol = f.eps * tol 

544 if _nx.all(_nx.absolute(a.imag) < tol): 

545 a = a.real 

546 return a 

547 

548 

549def _asscalar_dispatcher(a): 

550 # 2018-10-10, 1.16 

551 warnings.warn('np.asscalar(a) is deprecated since NumPy v1.16, use ' 

552 'a.item() instead', DeprecationWarning, stacklevel=3) 

553 return (a,) 

554 

555 

556@array_function_dispatch(_asscalar_dispatcher) 

557def asscalar(a): 

558 """ 

559 Convert an array of size 1 to its scalar equivalent. 

560 

561 .. deprecated:: 1.16 

562 

563 Deprecated, use `numpy.ndarray.item()` instead. 

564 

565 Parameters 

566 ---------- 

567 a : ndarray 

568 Input array of size 1. 

569 

570 Returns 

571 ------- 

572 out : scalar 

573 Scalar representation of `a`. The output data type is the same type 

574 returned by the input's `item` method. 

575 

576 Examples 

577 -------- 

578 >>> np.asscalar(np.array([24])) 

579 24 

580 """ 

581 return a.item() 

582 

583#----------------------------------------------------------------------------- 

584 

585_namefromtype = {'S1': 'character', 

586 '?': 'bool', 

587 'b': 'signed char', 

588 'B': 'unsigned char', 

589 'h': 'short', 

590 'H': 'unsigned short', 

591 'i': 'integer', 

592 'I': 'unsigned integer', 

593 'l': 'long integer', 

594 'L': 'unsigned long integer', 

595 'q': 'long long integer', 

596 'Q': 'unsigned long long integer', 

597 'f': 'single precision', 

598 'd': 'double precision', 

599 'g': 'long precision', 

600 'F': 'complex single precision', 

601 'D': 'complex double precision', 

602 'G': 'complex long double precision', 

603 'S': 'string', 

604 'U': 'unicode', 

605 'V': 'void', 

606 'O': 'object' 

607 } 

608 

609@set_module('numpy') 

610def typename(char): 

611 """ 

612 Return a description for the given data type code. 

613 

614 Parameters 

615 ---------- 

616 char : str 

617 Data type code. 

618 

619 Returns 

620 ------- 

621 out : str 

622 Description of the input data type code. 

623 

624 See Also 

625 -------- 

626 dtype, typecodes 

627 

628 Examples 

629 -------- 

630 >>> typechars = ['S1', '?', 'B', 'D', 'G', 'F', 'I', 'H', 'L', 'O', 'Q', 

631 ... 'S', 'U', 'V', 'b', 'd', 'g', 'f', 'i', 'h', 'l', 'q'] 

632 >>> for typechar in typechars: 

633 ... print(typechar, ' : ', np.typename(typechar)) 

634 ... 

635 S1 : character 

636 ? : bool 

637 B : unsigned char 

638 D : complex double precision 

639 G : complex long double precision 

640 F : complex single precision 

641 I : unsigned integer 

642 H : unsigned short 

643 L : unsigned long integer 

644 O : object 

645 Q : unsigned long long integer 

646 S : string 

647 U : unicode 

648 V : void 

649 b : signed char 

650 d : double precision 

651 g : long precision 

652 f : single precision 

653 i : integer 

654 h : short 

655 l : long integer 

656 q : long long integer 

657 

658 """ 

659 return _namefromtype[char] 

660 

661#----------------------------------------------------------------------------- 

662 

663#determine the "minimum common type" for a group of arrays. 

664array_type = [[_nx.half, _nx.single, _nx.double, _nx.longdouble], 

665 [None, _nx.csingle, _nx.cdouble, _nx.clongdouble]] 

666array_precision = {_nx.half: 0, 

667 _nx.single: 1, 

668 _nx.double: 2, 

669 _nx.longdouble: 3, 

670 _nx.csingle: 1, 

671 _nx.cdouble: 2, 

672 _nx.clongdouble: 3} 

673 

674 

675def _common_type_dispatcher(*arrays): 

676 return arrays 

677 

678 

679@array_function_dispatch(_common_type_dispatcher) 

680def common_type(*arrays): 

681 """ 

682 Return a scalar type which is common to the input arrays. 

683 

684 The return type will always be an inexact (i.e. floating point) scalar 

685 type, even if all the arrays are integer arrays. If one of the inputs is 

686 an integer array, the minimum precision type that is returned is a 

687 64-bit floating point dtype. 

688 

689 All input arrays except int64 and uint64 can be safely cast to the 

690 returned dtype without loss of information. 

691 

692 Parameters 

693 ---------- 

694 array1, array2, ... : ndarrays 

695 Input arrays. 

696 

697 Returns 

698 ------- 

699 out : data type code 

700 Data type code. 

701 

702 See Also 

703 -------- 

704 dtype, mintypecode 

705 

706 Examples 

707 -------- 

708 >>> np.common_type(np.arange(2, dtype=np.float32)) 

709 <class 'numpy.float32'> 

710 >>> np.common_type(np.arange(2, dtype=np.float32), np.arange(2)) 

711 <class 'numpy.float64'> 

712 >>> np.common_type(np.arange(4), np.array([45, 6.j]), np.array([45.0])) 

713 <class 'numpy.complex128'> 

714 

715 """ 

716 is_complex = False 

717 precision = 0 

718 for a in arrays: 

719 t = a.dtype.type 

720 if iscomplexobj(a): 

721 is_complex = True 

722 if issubclass(t, _nx.integer): 

723 p = 2 # array_precision[_nx.double] 

724 else: 

725 p = array_precision.get(t, None) 

726 if p is None: 

727 raise TypeError("can't get common type for non-numeric array") 

728 precision = max(precision, p) 

729 if is_complex: 

730 return array_type[1][precision] 

731 else: 

732 return array_type[0][precision]