def test_exact_interpolants():
    order1 = lambda x: 3 * x + 7
    order4 = lambda x: 4.123 * x**4 - 5.6 * x**3 - x**2 + 4.5
    order6 = lambda x: x**6 - 3 * x**5 - 2 * x**4 + x - 3
    order8 = lambda x: x**8 - 42 * x**7 + 7.5 * x**5 - 4.1234 * x**4 - 1.2 * x**2

    a, b = -10, 10
    x = np.linspace(a, b, 1e5, dtype=np.float64)

    est1 = adapt_i.make_interpolant(a, b, order1, 1, 1e-9,
                                    "monomial").evaluate(x)
    est4 = adapt_i.make_interpolant(a, b, order4, 4, 1e-9,
                                    "monomial").evaluate(x)
    est6 = adapt_i.make_interpolant(a, b, order6, 6, 1e-9,
                                    "monomial").evaluate(x)
    est8 = adapt_i.make_interpolant(a, b, order8, 8, 1e-9,
                                    "monomial").evaluate(x)

    print(la.norm(est1 - order1(x), np.inf) / la.norm(order1(x), np.inf))
    print(la.norm(est4 - order4(x), np.inf) / la.norm(order4(x), np.inf))
    print(la.norm(est6 - order6(x), np.inf) / la.norm(order6(x), np.inf))
    print(la.norm(est8 - order8(x), np.inf) / la.norm(order8(x), np.inf))

    assert la.norm(est1 - order1(x), np.inf) / la.norm(order1(x),
                                                       np.inf) < 1e-15
    assert la.norm(est4 - order4(x), np.inf) / la.norm(order4(x),
                                                       np.inf) < 1e-15
    assert la.norm(est6 - order6(x), np.inf) / la.norm(order6(x),
                                                       np.inf) < 1e-15
    assert la.norm(est8 - order8(x), np.inf) / la.norm(order8(x),
                                                       np.inf) < 1e-15
def test_all_parallel_methods():
    a, b = 0, 10
    est1 = adapt_i.make_interpolant(a, b, f, 3, 1e-9, "monomial")
    est2 = adapt_i.make_interpolant(a, b, f, 3, 1e-9, "chebyshev")
    est3 = adapt_i.make_interpolant(a, b, f, 3, 1e-9, "legendre")

    test_parallel(est1)
    test_parallel(est2)
    test_parallel(est3)
def test_remez_incorrect():
    # tests the lookup table size for incorrect remez algorithm and polynomial interpolation
    a, b = 0, 20
    order, precision = 6, 1e-6
    opt = ["arrays", "map", "calc intervals", "random", "remez incorrect"]
    approx = adapt_i.make_interpolant(a,
                                      b,
                                      f,
                                      order,
                                      precision,
                                      'chebyshev',
                                      dtype=32,
                                      optimizations=opt)
    #adapt_i.write_to_file("./testingclass", approx)
    #approx = adapt_i.load_from_file("./testingclass")
    run_one(approx, opt=opt)

    opt = ["arrays", "map", "calc intervals", "random"]
    approx1 = adapt_i.make_interpolant(a,
                                       b,
                                       f,
                                       order,
                                       precision,
                                       'chebyshev',
                                       dtype=32,
                                       optimizations=opt)
    run_one(approx1, opt=opt)

    opt = ["arrays", "map", "calc intervals", "random"]
    approx2 = adapt_i.make_interpolant(a,
                                       b,
                                       f,
                                       order,
                                       precision,
                                       'chebyshev',
                                       dtype=32,
                                       optimizations=opt,
                                       adapt_type="Trivial")
    run_one(approx2, opt=opt)

    print("Incorrect Remez, Correct, Polynomial Interpolation")
    print(len(approx.map), len(approx1.map), len(approx2.map))
    print('{0:.16f}'.format(la.norm(approx.coeff, 2)),
          '{0:.16f}'.format(la.norm(approx1.coeff, 2)),
          '{0:.16f}'.format(la.norm(approx2.coeff, 2)))
    print('{0:.16f}'.format(la.norm(approx.coeff, np.inf)),
          '{0:.16f}'.format(la.norm(approx1.coeff, np.inf)),
          '{0:.16f}'.format(la.norm(approx2.coeff, np.inf)))
