Coverage for /usr/lib/python3/dist-packages/numpy/lib/type_check.py: 34%

131 statements  

« prev     ^ index     » next       coverage.py v7.4.4, created at 2025-06-14 15:25 +0200

1"""Automatically adapted for numpy Sep 19, 2005 by convertcode.py 

2 

3""" 

4import functools 

5 

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

7 'isreal', 'nan_to_num', 'real', 'real_if_close', 

8 'typename', 'asfarray', 'mintypecode', 

9 'common_type'] 

10 

11from .._utils import set_module 

12import numpy.core.numeric as _nx 

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

14from numpy.core import overrides, getlimits 

15from .ufunclike import isneginf, isposinf 

16 

17 

18array_function_dispatch = functools.partial( 

19 overrides.array_function_dispatch, module='numpy') 

20 

21 

22_typecodes_by_elsize = 'GDFgdfQqLlIiHhBb?' 

23 

24 

25@set_module('numpy') 

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

27 """ 

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

29 be safely cast. 

30 

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

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

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

34 dtype.char). 

35 

36 Parameters 

37 ---------- 

38 typechars : list of str or array_like 

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

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

41 typeset : str or list of str, optional 

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

43 The default set is 'GDFgdf'. 

44 default : str, optional 

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

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

47 

48 Returns 

49 ------- 

50 typechar : str 

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

52 

53 See Also 

54 -------- 

55 dtype, sctype2char, maximum_sctype 

56 

57 Examples 

58 -------- 

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

60 'd' 

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

62 >>> np.mintypecode(x) 

63 'D' 

64 

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

66 'G' 

67 

68 """ 

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

70 for t in typechars) 

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

72 if not intersection: 

73 return default 

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

75 return 'D' 

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

77 

78 

79def _asfarray_dispatcher(a, dtype=None): 

80 return (a,) 

81 

82 

83@array_function_dispatch(_asfarray_dispatcher) 

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

85 """ 

86 Return an array converted to a float type. 

87 

88 Parameters 

89 ---------- 

90 a : array_like 

91 The input array. 

92 dtype : str or dtype object, optional 

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

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

95 

96 Returns 

97 ------- 

98 out : ndarray 

99 The input `a` as a float ndarray. 

100 

101 Examples 

102 -------- 

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

104 array([2., 3.]) 

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

106 array([2., 3.]) 

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

108 array([2., 3.]) 

109 

110 """ 

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

112 dtype = _nx.float_ 

113 return asarray(a, dtype=dtype) 

114 

115 

116def _real_dispatcher(val): 

117 return (val,) 

118 

119 

120@array_function_dispatch(_real_dispatcher) 

121def real(val): 

122 """ 

123 Return the real part of the complex argument. 

124 

125 Parameters 

126 ---------- 

127 val : array_like 

128 Input array. 

129 

130 Returns 

131 ------- 

132 out : ndarray or scalar 

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

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

135 returned type is float. 

136 

137 See Also 

138 -------- 

139 real_if_close, imag, angle 

140 

141 Examples 

142 -------- 

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

144 >>> a.real 

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

146 >>> a.real = 9 

147 >>> a 

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

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

150 >>> a 

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

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

153 1.0 

154 

155 """ 

156 try: 

157 return val.real 

158 except AttributeError: 

159 return asanyarray(val).real 

160 

161 

162def _imag_dispatcher(val): 

163 return (val,) 

164 

165 

166@array_function_dispatch(_imag_dispatcher) 

167def imag(val): 

168 """ 

169 Return the imaginary part of the complex argument. 

170 

171 Parameters 

172 ---------- 

173 val : array_like 

174 Input array. 

175 

176 Returns 

177 ------- 

178 out : ndarray or scalar 

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

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

181 elements, the returned type is float. 

182 

183 See Also 

184 -------- 

185 real, angle, real_if_close 

186 

187 Examples 

188 -------- 

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

190 >>> a.imag 

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

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

193 >>> a 

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

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

196 1.0 

197 

198 """ 

199 try: 

200 return val.imag 

201 except AttributeError: 

202 return asanyarray(val).imag 

203 

204 

205def _is_type_dispatcher(x): 

206 return (x,) 

207 

208 

209@array_function_dispatch(_is_type_dispatcher) 

210def iscomplex(x): 

211 """ 

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

213 

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

215 the input type is complex. 

216 

217 Parameters 

218 ---------- 

219 x : array_like 

220 Input array. 

221 

222 Returns 

223 ------- 

224 out : ndarray of bools 

225 Output array. 

226 

227 See Also 

228 -------- 

229 isreal 

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

231 numbers. 

232 

233 Examples 

234 -------- 

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

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

237 

238 """ 

239 ax = asanyarray(x) 

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

241 return ax.imag != 0 

242 res = zeros(ax.shape, bool) 

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

244 

245 

246@array_function_dispatch(_is_type_dispatcher) 

247def isreal(x): 

