print_coercion_tables.py 6.0 KB

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