Generates a pretty printed NumPy array with an assignment. Optionally transposes column vectors so they are drawn on one line. Strictly speaking arr can be any time convertible by `str(arr)`, but the output may not be what you want if the type of the variable is not a scalar or an
(label, arr)
| 237 | |
| 238 | |
| 239 | def pretty_str(label, arr): |
| 240 | """ |
| 241 | Generates a pretty printed NumPy array with an assignment. Optionally |
| 242 | transposes column vectors so they are drawn on one line. Strictly speaking |
| 243 | arr can be any time convertible by `str(arr)`, but the output may not |
| 244 | be what you want if the type of the variable is not a scalar or an |
| 245 | ndarray. |
| 246 | |
| 247 | Examples |
| 248 | -------- |
| 249 | >>> pprint('cov', np.array([[4., .1], [.1, 5]])) |
| 250 | cov = [[4. 0.1] |
| 251 | [0.1 5. ]] |
| 252 | |
| 253 | >>> print(pretty_str('x', np.array([[1], [2], [3]]))) |
| 254 | x = [[1 2 3]].T |
| 255 | """ |
| 256 | |
| 257 | def is_col(a): |
| 258 | """ return true if a is a column vector""" |
| 259 | try: |
| 260 | return a.shape[0] > 1 and a.shape[1] == 1 |
| 261 | except (AttributeError, IndexError): |
| 262 | return False |
| 263 | |
| 264 | if label is None: |
| 265 | label = '' |
| 266 | |
| 267 | if label: |
| 268 | label += ' = ' |
| 269 | |
| 270 | if is_col(arr): |
| 271 | return label + str(arr.T).replace('\n', '') + '.T' |
| 272 | |
| 273 | rows = str(arr).split('\n') |
| 274 | if not rows: |
| 275 | return '' |
| 276 | |
| 277 | s = label + rows[0] |
| 278 | pad = ' ' * len(label) |
| 279 | for line in rows[1:]: |
| 280 | s = s + '\n' + pad + line |
| 281 | |
| 282 | return s |
| 283 | |
| 284 | |
| 285 | def pprint(label, arr, **kwargs): |
no test coverage detected