248 """ 

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

250 

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

252 for that element is True. 

253 

254 Parameters 

255 ---------- 

256 x : array_like 

257 Input array. 

258 

259 Returns 

260 ------- 

261 out : ndarray, bool 

262 Boolean array of same shape as `x`. 

263 

264 Notes 

265 ----- 

266 `isreal` may behave unexpectedly for string or object arrays (see examples) 

267 

268 See Also 

269 -------- 

270 iscomplex 

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

272 

273 Examples 

274 -------- 

275 >>> a = np.array([1+1j, 1+0j, 4.5, 3, 2, 2j], dtype=complex) 

276 >>> np.isreal(a) 

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

278 

279 The function does not work on string arrays. 

280 

281 >>> a = np.array([2j, "a"], dtype="U") 

282 >>> np.isreal(a) # Warns about non-elementwise comparison 

283 False 

284 

285 Returns True for all elements in input array of ``dtype=object`` even if 

286 any of the elements is complex. 

287 

288 >>> a = np.array([1, "2", 3+4j], dtype=object) 

289 >>> np.isreal(a) 

290 array([ True, True, True]) 

291 

292 isreal should not be used with object arrays 

293 

294 >>> a = np.array([1+2j, 2+1j], dtype=object) 

295 >>> np.isreal(a) 

296 array([ True, True]) 

297 

298 """ 

299 return imag(x) == 0 

300 

301 

302@array_function_dispatch(_is_type_dispatcher) 

303def iscomplexobj(x): 

304 """ 

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

306 

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

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

309 

310 Parameters 

311 ---------- 

312 x : any 

313 The input can be of any type and shape. 

314 

315 Returns 

316 ------- 

317 iscomplexobj : bool 

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

319 one complex element. 

320 

321 See Also 

322 -------- 

323 isrealobj, iscomplex 

324 

325 Examples 

326 -------- 

327 >>> np.iscomplexobj(1) 

328 False 

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

330 True 

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

332 True 

333 

334 """ 

335 try: 

336 dtype = x.dtype 

337 type_ = dtype.type 

338 except AttributeError: 

339 type_ = asarray(x).dtype.type 

340 return issubclass(type_, _nx.complexfloating) 

341 

342 

343@array_function_dispatch(_is_type_dispatcher) 

344def isrealobj(x): 

345 """ 

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

347 

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

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

350 if the data type is complex. 

351 

352 Parameters 

353 ---------- 

354 x : any 

355 The input can be of any type and shape. 

356 

357 Returns 

358 ------- 

359 y : bool 

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

361 

362 See Also 

363 -------- 

364 iscomplexobj, isreal 

365 

366 Notes 

367 ----- 

368 The function is only meant for arrays with numerical values but it 

369 accepts all other objects. Since it assumes array input, the return 

370 value of other objects may be True. 

371 

372 >>> np.isrealobj('A string') 

373 True 

374 >>> np.isrealobj(False) 

375 True 

376 >>> np.isrealobj(None) 

377 True 

378 

379 Examples 

380 -------- 

381 >>> np.isrealobj(1) 

382 True 

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

384 False 

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

386 False 

387 

388 """ 

389 return not iscomplexobj(x) 

390 

391#----------------------------------------------------------------------------- 

392 

393def _getmaxmin(t): 

394 from numpy.core import getlimits 

395 f = getlimits.finfo(t) 

396 return f.max, f.min 

397 

398 

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

400 return (x,) 

401 

402 

403@array_function_dispatch(_nan_to_num_dispatcher) 

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

405 """ 

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

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

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

409 

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

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

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

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

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

415 value in `neginf` keyword. 

416 

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

418 imaginary components of `x` separately. 

419 

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

421 

422 Parameters 

423 ---------- 

424 x : scalar or array_like 

425 Input data. 

426 copy : bool, optional 

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

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

429 casting to an array does not require a copy. 

430 Default is True. 

431 

432 .. versionadded:: 1.13 

433 nan : int, float, optional 

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

435 then NaN values will be replaced with 0.0. 

436 

437 .. versionadded:: 1.17 

438 posinf : int, float, optional 

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

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

441 large number. 

442 

443 .. versionadded:: 1.17 

444 neginf : int, float, optional 

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

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

447 small (or negative) number. 

448 

449 .. versionadded:: 1.17 

450 

451 

452 

453 Returns 

454 ------- 

455 out : ndarray 

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

457 be `x` itself. 

458 

459 See Also 

460 -------- 

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

462 isneginf : Shows which elements are negative infinity. 

463 isposinf : Shows which elements are positive infinity. 

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

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

466 

467 Notes 

468 ----- 

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

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

471 

472 Examples 

473 -------- 

474 >>> np.nan_to_num(np.inf) 

475 1.7976931348623157e+308 

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

477 -1.7976931348623157e+308 

478 >>> np.nan_to_num(np.nan) 

479 0.0 

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

481 >>> np.nan_to_num(x) 

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

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

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

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

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

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

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

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

490 >>> np.nan_to_num(y) 

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

492 0.00000000e+000 +0.00000000e+000j, 

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

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

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

496 """ 

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

498 xtype = x.dtype.type 

499 

500 isscalar = (x.ndim == 0) 

501 

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

503 return x[()] if isscalar else x 

504 

505 iscomplex = issubclass(xtype, _nx.complexfloating) 

506 

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

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

509 if posinf is not None: 

510 maxf = posinf 

511 if neginf is not None: 

512 minf = neginf 

513 for d in dest: 

514 idx_nan = isnan(d) 

515 idx_posinf = isposinf(d) 

516 idx_neginf = isneginf(d) 

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

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

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

520 return x[()] if isscalar else x 

521 

522#----------------------------------------------------------------------------- 

523 

524def _real_if_close_dispatcher(a, tol=None): 

525 return (a,) 

526 

527 

528@array_function_dispatch(_real_if_close_dispatcher) 

529def real_if_close(a, tol=100): 

530 """ 

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

532 real parts. 

533 

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

535 `a`). 

536 

537 Parameters 

538 ---------- 

539 a : array_like 

540 Input array. 

541 tol : float 

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

543 in the array. If the tolerance is <=1, then the absolute tolerance 

544 is used. 

545 

546 Returns 

547 ------- 

548 out : ndarray 

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

550 has complex elements, the returned type is float. 

551 

552 See Also 

553 -------- 

554 real, imag, angle 

555 

556 Notes 

557 ----- 

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

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

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

561 out the machine epsilon for floats. 

562 

563 Examples 

564 -------- 

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

566 2.2204460492503131e-16 # may vary 

567 

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

569 array([2.1, 5.2]) 

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

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

572 

573 """ 

574 a = asanyarray(a) 

575 type_ = a.dtype.type 

576 if not issubclass(type_, _nx.complexfloating): 

577 return a 

578 if tol > 1: 

579 f = getlimits.finfo(type_) 

580 tol = f.eps * tol 

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

582 a = a.real 

583 return a 

584 

585 

586#----------------------------------------------------------------------------- 

587 

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

589 '?': 'bool', 

590 'b': 'signed char', 

591 'B': 'unsigned char', 

592 'h': 'short', 

593 'H': 'unsigned short', 

594 'i': 'integer', 

595 'I': 'unsigned integer', 

596 'l': 'long integer', 

597 'L': 'unsigned long integer', 

598 'q': 'long long integer', 

599 'Q': 'unsigned long long integer', 

600 'f': 'single precision', 

601 'd': 'double precision', 

602 'g': 'long precision', 

603 'F': 'complex single precision', 

604 'D': 'complex double precision', 

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

606 'S': 'string', 

607 'U': 'unicode', 

608 'V': 'void', 

609 'O': 'object' 

610 } 

611 

612@set_module('numpy') 

613def typename(char): 

614 """ 

615 Return a description for the given data type code. 

616 

617 Parameters 

618 ---------- 

619 char : str 

620 Data type code. 

621 

622 Returns 

623 ------- 

624 out : str 

625 Description of the input data type code. 

626 

627 See Also 

628 -------- 

629 dtype, typecodes 

630 

631 Examples 

632 -------- 

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

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

635 >>> for typechar in typechars: 

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

637 ... 

638 S1 : character 

639 ? : bool 

640 B : unsigned char 

641 D : complex double precision 

642 G : complex long double precision 

643 F : complex single precision 

644 I : unsigned integer 

645 H : unsigned short 

646 L : unsigned long integer 

647 O : object 

648 Q : unsigned long long integer 

649 S : string 

650 U : unicode 

651 V : void 

652 b : signed char 

653 d : double precision 

654 g : long precision 

655 f : single precision 

656 i : integer 

657 h : short 

658 l : long integer 

659 q : long long integer 

660 

661 """ 

662 return _namefromtype[char] 

663 

664#----------------------------------------------------------------------------- 

665 

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

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

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

669array_precision = {_nx.half: 0, 

670 _nx.single: 1, 

671 _nx.double: 2, 

672 _nx.longdouble: 3, 

673 _nx.csingle: 1, 

674 _nx.cdouble: 2, 

675 _nx.clongdouble: 3} 

676 

677 

678def _common_type_dispatcher(*arrays): 

679 return arrays 

680 

681 

682@array_function_dispatch(_common_type_dispatcher) 

683def common_type(*arrays): 

684 """ 

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

686 

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

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

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

690 64-bit floating point dtype. 

691 

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

693 returned dtype without loss of information. 

694 

695 Parameters 

696 ---------- 

697 array1, array2, ... : ndarrays 

698 Input arrays. 

699 

700 Returns 

701 ------- 

702 out : data type code 

703 Data type code. 

704 

705 See Also 

706 -------- 

707 dtype, mintypecode 

708 

709 Examples 

710 -------- 

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

712 <class 'numpy.float32'> 

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

714 <class 'numpy.float64'> 

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

716 <class 'numpy.complex128'> 

717 

718 """ 

719 is_complex = False 

720 precision = 0 

721 for a in arrays: 

722 t = a.dtype.type 

723 if iscomplexobj(a): 

724 is_complex = True 

725 if issubclass(t, _nx.integer): 

726 p = 2 # array_precision[_nx.double] 

727 else: 

728 p = array_precision.get(t, None) 

729 if p is None: 

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

731 precision = max(precision, p) 

732 if is_complex: 

733 return array_type[1][precision] 

734 else: 

735 return array_type[0][precision]