Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Suggested real and complex dtype functions #13

Open
izaid opened this issue Oct 7, 2024 · 2 comments
Open

Suggested real and complex dtype functions #13

izaid opened this issue Oct 7, 2024 · 2 comments

Comments

@izaid
Copy link

izaid commented Oct 7, 2024

Hello! Very excited about this library, as it (hopefully) provides a place to put functions that are array agnostic and usable by many people. Let me describe two simple ones that I'd like to make a PR for.

I'd like to add functions real_type(dtype) and complex_type(dtype). These are simple:

  • real_type takes in a real or complex dtype, and returns the corresponding floating-point dtype. So complex128 -> float64, complex64 -> float32, float64 -> float64, float32 -> float32.
  • complex_type takes in a real or complex dtype, and returns the corresponding complex floating-point dtype. So float64 -> complex128, float32 -> complex64, complex128 -> complex128, complex64 -> complex64.

This can be really helpful in application code to work out the correct types. Shall I make a PR for these?

@lucascolley
Copy link
Collaborator

lucascolley commented Oct 7, 2024

consumer libraries definitely want things along these lines, yes. I recently wrote this in SciPy:

def xp_float_to_complex(arr: Array, xp: ModuleType | None = None) -> Array:
    xp = array_namespace(arr) if xp is None else xp
    arr_dtype = arr.dtype
    # The standard float dtypes are float32 and float64.
    # Convert float32 to complex64,
    # and float64 (and non-standard real dtypes) to complex128
    if xp.isdtype(arr_dtype, xp.float32):
        arr = xp.astype(arr, xp.complex64)
    elif xp.isdtype(arr_dtype, 'real floating'):
        arr = xp.astype(arr, xp.complex128)

    return arr

and there is also the more elaborate xp_broadcast_promote in https://github.com/scipy/scipy/blob/main/scipy/_lib/_array_api.py.

Could either of those functions be written more simply using the functions you propose?

I would probably suggest hashing out the behaviour more fully before opening a PR. What should the functions do for other standard dtypes like int64? Also, I think it would be in the spirit of this library (in its current form) to error on any object that isn’t a standard dtype.

@asmeurer
Copy link
Member

asmeurer commented Oct 8, 2024

There was also some recent discussion about what a standardized API for this could look like data-apis/array-api#841 (comment)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants