Convert a function to a numpy function. Parameters ---------- fun : callable The function to convert. arr : array-like The input to test the function. Can be from any backend. nx : Backend The backend to use for the conversion. warn : bool, optional
(fun, arr, nx, warn=True)
| 1481 | |
| 1482 | |
| 1483 | def fun_to_numpy(fun, arr, nx, warn=True): |
| 1484 | """Convert a function to a numpy function. |
| 1485 | |
| 1486 | Parameters |
| 1487 | ---------- |
| 1488 | fun : callable |
| 1489 | The function to convert. |
| 1490 | arr : array-like |
| 1491 | The input to test the function. Can be from any backend. |
| 1492 | nx : Backend |
| 1493 | The backend to use for the conversion. |
| 1494 | warn : bool, optional |
| 1495 | Whether to raise a warning if the function is not compatible with numpy. |
| 1496 | Default is True. |
| 1497 | Returns |
| 1498 | ------- |
| 1499 | fun_numpy : callable |
| 1500 | The converted function. |
| 1501 | """ |
| 1502 | if arr is None: |
| 1503 | raise ValueError("arr should not be None to test fun") |
| 1504 | |
| 1505 | nx_arr = get_backend(arr) |
| 1506 | if nx_arr.__name__ != "numpy": |
| 1507 | arr = nx.to_numpy(arr) |
| 1508 | try: |
| 1509 | fun(arr) |
| 1510 | return fun |
| 1511 | except BaseException: |
| 1512 | if warn: |
| 1513 | warnings.warn( |
| 1514 | "The callable function should be able to handle numpy arrays, a compatible function is created and comes with overhead" |
| 1515 | ) |
| 1516 | |
| 1517 | def fun_numpy(x): |
| 1518 | return nx.to_numpy(fun(nx.from_numpy(x))) |
| 1519 | |
| 1520 | return fun_numpy |
no test coverage detected