def save_approximations(a, b, orders, precisions):
    # Change dtypes and precisions manually
    size, num_samples = 2**12, 2
    opt = ["arrays", "map", "random"]
    for precision in precisions:
        for order in orders:
            print(order, precision)
            if precision > 1e-7:
                try:
                    name = "./approximations/32o" + str(order) + "-p" + str(
                        precision)
                    approx = adapt_i.make_interpolant(a,
                                                      b,
                                                      f,
                                                      order,
                                                      precision,
                                                      'chebyshev',
                                                      dtype=32,
                                                      optimizations=opt)
                    adapt_i.write_to_file(name, approx)
                    run_one(approx, size, num_samples, opt)
                    run_one(approx, size, num_samples, opt + ["scalar"])
                    run_one(approx, size, num_samples,
                            opt + ["calc intervals"])
                    run_one(approx, size, num_samples,
                            opt + ["scalar", "calc intervals"])
                except:
                    pass

            opt = ["arrays", "map", "calc intervals", "random"]
            name = "./approximations/64o" + str(order) + "-p" + str(precision)
            approx = adapt_i.make_interpolant(a,
                                              b,
                                              f,
                                              order,
                                              precision,
                                              'chebyshev',
                                              dtype=64,
                                              optimizations=opt)
            adapt_i.write_to_file(name, approx)
            run_one(approx, size, num_samples, opt)
            run_one(approx, size, num_samples, opt + ["scalar"])
            run_one(approx, size, num_samples, opt + ["calc intervals"])
            run_one(approx, size, num_samples,
                    opt + ["scalar", "calc intervals"])
Esempio n. 5
0
def make_code(size,
              order,
              precision,
              d,
              vectorized=True,
              approx=None,
              code=None,
              opt=[]):
    a, b = 0, 20
    if approx is None:
        approx = adapt_i.make_interpolant(a,
                                          b,
                                          f,
                                          order,
                                          precision,
                                          'chebyshev',
                                          dtype=d,
                                          optimizations=opt)
    else:
        approx.optimizations = opt
    if code is None:
        if vectorized:
            # vector width is actually set depending on data type.
            code = adapt_i.generate_code(approx,
                                         size=size,
                                         vector_width=8,
                                         cpu=True)
        else:
            code = adapt_i.generate_code(approx, size=size, cpu=True)

    dt = approx.dtype_name
    var = "uniform " if vectorized else ""
    if vectorized:
        header = "export void eval("
    else:
        header = 'extern "C" void eval('
    if "arrays" in opt:
        header += "const " + var + dt + " mid[], "
        header += "const " + var + dt + " left[], "
        header += "const " + var + dt + " right[], "
        header += "const " + var + dt + " interval_a[], "
        header += "const " + var + dt + " interval_b[], "
        header += "const " + var + dt + " coeff[], "
    else:
        header += "const " + var + dt + " tree[], "

    if "map" in opt:
        fdt = "int64" if "calc intervals" in approx.optimizations else dt
        header += "const " + var + fdt + " f[], "

    header += var + dt + " x[], " + var + dt + " y[])"
    code = code.replace("\n", "\n\t")
    full_code = header + "{\n\n" + code + "\n}"
    return approx, full_code
