print_coercion_tables.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. #!/usr/bin/env python3
  2. """Prints type-coercion tables for the built-in NumPy types
  3. """
  4. import numpy as np
  5. from numpy._core.numerictypes import obj2sctype
  6. from collections import namedtuple
  7. # Generic object that can be added, but doesn't do anything else
  8. class GenericObject:
  9. def __init__(self, v):
  10. self.v = v
  11. def __add__(self, other):
  12. return self
  13. def __radd__(self, other):
  14. return self
  15. dtype = np.dtype('O')
  16. def print_cancast_table(ntypes):
  17. print('X', end=' ')
  18. for char in ntypes:
  19. print(char, end=' ')
  20. print()
  21. for row in ntypes:
  22. print(row, end=' ')
  23. for col in ntypes:
  24. if np.can_cast(row, col, "equiv"):
  25. cast = "#"
  26. elif np.can_cast(row, col, "safe"):
  27. cast = "="
  28. elif np.can_cast(row, col, "same_kind"):
  29. cast = "~"
  30. elif np.can_cast(row, col, "unsafe"):
  31. cast = "."
  32. else:
  33. cast = " "
  34. print(cast, end=' ')
  35. print()
  36. def print_coercion_table(ntypes, inputfirstvalue, inputsecondvalue, firstarray, use_promote_types=False):
  37. print('+', end=' ')
  38. for char in ntypes:
  39. print(char, end=' ')
  40. print()
  41. for row in ntypes:
  42. if row == 'O':
  43. rowtype = GenericObject
  44. else:
  45. rowtype = obj2sctype(row)
  46. print(row, end=' ')
  47. for col in ntypes:
  48. if col == 'O':
  49. coltype = GenericObject
  50. else:
  51. coltype = obj2sctype(col)
  52. try:
  53. if firstarray:
  54. rowvalue = np.array([rowtype(inputfirstvalue)], dtype=rowtype)
  55. else:
  56. rowvalue = rowtype(inputfirstvalue)
  57. colvalue = coltype(inputsecondvalue)
  58. if use_promote_types:
  59. char = np.promote_types(rowvalue.dtype, colvalue.dtype).char
  60. else:
  61. value = np.add(rowvalue, colvalue)
  62. if isinstance(value, np.ndarray):
  63. char = value.dtype.char
  64. else:
  65. char = np.dtype(type(value)).char
  66. except ValueError:
  67. char = '!'
  68. except OverflowError:
  69. char = '@'
  70. except TypeError:
  71. char = '#'
  72. print(char, end=' ')
  73. print()
  74. def print_new_cast_table(*, can_cast=True, legacy=False, flags=False):
  75. """Prints new casts, the values given are default "can-cast" values, not
  76. actual ones.
  77. """
  78. from numpy._core._multiarray_tests import get_all_cast_information
  79. cast_table = {
  80. -1: " ",
  81. 0: "#", # No cast (classify as equivalent here)
  82. 1: "#", # equivalent casting
  83. 2: "=", # safe casting
  84. 3: "~", # same-kind casting
  85. 4: ".", # unsafe casting
  86. }
  87. flags_table = {
  88. 0 : "▗", 7: "█",
  89. 1: "▚", 2: "▐", 4: "▄",
  90. 3: "▜", 5: "▙",
  91. 6: "▟",
  92. }
  93. cast_info = namedtuple("cast_info", ["can_cast", "legacy", "flags"])
  94. no_cast_info = cast_info(" ", " ", " ")
  95. casts = get_all_cast_information()
  96. table = {}
  97. dtypes = set()
  98. for cast in casts:
  99. dtypes.add(cast["from"])
  100. dtypes.add(cast["to"])
  101. if cast["from"] not in table:
  102. table[cast["from"]] = {}
  103. to_dict = table[cast["from"]]
  104. can_cast = cast_table[cast["casting"]]
  105. legacy = "L" if cast["legacy"] else "."
  106. flags = 0
  107. if cast["requires_pyapi"]:
  108. flags |= 1
  109. if cast["supports_unaligned"]:
  110. flags |= 2
  111. if cast["no_floatingpoint_errors"]:
  112. flags |= 4
  113. flags = flags_table[flags]
  114. to_dict[cast["to"]] = cast_info(can_cast=can_cast, legacy=legacy, flags=flags)
  115. # The np.dtype(x.type) is a bit strange, because dtype classes do
  116. # not expose much yet.
  117. types = np.typecodes["All"]
  118. def sorter(x):
  119. # This is a bit weird hack, to get a table as close as possible to
  120. # the one printing all typecodes (but expecting user-dtypes).
  121. dtype = np.dtype(x.type)
  122. try:
  123. indx = types.index(dtype.char)
  124. except ValueError:
  125. indx = np.inf
  126. return (indx, dtype.char)
  127. dtypes = sorted(dtypes, key=sorter)
  128. def print_table(field="can_cast"):
  129. print('X', end=' ')
  130. for dt in dtypes:
  131. print(np.dtype(dt.type).char, end=' ')
  132. print()
  133. for from_dt in dtypes:
  134. print(np.dtype(from_dt.type).char, end=' ')
  135. row = table.get(from_dt, {})
  136. for to_dt in dtypes:
  137. print(getattr(row.get(to_dt, no_cast_info), field), end=' ')
  138. print()
  139. if can_cast:
  140. # Print the actual table:
  141. print()
  142. print("Casting: # is equivalent, = is safe, ~ is same-kind, and . is unsafe")
  143. print()
  144. print_table("can_cast")
  145. if legacy:
  146. print()
  147. print("L denotes a legacy cast . a non-legacy one.")
  148. print()
  149. print_table("legacy")
  150. if flags:
  151. print()
  152. print(f"{flags_table[0]}: no flags, {flags_table[1]}: PyAPI, "
  153. f"{flags_table[2]}: supports unaligned, {flags_table[4]}: no-float-errors")
  154. print()
  155. print_table("flags")
  156. if __name__ == '__main__':
  157. print("can cast")
  158. print_cancast_table(np.typecodes['All'])
  159. print()
  160. print("In these tables, ValueError is '!', OverflowError is '@', TypeError is '#'")
  161. print()
  162. print("scalar + scalar")
  163. print_coercion_table(np.typecodes['All'], 0, 0, False)
  164. print()
  165. print("scalar + neg scalar")
  166. print_coercion_table(np.typecodes['All'], 0, -1, False)
  167. print()
  168. print("array + scalar")
  169. print_coercion_table(np.typecodes['All'], 0, 0, True)
  170. print()
  171. print("array + neg scalar")
  172. print_coercion_table(np.typecodes['All'], 0, -1, True)
  173. print()
  174. print("promote_types")
  175. print_coercion_table(np.typecodes['All'], 0, 0, False, True)
  176. print("New casting type promotion:")
  177. print_new_cast_table(can_cast=True, legacy=True, flags=True)