From aefef768930a2df2180e97d830054b7ebb11a38c Mon Sep 17 00:00:00 2001 From: Pearu Peterson Date: Sat, 21 Dec 2024 17:37:28 +0200 Subject: [PATCH 1/2] Add complex sqrt --- functional_algorithms/algorithms.py | 142 +++++++++++++++ functional_algorithms/targets/cpp.py | 1 + functional_algorithms/targets/numpy.py | 4 + functional_algorithms/targets/python.py | 1 + functional_algorithms/targets/stablehlo.py | 1 + functional_algorithms/targets/xla_client.py | 1 + functional_algorithms/tests/test_accuracy.py | 32 ++-- functional_algorithms/utils.py | 45 ++++- results/README.md | 2 + results/cpp/complex_sqrt.cpp | 84 +++++++++ results/estimate_accuracy.py | 4 +- results/numpy/sqrt.py | 137 ++++++++++++++ results/python/sqrt.py | 94 ++++++++++ results/stablehlo/sqrt.td | 180 +++++++++++++++++++ results/xla_client/complex_sqrt.cc | 81 +++++++++ 15 files changed, 789 insertions(+), 20 deletions(-) create mode 100644 results/cpp/complex_sqrt.cpp create mode 100644 results/numpy/sqrt.py create mode 100644 results/python/sqrt.py create mode 100644 results/stablehlo/sqrt.td create mode 100644 results/xla_client/complex_sqrt.cc diff --git a/functional_algorithms/algorithms.py b/functional_algorithms/algorithms.py index 5f2f104..ea880f4 100644 --- a/functional_algorithms/algorithms.py +++ b/functional_algorithms/algorithms.py @@ -88,6 +88,24 @@ def wrapper(ctx, *args, **kwargs): return wrapper +@definition("conj", domain="complex") +def complex_conj(ctx, z: complex): + """Conjugate of complex inputs.""" + return ctx.complex(z.real, -z.imag) + + +@definition("conj", domain="real") +def real_conj(ctx, z: float): + """Conjugate of real inputs.""" + return NotImplemented + + +@definition("conj") +def conj(ctx, z: float | complex): + """Conjugate of real and complex inputs.""" + assert 0 # unreachable + + @definition("square", domain="real") def real_square(ctx, x: float): """Square on real input: x * x""" @@ -1306,3 +1324,127 @@ def tanh(ctx, z: complex | float): See complex_atan for more information. """ assert 0 # unreachable + + +@definition("sqrt", domain="real") +def real_sqrt(ctx, z: float): + """Square root on real inputs""" + return NotImplemented + + +@definition("sqrt", domain="complex") +def complex_sqrt(ctx, z: complex): + """Square root on complex inputs: + + sqrt(z) = sqrt((hypot(x, y) + x)/2) + I * sgn(y) * sqrt((hypot(x, y) - x) / 2) + + where sgn(y) = 1 if y >= 0, and sgn(y) = -1 otherwise. + + + Algorithm + --------- + + In the above formula, catastrophic cancellation errors occur in + the imaginary part when x is positive, and in the real part when x + is negative. To avoid these, let us define + + u = sqrt((hypot(x, y) + abs(x))/2) + v = sgn(y) * sqrt((hypot(x, y) - abs(x))/2) + + and find + + u * v = sgn(y) * sqrt(hypot(x, y) ** 2 - x ** 2) / 2 = y / 2 + + That is, if x > 0, then we have + + sqrt(z) = u + I * y / u / 2 + + and if x < 0, + + sqrt(z) = abs(y) / u / 2 + I * sgn(y) * u + + If abs(x) and abs(y) are smaller that smallest normal, then as a + result of underflow, u will be zero and v will be undefined. On + the other hand, if abs(x) and abs(y) are close to largest floating + point number, then `hypot(x, y) + abs(x)` will overflow, and u + will be `inf`. To address the issues from underflow and overflow, + we'll use the following formula: + + 1. abs(x) == abs(y), or abs(x) == inf and abs(y) == inf, then + + u_eq = sqrt(abs(x)) * sqrt((1 + sqrt(2))/2) + abs(y) / u = sqrt(abs(x)) / sqrt((1 + sqrt(2))/2) + + 2. If abs(x) > abs(y) and u == 0 (the underflow case) or u == inf + (the overflow case), denote r = abs(y) / abs(x), then + + u_gt = sqrt(abs(x)) * sqrt((1 + hypot(1, r)) / 2) + abs(y) / u = sqrt(abs(y)) * sqrt(r) / sqrt((1 + hypot(1, r)) / 2) + + 3. If abs(x) < abs(y) and u == 0 (the underflow case) or u == inf + (the overflow case), denote r = abs(x) / abs(y), then + + u_lt = sqrt(abs(y)) * sqrt((r + sqrt(1, r)) / 2) + abs(y) / u = sqrt(abs(y)) / sqrt((r + sqrt(1, r)) / 2) + """ + x = z.real + y = z.imag + ax = abs(x) + ay = abs(y) + sq_ax = ctx.sqrt(ax) + sq_ay = ctx.sqrt(ay) + + one = ctx.constant(1, x) + two = ctx.constant(2, x) + + if ctx.alt is None: + sq_2 = ctx.sqrt(two) + sq_12 = ctx.sqrt(one + sq_2) + else: + sq_2_ = ctx.alt.sqrt(2) + sq_12_ = ctx.alt.sqrt(1 + sq_2_) + sq_2 = ctx.constant(sq_2_, x) + sq_12 = ctx.constant(sq_12_, x) + + u_general = ctx.sqrt((ctx.hypot(ax, ay) / two + ax / two)) + ay_div_u_general = ay / (u_general * two) + + r = ctx.select(ax == ay, one, ctx.select(ax < ay, ax / ay, ay / ax)) + sq_r = ctx.select(ax == ay, one, ctx.select(ax < ay, sq_ax / sq_ay, sq_ay / sq_ax)) + + h = ctx.hypot(one, r) + + u_eq = sq_ax * sq_12 / sq_2 + ay_div_eq = sq_ay / (sq_12 * sq_2) + + sq_1h = ctx.sqrt(one + h) + u_gt = sq_ax * (sq_1h / sq_2) + ay_div_u_gt = sq_ay * sq_r / (sq_1h * sq_2) + + sq_rh = ctx.sqrt(r + h) + u_lt = sq_ay * (sq_rh / sq_2) + ay_div_u_lt = sq_ay / (sq_rh * sq_2) + + u = ctx.select( + ax == ay, u_eq, ctx.select(ctx.Or(u_general == 0, u_general.is_posinf), ctx.select(ax > ay, u_gt, u_lt), u_general) + ) + ay_div_u = ctx.select( + ax == ay, + ay_div_eq, + ctx.select( + ctx.Or(u_general == 0, u_general.is_posinf), ctx.select(ax > ay, ay_div_u_gt, ay_div_u_lt), ay_div_u_general + ), + ) + + re = ctx.select(x >= 0, u, ay_div_u) + im = ctx.select(x < 0, ctx.select(y < 0, -u, u), ctx.select(y < 0, -ay_div_u, ay_div_u)) + return ctx(ctx.complex(re, im)) + + +@definition("sqrt") +def sqrt(ctx, z: complex | float): + """Square root on complex and real inputs. + + See complex_sqrt for more information. + """ + assert 0 # unreachable diff --git a/functional_algorithms/targets/cpp.py b/functional_algorithms/targets/cpp.py index 463a7f4..cbc0cd6 100644 --- a/functional_algorithms/targets/cpp.py +++ b/functional_algorithms/targets/cpp.py @@ -28,6 +28,7 @@ # real_asin=[(":float", ":float")], # square=[(":float", ":float"), (":complex", ":complex")], # asin=[(":float", ":float"), (":complex", ":complex")], + complex_sqrt=[(":complex", ":complex")], ) source_file_extension = ".cpp" diff --git a/functional_algorithms/targets/numpy.py b/functional_algorithms/targets/numpy.py index 6c3bcc4..af54796 100644 --- a/functional_algorithms/targets/numpy.py +++ b/functional_algorithms/targets/numpy.py @@ -78,6 +78,10 @@ def downcast_func(target, expr): log1p=[(":complex128",), (":complex64",), (":float64",), (":float32",)], hypot=[(":float32", ":float32"), (":float64", ":float64")], square=[(":complex128",), (":complex64",), (":float64",), (":float32",)], + sqrt=[ + (":complex128",), + (":complex64",), + ], ) diff --git a/functional_algorithms/targets/python.py b/functional_algorithms/targets/python.py index 726d35e..caa318b 100644 --- a/functional_algorithms/targets/python.py +++ b/functional_algorithms/targets/python.py @@ -32,6 +32,7 @@ def __rewrite_modifier__(expr): hypot=[(":float", ":float")], square=[(":float",), (":complex",)], log1p=[(":float",), (":complex",)], + sqrt=[(":float",), (":complex",)][1:], ) diff --git a/functional_algorithms/targets/stablehlo.py b/functional_algorithms/targets/stablehlo.py index 41ea544..2a5783a 100644 --- a/functional_algorithms/targets/stablehlo.py +++ b/functional_algorithms/targets/stablehlo.py @@ -20,6 +20,7 @@ log1p=[(":float",), (":complex",)], hypot=[(":float", ":float")], square=[(":float",), (":complex",)], + sqrt=[(":complex",)], ) diff --git a/functional_algorithms/targets/xla_client.py b/functional_algorithms/targets/xla_client.py index 7351ff8..4bfae56 100644 --- a/functional_algorithms/targets/xla_client.py +++ b/functional_algorithms/targets/xla_client.py @@ -29,6 +29,7 @@ atan=[(":float", ":float"), (":complex", ":complex")], atanh=[(":float", ":float"), (":complex", ":complex")], complex_log1p=[(":complex", ":complex")], + complex_sqrt=[(":complex", ":complex")], ) source_file_extension = ".cc" diff --git a/functional_algorithms/tests/test_accuracy.py b/functional_algorithms/tests/test_accuracy.py index 7241669..1c08dd3 100644 --- a/functional_algorithms/tests/test_accuracy.py +++ b/functional_algorithms/tests/test_accuracy.py @@ -1,10 +1,11 @@ import numpy import functional_algorithms as fa +import os import pytest import warnings -@pytest.fixture(scope="function", params=["jax"]) +@pytest.fixture(scope="function", params=["jax", "functional_algorithms"]) def backend(request): return request.param @@ -25,9 +26,17 @@ def dtype(request): def test_unary(unary_func_name, backend, device, dtype): - pytest.importorskip(backend) + if backend == "functional_algorithms": + backend = "algorithms" + else: + pytest.importorskip(backend) - func = getattr(getattr(fa.utils, f"numpy_with_{backend}")(device=device), unary_func_name) + try: + func = getattr(getattr(fa.utils, f"numpy_with_{backend}")(device=device, dtype=dtype), unary_func_name) + except NotImplementedError as msg: + pytest.skip(f"{unary_func_name}: {msg}") + except AttributeError as msg: + pytest.skip(f"{unary_func_name}: {msg}") if not func.backend_is_available(device): pytest.skip(f"{device} support is unavailable") @@ -43,7 +52,7 @@ def test_unary(unary_func_name, backend, device, dtype): # and smallest normal is defined as 1). fi = numpy.finfo(dtype) x = numpy.sqrt(fi.smallest_normal) * dtype(0.5) - v1 = getattr(getattr(fa.utils, f"numpy_with_{backend}")(device=device), "square")(x) + v1 = getattr(getattr(fa.utils, f"numpy_with_{backend}")(device=device, dtype=dtype), "square")(x) v2 = numpy.square(x) d = fa.utils.diff_ulp(v1, v2) if d > 1000: @@ -56,11 +65,10 @@ def test_unary(unary_func_name, backend, device, dtype): reference = getattr(mpmath, unary_func_name) npy_reference = getattr(fa.utils.numpy_with_numpy(), unary_func_name) - re_blocks, im_blocks = 101, 52 - re_blocksize, im_blocksize = 20, 20 - - if 0: - # used for testing + if int(os.environ.get("FA_HIGH_RESOLUTION", "0")): + re_blocks, im_blocks = 101, 52 + re_blocksize, im_blocksize = 20, 20 + else: re_blocks, im_blocks = 51, 26 re_blocksize, im_blocksize = 5, 5 @@ -156,7 +164,7 @@ def test_unary(unary_func_name, backend, device, dtype): print(timage) print() - if fa_reference is not None: + if fa_reference is not None and backend != "algorithms": rows = [ ( "ULP-difference", @@ -188,7 +196,7 @@ def test_unary(unary_func_name, backend, device, dtype): clusters = fa.utils.Clusters() for re, im in zip(*numpy.where(ulp == value)): clusters.add((re, im)) - for cluster in clusters: + for cluster in clusters.clusters + clusters.split().clusters: re, im = cluster.center_point() with warnings.catch_warnings(action="ignore"): np_value = npy_reference(samples[re, im]) @@ -209,4 +217,4 @@ def test_unary(unary_func_name, backend, device, dtype): col_fmt = "| " + " | ".join([f"{{{i}:>{w}}}" for i, w in enumerate(col_widths)]) + " |" print("\n".join([col_fmt.format(*map(str, row)) for row in rows])) - pytest.xfail("inaccurate or incorrect results") + # pytest.xfail("inaccurate or incorrect results") diff --git a/functional_algorithms/utils.py b/functional_algorithms/utils.py index 5285d38..40d9810 100644 --- a/functional_algorithms/utils.py +++ b/functional_algorithms/utils.py @@ -1,3 +1,4 @@ +import contextlib import itertools import numpy import math @@ -652,6 +653,26 @@ def context_from_backend(self, sample): return jax.default_device(jax.devices(self.device)[0]) +class vectorize_with_numpy(vectorize_with_backend): + + def backend_context(self, context): + return contextlib.nullcontext() + + def context_from_backend(self, obj): + return contextlib.nullcontext() + + def numpy_to_backend(self, arr): + return arr + + def numpy_from_backend(self, obj): + assert isinstance(obj, numpy.ndarray), type(obj) + return obj + + @property + def backend_types(self): + return (numpy.ndarray,) + + class mpmath_array_api: """Array API interface to mpmath functions including workarounds to mpmath bugs. @@ -1103,19 +1124,20 @@ def __getattr__(self, name): name = dict(arcsinh="asinh", arccos="acos", arcsin="asin", arccosh="acosh", arctan="atan", arctanh="atanh").get( name, name ) - if name in self._vfunc_cache: - return self._vfunc_cache[name] + dtype = self.params["dtype"] + key = name, dtype.__name__ + if key in self._vfunc_cache: + return self._vfunc_cache[key] import functional_algorithms as fa import numpy - dtype = self.params["dtype"] ctx = fa.Context(paths=[fa.algorithms]) graph = ctx.trace(getattr(fa.algorithms, name), dtype) graph2 = graph.rewrite(fa.targets.numpy, fa.rewrite) - func = fa.targets.numpy.as_function(graph2, debug=0) - vfunc = numpy.vectorize(func) - self._vfunc_cache[name] = vfunc + func = fa.targets.numpy.as_function(graph2, debug=self.params.get("debug", 0)) + vfunc = vectorize_with_numpy(func) + self._vfunc_cache[key] = vfunc return vfunc @@ -1947,3 +1969,14 @@ def add(self, point): def __iter__(self): return iter(self.clusters) + + def split(self): + """Split clusters by discarding the their center points.""" + result = type(self)() + for index, cluster in enumerate(self.clusters): + center = cluster.center_point() + for point in cluster.points: + if point == center: + continue + result.add(point) + return result diff --git a/results/README.md b/results/README.md index 6be551d..ebacdf9 100644 --- a/results/README.md +++ b/results/README.md @@ -84,6 +84,8 @@ Finally, | square | complex128 | 995705 | 6296 | - | - | - | - | | sqrt | float32 | 1000001 | - | - | - | - | using native sqrt | | sqrt | complex64 | 639573 | 362328 | 100 | - | - | using native sqrt | +| sqrt2 | complex64 | 639573 | 362328 | 100 | - | - | using native sqrt | +| sqrt | complex128 | 637905 | 364008 | 88 | - | - | - | | angle | complex64 | 940289 | 61332 | 376 | 4 | - | - | | angle | complex128 | 989787 | 12214 | - | - | - | - | | log1p | complex64 | 905931 | 94401 | 1661 | 8 | - | - | diff --git a/results/cpp/complex_sqrt.cpp b/results/cpp/complex_sqrt.cpp new file mode 100644 index 0000000..ee88cfa --- /dev/null +++ b/results/cpp/complex_sqrt.cpp @@ -0,0 +1,84 @@ +// This file is generated using functional_algorithms tool (0.11.1), see +// https://github.com/pearu/functional_algorithms +// for more information. + + + +#include +#include +#include +#include +#include + + +std::complex complex_sqrt_0(std::complex z) { + double x = (z).real(); + double constant_f0 = 0.0; + double ax = std::abs(x); + double y = (z).imag(); + double ay = std::abs(y); + bool eq_ax_ay = (ax) == (ay); + double sq_ax = std::sqrt(ax); + double sq_2 = 1.4142135623730951; + double mx = std::max(ax, ay); + double mn = std::min(ax, ay); + double one = 1.0; + double mn_over_mx = (mn) / (mx); + double r = (mn_over_mx) * (mn_over_mx); + double sqa = std::sqrt((one) + (r)); + double two = 2.0; + double u_general = std::sqrt( + (((((mx) == (mn)) ? ((sq_2) * (mx)) + : (((((sqa) == (one)) && ((r) > (constant_f0))) + ? ((mx) + (((mx) * (r)) / (two))) + : ((mx) * (sqa)))))) / + (two)) + + ((ax) / (two))); + bool logical_or_eq_u_general_constant_f0_eq_u_general_constant_posinf = + ((u_general) == (constant_f0)) || + ((u_general) == (std::numeric_limits::infinity())); + bool gt_ax_ay = (ax) > (ay); + bool lt_ax_ay = (ax) < (ay); + double _r_0_ = + ((eq_ax_ay) ? (one) : (((lt_ax_ay) ? ((ax) / (ay)) : ((ay) / (ax))))); + double abs__r_0_ = std::abs(_r_0_); + double _mx_0_ = std::max(one, abs__r_0_); + double _mn_0_ = std::min(one, abs__r_0_); + double _mn_over_mx_0_ = (_mn_0_) / (_mx_0_); + double _r_1_ = (_mn_over_mx_0_) * (_mn_over_mx_0_); + double _sqa_0_ = std::sqrt((one) + (_r_1_)); + double h = (((_mx_0_) == (_mn_0_)) + ? ((sq_2) * (_mx_0_)) + : (((((_sqa_0_) == (one)) && ((_r_1_) > (constant_f0))) + ? ((_mx_0_) + (((_mx_0_) * (_r_1_)) / (two))) + : ((_mx_0_) * (_sqa_0_))))); + double sq_1h = std::sqrt((one) + (h)); + double sq_ay = std::sqrt(ay); + double sq_rh = std::sqrt((_r_0_) + (h)); + double u = + ((eq_ax_ay) + ? (((sq_ax) * (1.5537739740300374)) / (sq_2)) + : (((logical_or_eq_u_general_constant_f0_eq_u_general_constant_posinf) + ? (((gt_ax_ay) ? ((sq_ax) * ((sq_1h) / (sq_2))) + : ((sq_ay) * ((sq_rh) / (sq_2))))) + : (u_general)))); + double ay_div_u = + ((eq_ax_ay) + ? ((sq_ay) / (2.19736822693562)) + : (((logical_or_eq_u_general_constant_f0_eq_u_general_constant_posinf) + ? (((gt_ax_ay) + ? (((sq_ay) * + (((eq_ax_ay) + ? (one) + : (((lt_ax_ay) ? ((sq_ax) / (sq_ay)) + : ((sq_ay) / (sq_ax))))))) / + ((sq_1h) * (sq_2))) + : ((sq_ay) / ((sq_rh) * (sq_2))))) + : ((ay) / ((u_general) * (two)))))); + bool lt_y_constant_f0 = (y) < (constant_f0); + return std::complex( + (((x) >= (constant_f0)) ? (u) : (ay_div_u)), + (((x) < (constant_f0)) + ? (((lt_y_constant_f0) ? (-(u)) : (u))) + : (((lt_y_constant_f0) ? (-(ay_div_u)) : (ay_div_u))))); +} \ No newline at end of file diff --git a/results/estimate_accuracy.py b/results/estimate_accuracy.py index 56f9662..02df35e 100644 --- a/results/estimate_accuracy.py +++ b/results/estimate_accuracy.py @@ -83,9 +83,9 @@ def get_inputs(): # ("sqrt", np.float32, {}), # real_sqrt is not implemented ("sqrt", np.float32, dict(use_native_sqrt=True)), # ("sqrt", np.float64, {}), # real_sqrt is not implemented - # ("sqrt", np.complex64, {}), # complex_sqrt is not implemented + ("sqrt", np.complex64, {}), ("sqrt", np.complex64, dict(use_native_sqrt=True)), - # ("sqrt", np.complex128, {}), # complex_sqrt is not implemented + ("sqrt", np.complex128, {}), ("angle", np.complex64, {}), ("angle", np.complex128, {}), # ("log1p", np.float32, {}), # real_log1p is not implemented diff --git a/results/numpy/sqrt.py b/results/numpy/sqrt.py new file mode 100644 index 0000000..4bbb295 --- /dev/null +++ b/results/numpy/sqrt.py @@ -0,0 +1,137 @@ +# This file is generated using functional_algorithms tool (0.11.1), see +# https://github.com/pearu/functional_algorithms +# for more information. + + +import numpy +import warnings + + +def make_complex(r, i): + if r.dtype == numpy.float32 and i.dtype == numpy.float32: + return numpy.array([r, i]).view(numpy.complex64)[0] + elif i.dtype == numpy.float64 and i.dtype == numpy.float64: + return numpy.array([r, i]).view(numpy.complex128)[0] + raise NotImplementedError((r.dtype, i.dtype)) + + +def sqrt_0(z: numpy.complex128) -> numpy.complex128: + with warnings.catch_warnings(action="ignore"): + z = numpy.complex128(z) + x: numpy.float64 = (z).real + constant_f0: numpy.float64 = numpy.float64(0.0) + ax: numpy.float64 = numpy.abs(x) + y: numpy.float64 = (z).imag + ay: numpy.float64 = numpy.abs(y) + eq_ax_ay: numpy.bool_ = numpy.equal(ax, ay, dtype=numpy.bool_) + sq_ax: numpy.float64 = numpy.sqrt(ax) + sq_2: numpy.float64 = numpy.float64(1.4142135623730951) + two: numpy.float64 = numpy.float64(2.0) + u_general: numpy.float64 = numpy.sqrt(((numpy.hypot(ax, ay)) / (two)) + ((ax) / (two))) + logical_or_eq_u_general_constant_f0_eq_u_general_constant_posinf: numpy.bool_ = ( + numpy.equal(u_general, constant_f0, dtype=numpy.bool_) + ) or (numpy.equal(u_general, numpy.float64(numpy.inf), dtype=numpy.bool_)) + gt_ax_ay: numpy.bool_ = (ax) > (ay) + one: numpy.float64 = numpy.float64(1.0) + lt_ax_ay: numpy.bool_ = (ax) < (ay) + r: numpy.float64 = (one) if (eq_ax_ay) else (((ax) / (ay)) if (lt_ax_ay) else ((ay) / (ax))) + h: numpy.float64 = numpy.hypot(one, r) + sq_1h: numpy.float64 = numpy.sqrt((one) + (h)) + sq_ay: numpy.float64 = numpy.sqrt(ay) + sq_rh: numpy.float64 = numpy.sqrt((r) + (h)) + u: numpy.float64 = ( + (((sq_ax) * (numpy.float64(1.5537739740300374))) / (sq_2)) + if (eq_ax_ay) + else ( + (((sq_ax) * ((sq_1h) / (sq_2))) if (gt_ax_ay) else ((sq_ay) * ((sq_rh) / (sq_2)))) + if (logical_or_eq_u_general_constant_f0_eq_u_general_constant_posinf) + else (u_general) + ) + ) + ay_div_u: numpy.float64 = ( + ((sq_ay) / (numpy.float64(2.19736822693562))) + if (eq_ax_ay) + else ( + ( + ( + ((sq_ay) * ((one) if (eq_ax_ay) else (((sq_ax) / (sq_ay)) if (lt_ax_ay) else ((sq_ay) / (sq_ax))))) + / ((sq_1h) * (sq_2)) + ) + if (gt_ax_ay) + else ((sq_ay) / ((sq_rh) * (sq_2))) + ) + if (logical_or_eq_u_general_constant_f0_eq_u_general_constant_posinf) + else ((ay) / ((u_general) * (two))) + ) + ) + lt_y_constant_f0: numpy.bool_ = (y) < (constant_f0) + result = make_complex( + (u) if ((x) >= (constant_f0)) else (ay_div_u), + ( + ((-(u)) if (lt_y_constant_f0) else (u)) + if ((x) < (constant_f0)) + else ((-(ay_div_u)) if (lt_y_constant_f0) else (ay_div_u)) + ), + ) + return result + + +def sqrt_1(z: numpy.complex64) -> numpy.complex64: + with warnings.catch_warnings(action="ignore"): + z = numpy.complex64(z) + x: numpy.float32 = (z).real + constant_f0: numpy.float32 = numpy.float32(0.0) + ax: numpy.float32 = numpy.abs(x) + y: numpy.float32 = (z).imag + ay: numpy.float32 = numpy.abs(y) + eq_ax_ay: numpy.bool_ = numpy.equal(ax, ay, dtype=numpy.bool_) + sq_ax: numpy.float32 = numpy.sqrt(ax) + sq_2: numpy.float32 = numpy.float32(1.4142135) + two: numpy.float32 = numpy.float32(2.0) + u_general: numpy.float32 = numpy.sqrt(((numpy.hypot(ax, ay)) / (two)) + ((ax) / (two))) + logical_or_eq_u_general_constant_f0_eq_u_general_constant_posinf: numpy.bool_ = ( + numpy.equal(u_general, constant_f0, dtype=numpy.bool_) + ) or (numpy.equal(u_general, numpy.float32(numpy.inf), dtype=numpy.bool_)) + gt_ax_ay: numpy.bool_ = (ax) > (ay) + one: numpy.float32 = numpy.float32(1.0) + lt_ax_ay: numpy.bool_ = (ax) < (ay) + r: numpy.float32 = (one) if (eq_ax_ay) else (((ax) / (ay)) if (lt_ax_ay) else ((ay) / (ax))) + h: numpy.float32 = numpy.hypot(one, r) + sq_1h: numpy.float32 = numpy.sqrt((one) + (h)) + sq_ay: numpy.float32 = numpy.sqrt(ay) + sq_rh: numpy.float32 = numpy.sqrt((r) + (h)) + u: numpy.float32 = ( + (((sq_ax) * (numpy.float32(1.553774))) / (sq_2)) + if (eq_ax_ay) + else ( + (((sq_ax) * ((sq_1h) / (sq_2))) if (gt_ax_ay) else ((sq_ay) * ((sq_rh) / (sq_2)))) + if (logical_or_eq_u_general_constant_f0_eq_u_general_constant_posinf) + else (u_general) + ) + ) + ay_div_u: numpy.float32 = ( + ((sq_ay) / (numpy.float32(2.1973681))) + if (eq_ax_ay) + else ( + ( + ( + ((sq_ay) * ((one) if (eq_ax_ay) else (((sq_ax) / (sq_ay)) if (lt_ax_ay) else ((sq_ay) / (sq_ax))))) + / ((sq_1h) * (sq_2)) + ) + if (gt_ax_ay) + else ((sq_ay) / ((sq_rh) * (sq_2))) + ) + if (logical_or_eq_u_general_constant_f0_eq_u_general_constant_posinf) + else ((ay) / ((u_general) * (two))) + ) + ) + lt_y_constant_f0: numpy.bool_ = (y) < (constant_f0) + result = make_complex( + (u) if ((x) >= (constant_f0)) else (ay_div_u), + ( + ((-(u)) if (lt_y_constant_f0) else (u)) + if ((x) < (constant_f0)) + else ((-(ay_div_u)) if (lt_y_constant_f0) else (ay_div_u)) + ), + ) + return result diff --git a/results/python/sqrt.py b/results/python/sqrt.py new file mode 100644 index 0000000..e0e5c36 --- /dev/null +++ b/results/python/sqrt.py @@ -0,0 +1,94 @@ +# This file is generated using functional_algorithms tool (0.11.1), see +# https://github.com/pearu/functional_algorithms +# for more information. + + +import math +import sys + + +def sqrt_0(z: complex) -> complex: + x: float = (z).real + constant_f0: float = 0.0 + ax: float = abs(x) + y: float = (z).imag + ay: float = abs(y) + eq_ax_ay: bool = (ax) == (ay) + sq_ax: float = math.sqrt(ax) + sq_2: float = 1.4142135623730951 + mx: float = max(ax, ay) + mn: float = min(ax, ay) + one: float = 1.0 + mn_over_mx: float = (mn) / (mx) + r: float = (mn_over_mx) * (mn_over_mx) + sqa: float = math.sqrt((one) + (r)) + two: float = 2.0 + u_general: float = math.sqrt( + ( + ( + ((sq_2) * (mx)) + if ((mx) == (mn)) + else (((mx) + (((mx) * (r)) / (two))) if (((sqa) == (one)) and ((r) > (constant_f0))) else ((mx) * (sqa))) + ) + / (two) + ) + + ((ax) / (two)) + ) + logical_or_eq_u_general_constant_f0_eq_u_general_constant_posinf: bool = ((u_general) == (constant_f0)) or ( + (u_general) == (math.inf) + ) + gt_ax_ay: bool = (ax) > (ay) + lt_ax_ay: bool = (ax) < (ay) + _r_0_: float = (one) if (eq_ax_ay) else (((ax) / (ay)) if (lt_ax_ay) else ((ay) / (ax))) + abs__r_0_: float = abs(_r_0_) + _mx_0_: float = max(one, abs__r_0_) + _mn_0_: float = min(one, abs__r_0_) + _mn_over_mx_0_: float = (_mn_0_) / (_mx_0_) + _r_1_: float = (_mn_over_mx_0_) * (_mn_over_mx_0_) + _sqa_0_: float = math.sqrt((one) + (_r_1_)) + h: float = ( + ((sq_2) * (_mx_0_)) + if ((_mx_0_) == (_mn_0_)) + else ( + ((_mx_0_) + (((_mx_0_) * (_r_1_)) / (two))) + if (((_sqa_0_) == (one)) and ((_r_1_) > (constant_f0))) + else ((_mx_0_) * (_sqa_0_)) + ) + ) + sq_1h: float = math.sqrt((one) + (h)) + sq_ay: float = math.sqrt(ay) + sq_rh: float = math.sqrt((_r_0_) + (h)) + u: float = ( + (((sq_ax) * (1.5537739740300374)) / (sq_2)) + if (eq_ax_ay) + else ( + (((sq_ax) * ((sq_1h) / (sq_2))) if (gt_ax_ay) else ((sq_ay) * ((sq_rh) / (sq_2)))) + if (logical_or_eq_u_general_constant_f0_eq_u_general_constant_posinf) + else (u_general) + ) + ) + ay_div_u: float = ( + ((sq_ay) / (2.19736822693562)) + if (eq_ax_ay) + else ( + ( + ( + ((sq_ay) * ((one) if (eq_ax_ay) else (((sq_ax) / (sq_ay)) if (lt_ax_ay) else ((sq_ay) / (sq_ax))))) + / ((sq_1h) * (sq_2)) + ) + if (gt_ax_ay) + else ((sq_ay) / ((sq_rh) * (sq_2))) + ) + if (logical_or_eq_u_general_constant_f0_eq_u_general_constant_posinf) + else ((ay) / ((u_general) * (two))) + ) + ) + lt_y_constant_f0: bool = (y) < (constant_f0) + return complex( + (u) if ((x) >= (constant_f0)) else (ay_div_u), + ( + ((-(u)) if (lt_y_constant_f0) else (u)) + if ((x) < (constant_f0)) + else ((-(ay_div_u)) if (lt_y_constant_f0) else (ay_div_u)) + ), + ) diff --git a/results/stablehlo/sqrt.td b/results/stablehlo/sqrt.td new file mode 100644 index 0000000..8530a90 --- /dev/null +++ b/results/stablehlo/sqrt.td @@ -0,0 +1,180 @@ +// This file is generated using functional_algorithms tool (0.11.1), see +// https://github.com/pearu/functional_algorithms +// for more information. + + + + +def : Pat<(sqrt_0 ComplexElementType:$z), + (StableHLO_ComplexOp + (StableHLO_SelectOp + (StableHLO_CompareOp + (StableHLO_RealOp:$x $z), + (StableHLO_ConstantLike<"0.0">:$constant_f0 $x), + StableHLO_ComparisonDirectionValue<"GE">, + (STABLEHLO_DEFAULT_COMPARISON_TYPE)), + (StableHLO_SelectOp:$u + (StableHLO_CompareOp:$eq_ax_ay + (StableHLO_AbsOp:$ax $x), + (StableHLO_AbsOp:$ay + (StableHLO_ImagOp:$y $z)), + StableHLO_ComparisonDirectionValue<"EQ">, + (STABLEHLO_DEFAULT_COMPARISON_TYPE)), + (StableHLO_DivOp + (StableHLO_MulOp + (StableHLO_SqrtOp:$sq_ax $ax), + (StableHLO_ConstantLike<"1.5537739740300374"> $x)), + (StableHLO_ConstantLike<"1.4142135623730951">:$sq_2 $x)), + (StableHLO_SelectOp + (StableHLO_OrOp:$logical_or_eq_u_general_constant_f0_eq_u_general_constant_posinf + (StableHLO_CompareOp + (StableHLO_SqrtOp:$u_general + (StableHLO_AddOp + (StableHLO_DivOp + (StableHLO_SelectOp + (StableHLO_CompareOp + (StableHLO_MaxOp:$mx $ax, $ay), + (StableHLO_MinOp:$mn $ax, $ay), + StableHLO_ComparisonDirectionValue<"EQ">, + (STABLEHLO_DEFAULT_COMPARISON_TYPE)), + (StableHLO_MulOp $sq_2, $mx), + (StableHLO_SelectOp + (StableHLO_AndOp + (StableHLO_CompareOp + (StableHLO_SqrtOp:$sqa + (StableHLO_AddOp + (StableHLO_ConstantLike<"1.0">:$one $x), + (StableHLO_MulOp:$r + (StableHLO_DivOp:$mn_over_mx $mn, $mx), + $mn_over_mx))), + $one, + StableHLO_ComparisonDirectionValue<"EQ">, + (STABLEHLO_DEFAULT_COMPARISON_TYPE)), + (StableHLO_CompareOp + $r, + $constant_f0, + StableHLO_ComparisonDirectionValue<"GT">, + (STABLEHLO_DEFAULT_COMPARISON_TYPE))), + (StableHLO_AddOp + $mx, + (StableHLO_DivOp + (StableHLO_MulOp $mx, $r), + (StableHLO_ConstantLike<"2.0">:$two $x))), + (StableHLO_MulOp $mx, $sqa))), + $two), + (StableHLO_DivOp $ax, $two))), + $constant_f0, + StableHLO_ComparisonDirectionValue<"EQ">, + (STABLEHLO_DEFAULT_COMPARISON_TYPE)), + (StableHLO_CompareOp + $u_general, + (StableHLO_ConstantLikePosInfValue $x), + StableHLO_ComparisonDirectionValue<"EQ">, + (STABLEHLO_DEFAULT_COMPARISON_TYPE))), + (StableHLO_SelectOp + (StableHLO_CompareOp:$gt_ax_ay + $ax, + $ay, + StableHLO_ComparisonDirectionValue<"GT">, + (STABLEHLO_DEFAULT_COMPARISON_TYPE)), + (StableHLO_MulOp + $sq_ax, + (StableHLO_DivOp + (StableHLO_SqrtOp:$sq_1h + (StableHLO_AddOp + $one, + (StableHLO_SelectOp:$h + (StableHLO_CompareOp + (StableHLO_MaxOp:$_mx_0_ + $one, + (StableHLO_AbsOp:$abs__r_0_ + (StableHLO_SelectOp:$_r_0_ + $eq_ax_ay, + $one, + (StableHLO_SelectOp + (StableHLO_CompareOp:$lt_ax_ay + $ax, + $ay, + StableHLO_ComparisonDirectionValue<"LT">, + (STABLEHLO_DEFAULT_COMPARISON_TYPE)), + (StableHLO_DivOp $ax, $ay), + (StableHLO_DivOp $ay, $ax))))), + (StableHLO_MinOp:$_mn_0_ $one, $abs__r_0_), + StableHLO_ComparisonDirectionValue<"EQ">, + (STABLEHLO_DEFAULT_COMPARISON_TYPE)), + (StableHLO_MulOp $sq_2, $_mx_0_), + (StableHLO_SelectOp + (StableHLO_AndOp + (StableHLO_CompareOp + (StableHLO_SqrtOp:$_sqa_0_ + (StableHLO_AddOp + $one, + (StableHLO_MulOp:$_r_1_ + (StableHLO_DivOp:$_mn_over_mx_0_ $_mn_0_, $_mx_0_), + $_mn_over_mx_0_))), + $one, + StableHLO_ComparisonDirectionValue<"EQ">, + (STABLEHLO_DEFAULT_COMPARISON_TYPE)), + (StableHLO_CompareOp + $_r_1_, + $constant_f0, + StableHLO_ComparisonDirectionValue<"GT">, + (STABLEHLO_DEFAULT_COMPARISON_TYPE))), + (StableHLO_AddOp + $_mx_0_, + (StableHLO_DivOp + (StableHLO_MulOp $_mx_0_, $_r_1_), + $two)), + (StableHLO_MulOp $_mx_0_, $_sqa_0_))))), + $sq_2)), + (StableHLO_MulOp + (StableHLO_SqrtOp:$sq_ay $ay), + (StableHLO_DivOp + (StableHLO_SqrtOp:$sq_rh + (StableHLO_AddOp $_r_0_, $h)), + $sq_2))), + $u_general)), + (StableHLO_SelectOp:$ay_div_u + $eq_ax_ay, + (StableHLO_DivOp + $sq_ay, + (StableHLO_ConstantLike<"2.19736822693562"> $x)), + (StableHLO_SelectOp + $logical_or_eq_u_general_constant_f0_eq_u_general_constant_posinf, + (StableHLO_SelectOp + $gt_ax_ay, + (StableHLO_DivOp + (StableHLO_MulOp + $sq_ay, + (StableHLO_SelectOp + $eq_ax_ay, + $one, + (StableHLO_SelectOp + $lt_ax_ay, + (StableHLO_DivOp $sq_ax, $sq_ay), + (StableHLO_DivOp $sq_ay, $sq_ax)))), + (StableHLO_MulOp $sq_1h, $sq_2)), + (StableHLO_DivOp + $sq_ay, + (StableHLO_MulOp $sq_rh, $sq_2))), + (StableHLO_DivOp + $ay, + (StableHLO_MulOp $u_general, $two))))), + (StableHLO_SelectOp + (StableHLO_CompareOp + $x, + $constant_f0, + StableHLO_ComparisonDirectionValue<"LT">, + (STABLEHLO_DEFAULT_COMPARISON_TYPE)), + (StableHLO_SelectOp + (StableHLO_CompareOp:$lt_y_constant_f0 + $y, + $constant_f0, + StableHLO_ComparisonDirectionValue<"LT">, + (STABLEHLO_DEFAULT_COMPARISON_TYPE)), + (StableHLO_NegOp $u), + $u), + (StableHLO_SelectOp + $lt_y_constant_f0, + (StableHLO_NegOp $ay_div_u), + $ay_div_u)))>; \ No newline at end of file diff --git a/results/xla_client/complex_sqrt.cc b/results/xla_client/complex_sqrt.cc new file mode 100644 index 0000000..bccd63a --- /dev/null +++ b/results/xla_client/complex_sqrt.cc @@ -0,0 +1,81 @@ +// This file is generated using functional_algorithms tool (0.11.1), see +// https://github.com/pearu/functional_algorithms +// for more information. + + + +#include "xla/client/lib/constants.h" +#include "xla/client/xla_builder.h" +#include + + +template +XlaOp complex_sqrt_0(XlaOp z) { + XlaOp x = Real(z); + XlaOp constant_constant_0 = ScalarLike(x, 0); + XlaOp ax = Abs(x); + XlaOp y = Imag(z); + XlaOp ay = Abs(y); + XlaOp eq_ax_ay = Eq(ax, ay); + XlaOp sq_ax = Sqrt(ax); + FloatType sq_2_ = std::sqrt(2); + FloatType sq_12_ = std::sqrt((1) + (sq_2_)); + XlaOp sq_2 = ScalarLike(x, sq_2_); + XlaOp mx = Max(ax, ay); + XlaOp mn = Min(ax, ay); + XlaOp one = ScalarLike(x, 1); + XlaOp r = Square(Div(mn, mx)); + XlaOp sqa = Sqrt(Add(one, r)); + XlaOp two = ScalarLike(x, 2); + XlaOp u_general = + Sqrt(Add(Div(Select(Eq(mx, mn), Mul(sq_2, mx), + Select(And(Eq(sqa, one), Gt(r, constant_constant_0)), + Add(mx, Div(Mul(mx, r), two)), Mul(mx, sqa))), + two), + Div(ax, two))); + XlaOp + logical_or_eq_u_general_constant_constant_0_eq_u_general_constant_constant_posinf = + Or(Eq(u_general, constant_constant_0), + Eq(u_general, + ScalarLike(x, std::numeric_limits::infinity()))); + XlaOp gt_ax_ay = Gt(ax, ay); + XlaOp lt_ax_ay = Lt(ax, ay); + XlaOp _r_0_ = + Select(eq_ax_ay, one, Select(lt_ax_ay, Div(ax, ay), Div(ay, ax))); + XlaOp abs__r_0_ = Abs(_r_0_); + XlaOp _mx_0_ = Max(one, abs__r_0_); + XlaOp _mn_0_ = Min(one, abs__r_0_); + XlaOp _r_1_ = Square(Div(_mn_0_, _mx_0_)); + XlaOp _sqa_0_ = Sqrt(Add(one, _r_1_)); + XlaOp h = Select( + Eq(_mx_0_, _mn_0_), Mul(sq_2, _mx_0_), + Select(And(Eq(_sqa_0_, one), Gt(_r_1_, constant_constant_0)), + Add(_mx_0_, Div(Mul(_mx_0_, _r_1_), two)), Mul(_mx_0_, _sqa_0_))); + XlaOp sq_1h = Sqrt(Add(one, h)); + XlaOp sq_ay = Sqrt(ay); + XlaOp sq_rh = Sqrt(Add(_r_0_, h)); + XlaOp u = Select( + eq_ax_ay, Div(Mul(sq_ax, ScalarLike(x, sq_12_)), sq_2), + Select( + logical_or_eq_u_general_constant_constant_0_eq_u_general_constant_constant_posinf, + Select(gt_ax_ay, Mul(sq_ax, Div(sq_1h, sq_2)), + Mul(sq_ay, Div(sq_rh, sq_2))), + u_general)); + XlaOp ay_div_u = Select( + eq_ax_ay, Div(sq_ay, ScalarLike(x, (sq_12_) * (sq_2_))), + Select( + logical_or_eq_u_general_constant_constant_0_eq_u_general_constant_constant_posinf, + Select(gt_ax_ay, + Div(Mul(sq_ay, Select(eq_ax_ay, one, + Select(lt_ax_ay, Div(sq_ax, sq_ay), + Div(sq_ay, sq_ax)))), + Mul(sq_1h, sq_2)), + Div(sq_ay, Mul(sq_rh, sq_2))), + Div(ay, Mul(u_general, two)))); + XlaOp lt_y_constant_constant_0 = Lt(y, constant_constant_0); + return Complex( + Select(Ge(x, constant_constant_0), u, ay_div_u), + Select(Lt(x, constant_constant_0), + Select(lt_y_constant_constant_0, Neg(u), u), + Select(lt_y_constant_constant_0, Neg(ay_div_u), ay_div_u))); +} \ No newline at end of file From 6679d9e594c0083986b4633fce027a88541ef67b Mon Sep 17 00:00:00 2001 From: Pearu Peterson Date: Sat, 21 Dec 2024 17:47:28 +0200 Subject: [PATCH 2/2] Re-enable xfail in test_accuracy --- functional_algorithms/tests/test_accuracy.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/functional_algorithms/tests/test_accuracy.py b/functional_algorithms/tests/test_accuracy.py index 1c08dd3..47aa596 100644 --- a/functional_algorithms/tests/test_accuracy.py +++ b/functional_algorithms/tests/test_accuracy.py @@ -217,4 +217,4 @@ def test_unary(unary_func_name, backend, device, dtype): col_fmt = "| " + " | ".join([f"{{{i}:>{w}}}" for i, w in enumerate(col_widths)]) + " |" print("\n".join([col_fmt.format(*map(str, row)) for row in rows])) - # pytest.xfail("inaccurate or incorrect results") + pytest.xfail("inaccurate or incorrect results")