def test_guaranteed_accuracy():
    func1 = lambda x: np.sin(np.sin(x))
    func2 = lambda x: np.cos(np.sin(x))
    func3 = lambda x: np.sqrt(x)

    a, b = -10, 10
    x = np.linspace(a, b, 100, dtype=np.float64)

    est31 = adapt_i.make_interpolant(a, b, func1, 10, 1e-3,
                                     "monomial").evaluate(x)
    est32 = adapt_i.make_interpolant(a, b, func2, 10, 1e-3,
                                     "chebyshev").evaluate(x)
    est33 = adapt_i.make_interpolant(a, b, func3, 10, 1e-3,
                                     "legendre").evaluate(x)

    est61 = adapt_i.make_interpolant(a, b, func1, 10, 1e-6,
                                     "monomial").evaluate(x)
    est62 = adapt_i.make_interpolant(a, b, func2, 10, 1e-6,
                                     "chebyshev").evaluate(x)
    est63 = adapt_i.make_interpolant(a, b, func3, 10, 1e-6,
                                     "legendre").evaluate(x)

    est91 = adapt_i.make_interpolant(a, b, func1, 10, 1e-9,
                                     "monomial").evaluate(x)
    est92 = adapt_i.make_interpolant(a, b, func2, 10, 1e-9,
                                     "chebyshev").evaluate(x)
    est93 = adapt_i.make_interpolant(a, b, func3, 10, 1e-9,
                                     "legendre").evaluate(x)

    assert la.norm(est31 - func1(x), np.inf) / la.norm(func1(x), np.inf) < 1e-3
    assert la.norm(est32 - func2(x), np.inf) / la.norm(func2(x), np.inf) < 1e-3
    assert la.norm(est33 - func3(x), np.inf) / la.norm(func3(x), np.inf) < 1e-3

    assert la.norm(est61 - func1(x), np.inf) / la.norm(func1(x), np.inf) < 1e-6
    assert la.norm(est62 - func2(x), np.inf) / la.norm(func2(x), np.inf) < 1e-6
    assert la.norm(est63 - func3(x), np.inf) / la.norm(func3(x), np.inf) < 1e-6

    assert la.norm(est91 - func1(x), np.inf) / la.norm(func1(x), np.inf) < 1e-9
    assert la.norm(est92 - func2(x), np.inf) / la.norm(func2(x), np.inf) < 1e-9
    assert la.norm(est93 - func3(x), np.inf) / la.norm(func3(x), np.inf) < 1e-9
Esempio n. 7
0
def get_asm():
    a, b = 0, 20
    order, precision = 5, 1e-6
    print("make approximation")
    approx = adapt_i.make_interpolant(a,
                                      b,
                                      f,
                                      order,
                                      precision,
                                      'chebyshev',
                                      dtype=32,
                                      optimizations=["arrays"])
    print("Run approximation")

    run_one(approx, opt=['test first loop', 'get asm'])
    run_one(approx, opt=['test second loop', 'get asm'])

    run_one(approx, opt=['arrays', 'map', 'test first loop', 'get asm'])
    run_one(approx, opt=['arrays', 'map', 'test second loop', 'get asm'])
def test_guaranteed_accuracy():
    func1 = lambda x: np.sin(1. / (x))
    func2 = lambda x: np.abs(x * np.sin(x))
    func3 = lambda x: np.sqrt(x)
    func4 = lambda x: np.abs(x * np.cos(x))

    a, b = 0.01, 10
    x = np.linspace(a, b, 1e5, dtype=np.float64)

    for func in [func4, func2, func3, func1]:
        for err in [1e-3, 1e-6, 1e-9]:
            for interpolant in ["monomial", "chebyshev", "legendre"]:
                est = adapt_i.make_interpolant(a, b, func, 6, err,
                                               interpolant).evaluate(x)
                abs_err = la.norm(est - func(x), np.inf)
                rel_err = abs_err / la.norm(func(x), np.inf)
                print(interpolant, err, rel_err)
                plt.figure()
                plt.plot(x, func(x), 'r')
                plt.plot(x, est, 'b')
                plt.show()
                assert rel_err < err
def scalar_test():
    # decreasing the size causes the GFLOPS to go down...
    # size of 0 takes about 1e-5 seconds to run function.
    # with 2**10 and 2**15 size its still about that.
    # 2**20 is better but 2**26 guarentees its good
    # takes long enough for the measurement to make sense.
    a, b = 1, 21
    order, precision = 3, np.finfo(np.float32).eps * 10
    size, num_samples = 2**23, 50
    d = 32
    opt = ["arrays", "map", "random"]
    approx = adapt_i.make_interpolant(a,
                                      b,
                                      f,
                                      order,
                                      precision,
                                      'chebyshev',
                                      dtype=d,
                                      optimizations=opt)
    run_one(approx, size, num_samples, opt=opt + ["calc intervals"])
    run_one(approx, size, num_samples, opt=opt)
    # scalar does something incorrect? oh.. data race?
    run_one(approx, size, num_samples, opt=opt + ["scalar", "calc intervals"])
    run_one(approx, size, num_samples, opt=opt + ["scalar"])
