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

Avoid complex->real casts via jax.numpy.astype #236

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions jax_cfd/base/fast_diagonalization.py
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,13 @@ def apply(rhs: Array) -> Array:
return apply


def _cast(x, dtype):
if (np.issubdtype(x.dtype, np.complexfloating)
and not np.issubdtype(dtype, np.complexfloating)):
x = x.real
return x.astype(dtype)


def _circulant_fft_transform(
func: Callable[[Array], Array],
operators: Sequence[np.ndarray],
Expand All @@ -184,7 +191,7 @@ def _circulant_fft_transform(
def apply(rhs: Array) -> Array:
if rhs.shape != shape:
raise ValueError(f'rhs.shape={rhs.shape} does not match shape={shape}')
return jnp.fft.ifftn(diagonals * jnp.fft.fftn(rhs)).astype(dtype)
return _cast(jnp.fft.ifftn(diagonals * jnp.fft.fftn(rhs)), dtype)

return apply

Expand Down Expand Up @@ -213,7 +220,7 @@ def _circulant_rfft_transform(
def apply(rhs: Array) -> Array:
if rhs.dtype != dtype:
raise ValueError(f'rhs.dtype={rhs.dtype} does not match dtype={dtype}')
return jnp.fft.irfftn(diagonals * jnp.fft.rfftn(rhs)).astype(dtype)
return _cast(jnp.fft.irfftn(diagonals * jnp.fft.rfftn(rhs)), dtype)

return apply

Expand Down
Loading