_utils_impl.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784
  1. import functools
  2. import os
  3. import platform
  4. import sys
  5. import textwrap
  6. import types
  7. import warnings
  8. import numpy as np
  9. from numpy._core import ndarray
  10. from numpy._utils import set_module
  11. __all__ = [
  12. 'get_include', 'info', 'show_runtime'
  13. ]
  14. @set_module('numpy')
  15. def show_runtime():
  16. """
  17. Print information about various resources in the system
  18. including available intrinsic support and BLAS/LAPACK library
  19. in use
  20. .. versionadded:: 1.24.0
  21. See Also
  22. --------
  23. show_config : Show libraries in the system on which NumPy was built.
  24. Notes
  25. -----
  26. 1. Information is derived with the help of `threadpoolctl <https://pypi.org/project/threadpoolctl/>`_
  27. library if available.
  28. 2. SIMD related information is derived from ``__cpu_features__``,
  29. ``__cpu_baseline__`` and ``__cpu_dispatch__``
  30. """
  31. from pprint import pprint
  32. from numpy._core._multiarray_umath import (
  33. __cpu_baseline__,
  34. __cpu_dispatch__,
  35. __cpu_features__,
  36. )
  37. config_found = [{
  38. "numpy_version": np.__version__,
  39. "python": sys.version,
  40. "uname": platform.uname(),
  41. }]
  42. features_found, features_not_found = [], []
  43. for feature in __cpu_dispatch__:
  44. if __cpu_features__[feature]:
  45. features_found.append(feature)
  46. else:
  47. features_not_found.append(feature)
  48. config_found.append({
  49. "simd_extensions": {
  50. "baseline": __cpu_baseline__,
  51. "found": features_found,
  52. "not_found": features_not_found
  53. }
  54. })
  55. config_found.append({
  56. "ignore_floating_point_errors_in_matmul":
  57. not np._core._multiarray_umath._blas_supports_fpe(None),
  58. })
  59. try:
  60. from threadpoolctl import threadpool_info
  61. config_found.extend(threadpool_info())
  62. except ImportError:
  63. print("WARNING: `threadpoolctl` not found in system!"
  64. " Install it by `pip install threadpoolctl`."
  65. " Once installed, try `np.show_runtime` again"
  66. " for more detailed build information")
  67. pprint(config_found)
  68. @set_module('numpy')
  69. def get_include():
  70. """
  71. Return the directory that contains the NumPy \\*.h header files.
  72. Extension modules that need to compile against NumPy may need to use this
  73. function to locate the appropriate include directory.
  74. Notes
  75. -----
  76. When using ``setuptools``, for example in ``setup.py``::
  77. import numpy as np
  78. ...
  79. Extension('extension_name', ...
  80. include_dirs=[np.get_include()])
  81. ...
  82. Note that a CLI tool ``numpy-config`` was introduced in NumPy 2.0, using
  83. that is likely preferred for build systems other than ``setuptools``::
  84. $ numpy-config --cflags
  85. -I/path/to/site-packages/numpy/_core/include
  86. # Or rely on pkg-config:
  87. $ export PKG_CONFIG_PATH=$(numpy-config --pkgconfigdir)
  88. $ pkg-config --cflags
  89. -I/path/to/site-packages/numpy/_core/include
  90. Examples
  91. --------
  92. >>> np.get_include()
  93. '.../site-packages/numpy/core/include' # may vary
  94. """
  95. import numpy
  96. if numpy.show_config is None:
  97. # running from numpy source directory
  98. d = os.path.join(os.path.dirname(numpy.__file__), '_core', 'include')
  99. else:
  100. # using installed numpy core headers
  101. import numpy._core as _core
  102. d = os.path.join(os.path.dirname(_core.__file__), 'include')
  103. return d
  104. class _Deprecate:
  105. """
  106. Decorator class to deprecate old functions.
  107. Refer to `deprecate` for details.
  108. See Also
  109. --------
  110. deprecate
  111. """
  112. def __init__(self, old_name=None, new_name=None, message=None):
  113. self.old_name = old_name
  114. self.new_name = new_name
  115. self.message = message
  116. def __call__(self, func, *args, **kwargs):
  117. """
  118. Decorator call. Refer to ``decorate``.
  119. """
  120. old_name = self.old_name
  121. new_name = self.new_name
  122. message = self.message
  123. if old_name is None:
  124. old_name = func.__name__
  125. if new_name is None:
  126. depdoc = f"`{old_name}` is deprecated!"
  127. else:
  128. depdoc = f"`{old_name}` is deprecated, use `{new_name}` instead!"
  129. if message is not None:
  130. depdoc += "\n" + message
  131. @functools.wraps(func)
  132. def newfunc(*args, **kwds):
  133. warnings.warn(depdoc, DeprecationWarning, stacklevel=2)
  134. return func(*args, **kwds)
  135. newfunc.__name__ = old_name
  136. doc = func.__doc__
  137. if doc is None:
  138. doc = depdoc
  139. else:
  140. lines = doc.expandtabs().split('\n')
  141. indent = _get_indent(lines[1:])
  142. if lines[0].lstrip():
  143. # Indent the original first line to let inspect.cleandoc()
  144. # dedent the docstring despite the deprecation notice.
  145. doc = indent * ' ' + doc
  146. else:
  147. # Remove the same leading blank lines as cleandoc() would.
  148. skip = len(lines[0]) + 1
  149. for line in lines[1:]:
  150. if len(line) > indent:
  151. break
  152. skip += len(line) + 1
  153. doc = doc[skip:]
  154. depdoc = textwrap.indent(depdoc, ' ' * indent)
  155. doc = f'{depdoc}\n\n{doc}'
  156. newfunc.__doc__ = doc
  157. return newfunc
  158. def _get_indent(lines):
  159. """
  160. Determines the leading whitespace that could be removed from all the lines.
  161. """
  162. indent = sys.maxsize
  163. for line in lines:
  164. content = len(line.lstrip())
  165. if content:
  166. indent = min(indent, len(line) - content)
  167. if indent == sys.maxsize:
  168. indent = 0
  169. return indent
  170. def deprecate(*args, **kwargs):
  171. """
  172. Issues a DeprecationWarning, adds warning to `old_name`'s
  173. docstring, rebinds ``old_name.__name__`` and returns the new
  174. function object.
  175. This function may also be used as a decorator.
  176. .. deprecated:: 2.0
  177. Use `~warnings.warn` with :exc:`DeprecationWarning` instead.
  178. Parameters
  179. ----------
  180. func : function
  181. The function to be deprecated.
  182. old_name : str, optional
  183. The name of the function to be deprecated. Default is None, in
  184. which case the name of `func` is used.
  185. new_name : str, optional
  186. The new name for the function. Default is None, in which case the
  187. deprecation message is that `old_name` is deprecated. If given, the
  188. deprecation message is that `old_name` is deprecated and `new_name`
  189. should be used instead.
  190. message : str, optional
  191. Additional explanation of the deprecation. Displayed in the
  192. docstring after the warning.
  193. Returns
  194. -------
  195. old_func : function
  196. The deprecated function.
  197. Examples
  198. --------
  199. Note that ``olduint`` returns a value after printing Deprecation
  200. Warning:
  201. >>> olduint = np.lib.utils.deprecate(np.uint)
  202. DeprecationWarning: `uint64` is deprecated! # may vary
  203. >>> olduint(6)
  204. 6
  205. """
  206. # Deprecate may be run as a function or as a decorator
  207. # If run as a function, we initialise the decorator class
  208. # and execute its __call__ method.
  209. # Deprecated in NumPy 2.0, 2023-07-11
  210. warnings.warn(
  211. "`deprecate` is deprecated, "
  212. "use `warn` with `DeprecationWarning` instead. "
  213. "(deprecated in NumPy 2.0)",
  214. DeprecationWarning,
  215. stacklevel=2
  216. )
  217. if args:
  218. fn = args[0]
  219. args = args[1:]
  220. return _Deprecate(*args, **kwargs)(fn)
  221. else:
  222. return _Deprecate(*args, **kwargs)
  223. def deprecate_with_doc(msg):
  224. """
  225. Deprecates a function and includes the deprecation in its docstring.
  226. .. deprecated:: 2.0
  227. Use `~warnings.warn` with :exc:`DeprecationWarning` instead.
  228. This function is used as a decorator. It returns an object that can be
  229. used to issue a DeprecationWarning, by passing the to-be decorated
  230. function as argument, this adds warning to the to-be decorated function's
  231. docstring and returns the new function object.
  232. See Also
  233. --------
  234. deprecate : Decorate a function such that it issues a
  235. :exc:`DeprecationWarning`
  236. Parameters
  237. ----------
  238. msg : str
  239. Additional explanation of the deprecation. Displayed in the
  240. docstring after the warning.
  241. Returns
  242. -------
  243. obj : object
  244. """
  245. # Deprecated in NumPy 2.0, 2023-07-11
  246. warnings.warn(
  247. "`deprecate` is deprecated, "
  248. "use `warn` with `DeprecationWarning` instead. "
  249. "(deprecated in NumPy 2.0)",
  250. DeprecationWarning,
  251. stacklevel=2
  252. )
  253. return _Deprecate(message=msg)
  254. #-----------------------------------------------------------------------------
  255. # NOTE: pydoc defines a help function which works similarly to this
  256. # except it uses a pager to take over the screen.
  257. # combine name and arguments and split to multiple lines of width
  258. # characters. End lines on a comma and begin argument list indented with
  259. # the rest of the arguments.
  260. def _split_line(name, arguments, width):
  261. firstwidth = len(name)
  262. k = firstwidth
  263. newstr = name
  264. sepstr = ", "
  265. arglist = arguments.split(sepstr)
  266. for argument in arglist:
  267. if k == firstwidth:
  268. addstr = ""
  269. else:
  270. addstr = sepstr
  271. k = k + len(argument) + len(addstr)
  272. if k > width:
  273. k = firstwidth + 1 + len(argument)
  274. newstr = newstr + ",\n" + " " * (firstwidth + 2) + argument
  275. else:
  276. newstr = newstr + addstr + argument
  277. return newstr
  278. _namedict = None
  279. _dictlist = None
  280. # Traverse all module directories underneath globals
  281. # to see if something is defined
  282. def _makenamedict(module='numpy'):
  283. module = __import__(module, globals(), locals(), [])
  284. thedict = {module.__name__: module.__dict__}
  285. dictlist = [module.__name__]
  286. totraverse = [module.__dict__]
  287. while True:
  288. if len(totraverse) == 0:
  289. break
  290. thisdict = totraverse.pop(0)
  291. for x in thisdict.keys():
  292. if isinstance(thisdict[x], types.ModuleType):
  293. modname = thisdict[x].__name__
  294. if modname not in dictlist:
  295. moddict = thisdict[x].__dict__
  296. dictlist.append(modname)
  297. totraverse.append(moddict)
  298. thedict[modname] = moddict
  299. return thedict, dictlist
  300. def _info(obj, output=None):
  301. """Provide information about ndarray obj.
  302. Parameters
  303. ----------
  304. obj : ndarray
  305. Must be ndarray, not checked.
  306. output
  307. Where printed output goes.
  308. Notes
  309. -----
  310. Copied over from the numarray module prior to its removal.
  311. Adapted somewhat as only numpy is an option now.
  312. Called by info.
  313. """
  314. extra = ""
  315. tic = ""
  316. bp = lambda x: x
  317. cls = getattr(obj, '__class__', type(obj))
  318. nm = getattr(cls, '__name__', cls)
  319. strides = obj.strides
  320. endian = obj.dtype.byteorder
  321. if output is None:
  322. output = sys.stdout
  323. print("class: ", nm, file=output)
  324. print("shape: ", obj.shape, file=output)
  325. print("strides: ", strides, file=output)
  326. print("itemsize: ", obj.itemsize, file=output)
  327. print("aligned: ", bp(obj.flags.aligned), file=output)
  328. print("contiguous: ", bp(obj.flags.contiguous), file=output)
  329. print("fortran: ", obj.flags.fortran, file=output)
  330. print(
  331. f"data pointer: {hex(obj.ctypes._as_parameter_.value)}{extra}",
  332. file=output
  333. )
  334. print("byteorder: ", end=' ', file=output)
  335. if endian in ['|', '=']:
  336. print(f"{tic}{sys.byteorder}{tic}", file=output)
  337. byteswap = False
  338. elif endian == '>':
  339. print(f"{tic}big{tic}", file=output)
  340. byteswap = sys.byteorder != "big"
  341. else:
  342. print(f"{tic}little{tic}", file=output)
  343. byteswap = sys.byteorder != "little"
  344. print("byteswap: ", bp(byteswap), file=output)
  345. print(f"type: {obj.dtype}", file=output)
  346. @set_module('numpy')
  347. def info(object=None, maxwidth=76, output=None, toplevel='numpy'):
  348. """
  349. Get help information for an array, function, class, or module.
  350. Parameters
  351. ----------
  352. object : object or str, optional
  353. Input object or name to get information about. If `object` is
  354. an `ndarray` instance, information about the array is printed.
  355. If `object` is a numpy object, its docstring is given. If it is
  356. a string, available modules are searched for matching objects.
  357. If None, information about `info` itself is returned.
  358. maxwidth : int, optional
  359. Printing width.
  360. output : file like object, optional
  361. File like object that the output is written to, default is
  362. ``None``, in which case ``sys.stdout`` will be used.
  363. The object has to be opened in 'w' or 'a' mode.
  364. toplevel : str, optional
  365. Start search at this level.
  366. Notes
  367. -----
  368. When used interactively with an object, ``np.info(obj)`` is equivalent
  369. to ``help(obj)`` on the Python prompt or ``obj?`` on the IPython
  370. prompt.
  371. Examples
  372. --------
  373. >>> np.info(np.polyval) # doctest: +SKIP
  374. polyval(p, x)
  375. Evaluate the polynomial p at x.
  376. ...
  377. When using a string for `object` it is possible to get multiple results.
  378. >>> np.info('fft') # doctest: +SKIP
  379. *** Found in numpy ***
  380. Core FFT routines
  381. ...
  382. *** Found in numpy.fft ***
  383. fft(a, n=None, axis=-1)
  384. ...
  385. *** Repeat reference found in numpy.fft.fftpack ***
  386. *** Total of 3 references found. ***
  387. When the argument is an array, information about the array is printed.
  388. >>> a = np.array([[1 + 2j, 3, -4], [-5j, 6, 0]], dtype=np.complex64)
  389. >>> np.info(a)
  390. class: ndarray
  391. shape: (2, 3)
  392. strides: (24, 8)
  393. itemsize: 8
  394. aligned: True
  395. contiguous: True
  396. fortran: False
  397. data pointer: 0x562b6e0d2860 # may vary
  398. byteorder: little
  399. byteswap: False
  400. type: complex64
  401. """
  402. global _namedict, _dictlist
  403. # Local import to speed up numpy's import time.
  404. import inspect
  405. import pydoc
  406. if (hasattr(object, '_ppimport_importer') or
  407. hasattr(object, '_ppimport_module')):
  408. object = object._ppimport_module
  409. elif hasattr(object, '_ppimport_attr'):
  410. object = object._ppimport_attr
  411. if output is None:
  412. output = sys.stdout
  413. if object is None:
  414. info(info)
  415. elif isinstance(object, ndarray):
  416. _info(object, output=output)
  417. elif isinstance(object, str):
  418. if _namedict is None:
  419. _namedict, _dictlist = _makenamedict(toplevel)
  420. numfound = 0
  421. objlist = []
  422. for namestr in _dictlist:
  423. try:
  424. obj = _namedict[namestr][object]
  425. if id(obj) in objlist:
  426. print(f"\n *** Repeat reference found in {namestr} *** ",
  427. file=output
  428. )
  429. else:
  430. objlist.append(id(obj))
  431. print(f" *** Found in {namestr} ***", file=output)
  432. info(obj)
  433. print("-" * maxwidth, file=output)
  434. numfound += 1
  435. except KeyError:
  436. pass
  437. if numfound == 0:
  438. print(f"Help for {object} not found.", file=output)
  439. else:
  440. print("\n "
  441. "*** Total of %d references found. ***" % numfound,
  442. file=output
  443. )
  444. elif inspect.isfunction(object) or inspect.ismethod(object):
  445. name = object.__name__
  446. try:
  447. arguments = str(inspect.signature(object))
  448. except Exception:
  449. arguments = "()"
  450. if len(name + arguments) > maxwidth:
  451. argstr = _split_line(name, arguments, maxwidth)
  452. else:
  453. argstr = name + arguments
  454. print(" " + argstr + "\n", file=output)
  455. print(inspect.getdoc(object), file=output)
  456. elif inspect.isclass(object):
  457. name = object.__name__
  458. try:
  459. arguments = str(inspect.signature(object))
  460. except Exception:
  461. arguments = "()"
  462. if len(name + arguments) > maxwidth:
  463. argstr = _split_line(name, arguments, maxwidth)
  464. else:
  465. argstr = name + arguments
  466. print(" " + argstr + "\n", file=output)
  467. doc1 = inspect.getdoc(object)
  468. if doc1 is None:
  469. if hasattr(object, '__init__'):
  470. print(inspect.getdoc(object.__init__), file=output)
  471. else:
  472. print(inspect.getdoc(object), file=output)
  473. methods = pydoc.allmethods(object)
  474. public_methods = [meth for meth in methods if meth[0] != '_']
  475. if public_methods:
  476. print("\n\nMethods:\n", file=output)
  477. for meth in public_methods:
  478. thisobj = getattr(object, meth, None)
  479. if thisobj is not None:
  480. methstr, other = pydoc.splitdoc(
  481. inspect.getdoc(thisobj) or "None"
  482. )
  483. print(f" {meth} -- {methstr}", file=output)
  484. elif hasattr(object, '__doc__'):
  485. print(inspect.getdoc(object), file=output)
  486. def safe_eval(source):
  487. """
  488. Protected string evaluation.
  489. .. deprecated:: 2.0
  490. Use `ast.literal_eval` instead.
  491. Evaluate a string containing a Python literal expression without
  492. allowing the execution of arbitrary non-literal code.
  493. .. warning::
  494. This function is identical to :py:meth:`ast.literal_eval` and
  495. has the same security implications. It may not always be safe
  496. to evaluate large input strings.
  497. Parameters
  498. ----------
  499. source : str
  500. The string to evaluate.
  501. Returns
  502. -------
  503. obj : object
  504. The result of evaluating `source`.
  505. Raises
  506. ------
  507. SyntaxError
  508. If the code has invalid Python syntax, or if it contains
  509. non-literal code.
  510. Examples
  511. --------
  512. >>> np.safe_eval('1')
  513. 1
  514. >>> np.safe_eval('[1, 2, 3]')
  515. [1, 2, 3]
  516. >>> np.safe_eval('{"foo": ("bar", 10.0)}')
  517. {'foo': ('bar', 10.0)}
  518. >>> np.safe_eval('import os')
  519. Traceback (most recent call last):
  520. ...
  521. SyntaxError: invalid syntax
  522. >>> np.safe_eval('open("/home/user/.ssh/id_dsa").read()')
  523. Traceback (most recent call last):
  524. ...
  525. ValueError: malformed node or string: <_ast.Call object at 0x...>
  526. """
  527. # Deprecated in NumPy 2.0, 2023-07-11
  528. warnings.warn(
  529. "`safe_eval` is deprecated. Use `ast.literal_eval` instead. "
  530. "Be aware of security implications, such as memory exhaustion "
  531. "based attacks (deprecated in NumPy 2.0)",
  532. DeprecationWarning,
  533. stacklevel=2
  534. )
  535. # Local import to speed up numpy's import time.
  536. import ast
  537. return ast.literal_eval(source)
  538. def _median_nancheck(data, result, axis):
  539. """
  540. Utility function to check median result from data for NaN values at the end
  541. and return NaN in that case. Input result can also be a MaskedArray.
  542. Parameters
  543. ----------
  544. data : array
  545. Sorted input data to median function
  546. result : Array or MaskedArray
  547. Result of median function.
  548. axis : int
  549. Axis along which the median was computed.
  550. Returns
  551. -------
  552. result : scalar or ndarray
  553. Median or NaN in axes which contained NaN in the input. If the input
  554. was an array, NaN will be inserted in-place. If a scalar, either the
  555. input itself or a scalar NaN.
  556. """
  557. if data.size == 0:
  558. return result
  559. potential_nans = data.take(-1, axis=axis)
  560. n = np.isnan(potential_nans)
  561. # masked NaN values are ok, although for masked the copyto may fail for
  562. # unmasked ones (this was always broken) when the result is a scalar.
  563. if np.ma.isMaskedArray(n):
  564. n = n.filled(False)
  565. if not n.any():
  566. return result
  567. # Without given output, it is possible that the current result is a
  568. # numpy scalar, which is not writeable. If so, just return nan.
  569. if isinstance(result, np.generic):
  570. return potential_nans
  571. # Otherwise copy NaNs (if there are any)
  572. np.copyto(result, potential_nans, where=n)
  573. return result
  574. def _opt_info():
  575. """
  576. Returns a string containing the CPU features supported
  577. by the current build.
  578. The format of the string can be explained as follows:
  579. - Dispatched features supported by the running machine end with `*`.
  580. - Dispatched features not supported by the running machine
  581. end with `?`.
  582. - Remaining features represent the baseline.
  583. Returns:
  584. str: A formatted string indicating the supported CPU features.
  585. """
  586. from numpy._core._multiarray_umath import (
  587. __cpu_baseline__,
  588. __cpu_dispatch__,
  589. __cpu_features__,
  590. )
  591. if len(__cpu_baseline__) == 0 and len(__cpu_dispatch__) == 0:
  592. return ''
  593. enabled_features = ' '.join(__cpu_baseline__)
  594. for feature in __cpu_dispatch__:
  595. if __cpu_features__[feature]:
  596. enabled_features += f" {feature}*"
  597. else:
  598. enabled_features += f" {feature}?"
  599. return enabled_features
  600. def drop_metadata(dtype, /):
  601. """
  602. Returns the dtype unchanged if it contained no metadata or a copy of the
  603. dtype if it (or any of its structure dtypes) contained metadata.
  604. This utility is used by `np.save` and `np.savez` to drop metadata before
  605. saving.
  606. .. note::
  607. Due to its limitation this function may move to a more appropriate
  608. home or change in the future and is considered semi-public API only.
  609. .. warning::
  610. This function does not preserve more strange things like record dtypes
  611. and user dtypes may simply return the wrong thing. If you need to be
  612. sure about the latter, check the result with:
  613. ``np.can_cast(new_dtype, dtype, casting="no")``.
  614. """
  615. if dtype.fields is not None:
  616. found_metadata = dtype.metadata is not None
  617. names = []
  618. formats = []
  619. offsets = []
  620. titles = []
  621. for name, field in dtype.fields.items():
  622. field_dt = drop_metadata(field[0])
  623. if field_dt is not field[0]:
  624. found_metadata = True
  625. names.append(name)
  626. formats.append(field_dt)
  627. offsets.append(field[1])
  628. titles.append(None if len(field) < 3 else field[2])
  629. if not found_metadata:
  630. return dtype
  631. structure = {
  632. 'names': names, 'formats': formats, 'offsets': offsets, 'titles': titles,
  633. 'itemsize': dtype.itemsize}
  634. # NOTE: Could pass (dtype.type, structure) to preserve record dtypes...
  635. return np.dtype(structure, align=dtype.isalignedstruct)
  636. elif dtype.subdtype is not None:
  637. # subarray dtype
  638. subdtype, shape = dtype.subdtype
  639. new_subdtype = drop_metadata(subdtype)
  640. if dtype.metadata is None and new_subdtype is subdtype:
  641. return dtype
  642. return np.dtype((new_subdtype, shape))
  643. else:
  644. # Normal unstructured dtype
  645. if dtype.metadata is None:
  646. return dtype
  647. # Note that `dt.str` doesn't round-trip e.g. for user-dtypes.
  648. return np.dtype(dtype.str)