Esempio n. 10
0
def test_throughput(n, d, precision, size):
    if d != '32' and d != '64': return
    throw_out = 20
    a, b = 0, 20
    vws = [1]  # vector widths used
    GB = size * float(d) / (8 * 2**20
                            )  # number of bits / a GB in bits = # of GB
    orders = [1]

    tests = [[0 for __ in range(len(vws))] for _ in range(len(orders) + 1)]

    for j in range(len(orders)):
        approx = adapt_i.make_interpolant(a,
                                          b,
                                          f,
                                          orders[j],
                                          precision,
                                          'chebyshev',
                                          dtype=d)
        for v in range(len(vws)):
            # see how much time to process array
            adapt_i.generate_code(approx, size, vws[v])
            print()
            knl, q, treed = generate.build_code(approx)
            print(approx.code)
            for trial in range(n + throw_out):
                print("order: " + repr(j) + "/" + repr(len(orders)) +
                      "\ttrial:" + repr(trial + 1) + "/" +
                      repr(n + throw_out) + "\r")
                o = np.float32 if d == '32' else np.float64
                x = np.random.uniform(a, b, size=size).astype(o)
                run_time, _ = generate.run_single(x, approx)
                # run code multiple times before actually adding to tests
                if trial > throw_out:
                    tests[j + 1][v] += GB / run_time
                    # only evaluate scipy's speed the first time
                    if j == 0:
                        start_time = time.time()
                        val = f0(x, v)
                        run_time = time.time() - start_time
                        tests[0][v] += GB / run_time
    print()

    # average out each test
    for i in range(len(tests)):
        for j in range(len(vws)):
            tests[i][j] /= float(n)

    fig = plt.figure()
    plt.title("throughput {0} single, {1} trials, vw={2}".format(
        precision, n, vws[0]))
    plt.xlabel("Function Evaluated")
    plt.ylabel("Average Throughput (GB/s)")
    #plt.yscale("log")
    #plt.xscale("log")
    #plt.bar(0, tests[0][0], width=.5, align='center', color='r')
    i = 0
    z = np.linspace(-.2, .2, len(vws))
    colors = ['b', 'g', 'y', 'k', 'm', 'c']
    for v in range(len(vws)):
        plt.bar(i + z[v],
                tests[i][v],
                width=.3 / len(vws),
                align='center',
                color=colors[i])
    xticks = ['scipy specials']
    for order in orders:
        z = np.linspace(-.2, .2, len(vws))
        for v in range(len(vws)):
            plt.bar(i + 1 + z[v],
                    tests[i + 1][v],
                    width=.3 / len(vws),
                    align='center',
                    color=colors[i])
        i += 1
        xticks.append("{0}th order approx".format(order))
    plt.xticks(range(len(orders) + 1), xticks)
    string = "../data/00" + repr(d) + "t" + repr(time.time() % 100) + "n"
    string += repr(n) + "+vw" + repr(vws[0]) + repr(vws[-1]) + "o"
    string += repr(orders[0]) + repr(precision) + repr(size) + ".png"
    fig.savefig(string)
Esempio n. 11
0
def make_data(size,
              order,
              precision,
              d,
              vectorized=True,
              approx=None,
              code=None,
              opt=[]):
    a, b = 0, 20
    if code == None and approx == None:
        approx = adapt_i.make_interpolant(a,
                                          b,
                                          f,
                                          order,
                                          precision,
                                          'chebyshev',
                                          dtype=d,
                                          optimizations=opt)

        # see how much time to process array, vector width = 1
        if vectorized:
            code = adapt_i.generate_code(approx,
                                         size=size,
                                         vector_width=8,
                                         cpu=True)
        else:
            code = adapt_i.generate_code(approx, size=size, cpu=True)
    #print(code)
    dt = approx.dtype_name
    var = "uniform " if vectorized else ""
    header = "export void eval("
    if "arrays" in opt:
        header += "const " + var + dt + " mid[], "
        header += "const " + var + dt + " left[], "
        header += "const " + var + dt + " right[], "
        header += "const " + var + dt + " interval_a[], "
        header += "const " + var + dt + " interval_b[], "
        header += "const " + var + dt + " coeff[], "
    else:
        header += "const " + var + dt + " tree[], "

    if "map" in opt:
        header += "const " + var + dt + " f[], "

    header += var + dt + " x[], " + var + dt + " y[])"

    code = code.replace("\n", "\n\t")
    full_code = header + "{\n\n" + code + "\n}"
    with open("simple_ispc.ispc", "w") as h:
        h.writelines(full_code)

    s = [size, size]
    if "arrays" in opt:
        s.append(len(approx.mid))
        s.append(len(approx.left))
        s.append(len(approx.right))
        s.append(len(approx.interval_a))
        s.append(len(approx.interval_b))
        s.append(len(approx.coeff))
    else:
        s.append(len(approx.tree_1d))

    if "map" in opt:
        s.append(len(approx.map))

    dt = float
    if "arrays" in opt:
        save("left.txt", approx.left, dt)
        save("right.txt", approx.right, dt)
        save("interval_a.txt", approx.interval_a, dt)
        save("interval_b.txt", approx.interval_b, dt)
        save("coeff.txt", approx.coeff, dt)
        save("mid.txt", approx.mid, dt)
        os.system("mv left.txt tests/perf/")
        os.system("mv right.txt tests/perf/")
        os.system("mv interval_a.txt tests/perf/")
        os.system("mv interval_b.txt tests/perf/")
        os.system("mv coeff.txt tests/perf/")
        os.system("mv mid.txt tests/perf/")
    else:
        save("tree.txt", approx.tree_1d, dt)
        os.system("mv tree.txt tests/perf/")

    if "map" in opt:
        save("f.txt", approx.map, dt)
        os.system("mv f.txt tests/perf/")

    # add changing eval function in tests/perf/simple.cpp
    """
    with open("tests/perf/simple.cpp", 'rw') as sim:
        cpp = sim.readlines()
        # actually this only needs to comment and uncomment correct lines 
        if "arrays" in opt or "map" in opt:
            cpp.replace("", "eval(mid, left, right, interval_a, interval_b, coeff, f, x, y);\n")
        else:
            cpp.repalce("", "eval(tree, x, y);")
        sim.writelines(cpp)
    """

    save("sizes.txt", s, int)
    os.system("mv sizes.txt tests/perf/")
    os.system("mv *.ispc tests/perf/")
    return approx, full_code
Esempio n. 12
0
def demo_adapt(function,
               order,
               allowed_error,
               basis,
               adapt_type="Trivial",
               accurate=True,
               animate=False,
               a=0,
               b=10,
               opt=[]):

    print("Creating Interpolant")
    my_approx = adapt_i.make_interpolant(a,
                                         b,
                                         function,
                                         order,
                                         allowed_error,
                                         basis,
                                         adapt_type,
                                         '32',
                                         accurate,
                                         optimizations=opt)
    print("\nGenerated Code:\n")
    N = 2**10
    adapt_i.generate_code(my_approx, size=N, cpu=True)
    print(my_approx.code)
    print("Evaluating Interpolant")
    x = np.linspace(a, b, N, dtype=np.float64)
    if with_pyopencl and False:
        est = adapt_i.run_approximation(x, my_approx)
    else:
        est = my_approx.evaluate_tree(x)
    print("Evaluating Function")
    true = function(x)
    print("Plotting")
    #not working with tree version
    if animate:
        fig = plt.figure()
        ax1 = fig.add_subplot(1, 2, 2)
        ax2 = fig.add_subplot(1, 2, 1)
        #ax1.set_ylim(-2, 2)
        ax2.set_yscale("log")
        ims = []
        # traverse levels 1 to end
        for i in range(int(my_approx.num_levels)):
            print("Plotting Level: ", i, '/', my_approx.num_levels - 1)
            ims.append([])
            im0, = ax1.plot(x, function(x), 'r')
            rel, = ax2.plot(x, 0 * x + allowed_error, 'r')
            ax1.set_xlabel("x")
            ax1.set_ylabel("y")
            ax1.set_title("True Function vs. Approximation")
            ax2.set_xlabel("x")
            ax2.set_ylabel("Errors")
            ax2.set_title("Relative and Absolute Errors on Intervals")
            ims[i].append(im0)
            ims[i].append(rel)

            t = np.linspace(a, b, 1e5)
            y, data = my_approx.evaluate_tree(t, i + 1, 1)
            midpoints = [elem[0] for elem in data]
            ranges = [elem[2] for elem in data]
            rel_errors = [elem[3] for elem in data]

            er = abs(np.array(y) - function(t))

            im2, = ax1.plot(t, y, 'b')
            im3, = ax2.plot(t, er, 'g')
            for r in ranges:
                im4 = ax2.axvline(x=r[0])
                ims[i].append(im4)
            im5, = ax2.plot(midpoints, rel_errors, 'bs')
            ims[i].append(im2)
            ims[i].append(im3)
            ims[i].append(im5)

            im6 = ax2.axvline(x=ranges[-1][1])
            ims[i].append(im6)
        ani = animation.ArtistAnimation(fig, ims, interval=1000)
        ani.save("adapt.mp4")
        plt.show()
    else:
        my_plot(x, true, est, abs(true - est), allowed_error, my_approx)
def test_speed():
    n = 10
    throw_out = 40
    a, b = 0, 20
    sizes = 2**np.arange(1, 13)
    #sizes = np.linspace(1e2, 5e6, 5, dtype=np.int)
    tests = []
    orders = [9, 16]
    tests.append(0 * np.zeros(sizes.shape))

    tests.append(0 * np.zeros(sizes.shape))
    for j in range(len(orders)):
        tests.append(0 * np.zeros(sizes.shape))
        approx = adapt_i.make_interpolant(a, b, f, orders[j], 1e-9,
                                          'chebyshev')
        if True:  # test interpolant is accurate
            y = np.linspace(a, b, 8 * 5e3)
            adapt_i.generate_code(approx, 8 * 5e3, 32)
            knl, q, xd, yd, treed = generate.build_code(y, approx)
            _, z = generate.run_single(approx)
            rel_err = la.norm(z - f(y), np.inf) / la.norm(f(y), np.inf)
            print("rel_error", orders[j], rel_err)
        for i in range(sizes.shape[0]):
            index = 0
            x = np.linspace(a, b, sizes[i])
            adapt_i.generate_code(approx, sizes[i], 1)
            knl, q, xd, yd, treed = generate.build_code(x, approx)
            for trial in range(n + throw_out):
                print("order: " + repr(j) + "/" + repr(len(orders)) +
                      "\ttrial:" + repr(trial + 1) + "/" +
                      repr(n + throw_out) + "\r")
                run_time, _ = generate.run_single(approx)
                # run code multiple times before actually adding to tests
                if trial >= throw_out:
                    tests[j + 1][i] += run_time
                    if j == 0:
                        if trial - throw_out > 17:
                            print("mine", run_time)
                        start_time = time.time()
                        val = f(x)
                        run_time = time.time() - start_time
                        #print(la.norm(_-val,np.inf)/la.norm(val, np.inf))
                        if trial - throw_out > 17:
                            print("scipy", run_time, sizes[i],
                                  trial - throw_out)
                        tests[0][i] += run_time
            print()

    # average out each test
    for i in range(len(tests)):
        tests[i] /= float(n)

    fig = plt.figure()
    plt.title("Runtimes 1E-9 prec. bessel 0-20, {0} trials, vw=1".format(n))
    plt.xlabel("Size of evaluated array")
    plt.ylabel("Time to evaluate (seconds)")
    #plt.yscale("log")
    #plt.xscale("log")
    sp, = plt.plot(sizes, tests[0], 'r', label='scipy bessel')
    i = 0
    hand = [sp]
    colors = ['b', 'g', 'y', 'k', 'm', 'c']
    for order in orders:
        a1, = plt.plot(sizes,
                       tests[i + 1],
                       colors[i],
                       label="{0}th order approx".format(order))
        i += 1
        hand.append(a1)
    plt.legend(handles=hand)
    #plt.show()
    string = "data/t" + repr(time.time()) + "n" + repr(n) + "vw1o" + repr(
        orders[0]) + ".png"
    fig.savefig(string)
Esempio n. 14
0
    # maybe im using the wrong dtype somewhere?
    # its actually not. The scaling/L is imprecise for some reason..
    #2/(b-a) is accurate though.. at least I figured it out...
    if 0:
        order, num_samples = 3, 10
        a, b = -3, 23

        size = 2**23
        precision = 90000 * np.finfo(np.float32).eps
        opt = ["arrays", "map", "verbose"]
        #name = "./approximations/64o" + str(order) + "-p" + str(precision)
        #approx = adapt_i.load_from_file(name)
        approx = adapt_i.make_interpolant(a,
                                          b,
                                          f,
                                          order,
                                          precision,
                                          'chebyshev',
                                          dtype=64,
                                          optimizations=opt)
        print(2 * approx.D + approx.lgD)
        scaling = (approx.upper_bound - approx.lower_bound) / len(approx.map)
        c = list(
            map(
                lambda x: (
                    int(bin(x)[:-2 * approx.D], 2),
                    int("0b" + bin(x)[-2 * approx.D:-approx.D], 2),
                    int("0b" + bin(x)[-approx.D:], 2),
                    bin(x),
                    int("0b" + bin(x)[-2 * approx.D:-approx.D], 2) * scaling +
                    approx.lower_bound,
                    int(bin(x)[:-2 * approx.D], 2) * scaling,
Esempio n. 15
0
def new_test():
    # Function used to obtain results. DONT CHANGE
    a, b = 0, 20
    order, precision = 5, 1e-6

    approx = adapt_i.make_interpolant(a,
                                      b,
                                      f,
                                      order,
                                      precision,
                                      'chebyshev',
                                      dtype=32,
                                      optimizations=["arrays"])

    run_one(approx, precision, opt=['test flops'])
    run_one(approx, precision, opt=['none'])

    run_one(approx, precision, opt=['arrays', 'map'])
    run_one(approx, precision, opt=['arrays', 'map', 'test first loop'])
    run_one(approx, precision, opt=['arrays', 'map', 'test second loop'])

    run_one(approx, precision, opt=[])
    run_one(approx, precision, opt=['test first loop'])
    run_one(approx, precision, opt=['test second loop'])

    print("Doubles: Same Precision")
    approx = adapt_i.make_interpolant(a,
                                      b,
                                      f,
                                      order,
                                      precision,
                                      'chebyshev',
                                      dtype=64,
                                      optimizations=["arrays"])

    # give peak flop estimate
    run_one(approx, precision, opt=['64', 'test flops'])
    run_one(approx, precision, opt=['64', 'none'])

    run_one(approx, precision, opt=['64', 'arrays', 'map'])
    run_one(approx, precision, opt=['64', 'arrays', 'map', 'test first loop'])
    run_one(approx, precision, opt=['64', 'arrays', 'map', 'test second loop'])

    run_one(approx, precision, opt=['64'])
    run_one(approx, precision, opt=['64', 'test first loop'])
    run_one(approx, precision, opt=['64', 'test second loop'])

    print("Doubles: Higher Precision")
    order, precision = 5, 1e-13
    approx = adapt_i.make_interpolant(a,
                                      b,
                                      f,
                                      order,
                                      precision,
                                      'chebyshev',
                                      dtype=64,
                                      optimizations=["arrays"])

    # give peak flop estimate
    run_one(approx, precision, opt=['64', 'test flops'])
    run_one(approx, precision, opt=['64', 'none'])

    run_one(approx, precision, opt=['64', 'arrays', 'map'])
    run_one(approx, precision, opt=['64', 'arrays', 'map', 'test first loop'])
    run_one(approx, precision, opt=['64', 'arrays', 'map', 'test second loop'])

    run_one(approx, precision, opt=['64'])
    run_one(approx, precision, opt=['64', 'test first loop'])
    run_one(approx, precision, opt=['64', 'test second loop'])
Esempio n. 16
0
def test():
    # Function used to obtain results. DONT CHANGE
    a, b = 0, 20
    order, precision = 5, 1e-4

    approx = adapt_i.make_interpolant(a,
                                      b,
                                      f,
                                      order,
                                      precision,
                                      'chebyshev',
                                      dtype=32,
                                      optimizations=["arrays"])

    run_one(approx, precision, opt=[])
    #run_one(approx, precision, opt=['unroll'])
    #run_one(approx, precision, opt=['unroll_order'])
    #run_one(approx, precision, opt=['prefetch'])
    #run_one(approx, precision, opt=['unroll', 'unroll_order', 'prefetch'])
    run_one(approx, precision, opt=['test first loop'])
    run_one(approx, precision, opt=['test second loop'])

    run_one(approx, precision, opt=['arrays', 'map'])
    #run_one(approx, precision, opt=['arrays', 'map', 'unroll'])
    #run_one(approx, precision, opt=['arrays', 'map', 'unroll_order'])
    #run_one(approx, precision, opt=['arrays', 'map', 'prefetch'])
    #run_one(approx, precision, opt=['arrays', 'map', 'unroll', 'unroll_order', 'prefetch'])
    run_one(approx, precision, opt=['arrays', 'map', 'test first loop'])
    run_one(approx, precision, opt=['arrays', 'map', 'test second loop'])

    #run_one(approx, precision, opt=['none'])

    print("USING DOUBLES")
    approx = adapt_i.make_interpolant(a,
                                      b,
                                      f,
                                      order,
                                      precision,
                                      'chebyshev',
                                      dtype=64,
                                      optimizations=["arrays"])

    run_one(approx, precision, opt=['64'])
    #run_one(approx, precision, opt=['64', 'unroll'])
    #run_one(approx, precision, opt=['64', 'unroll_order'])
    #run_one(approx, precision, opt=['64', 'prefetch'])
    #run_one(approx, precision, opt=['64', 'unroll', 'unroll_order', 'prefetch'])
    run_one(approx, precision, opt=['64', 'test first loop'])
    run_one(approx, precision, opt=['64', 'test second loop'])

    run_one(approx, precision, opt=['64', 'arrays', 'map'])
    #run_one(approx, precision, opt=['64', 'arrays', 'map', 'unroll'])
    #run_one(approx, precision, opt=['64', 'arrays', 'map', 'unroll_order'])
    #run_one(approx, precision, opt=['64', 'arrays', 'map', 'prefetch'])
    #run_one(approx, precision, opt=['64', 'arrays', 'map', 'unroll', 'unroll_order', 'prefetch'])
    run_one(approx, precision, opt=['64', 'arrays', 'map', 'test first loop'])
    run_one(approx, precision, opt=['64', 'arrays', 'map', 'test second loop'])

    #run_one(approx, opt=['64', 'none'])

    precision = 1e-13
    approx = adapt_i.make_interpolant(a,
                                      b,
                                      f,
                                      order,
                                      precision,
                                      'chebyshev',
                                      dtype=64,
                                      optimizations=["arrays"])
    run_one(approx, precision, opt=['64'])
    run_one(approx, precision, opt=['64', 'test first loop'])
    run_one(approx, precision, opt=['64', 'test second loop'])

    run_one(approx, precision, opt=['64', 'arrays', 'map'])
    run_one(approx, precision, opt=['64', 'arrays', 'map', 'test first loop'])
    run_one(approx, precision, opt=['64', 'arrays', 'map', 'test second loop'])
    """