def power_interval(a, n):
    the_power = ft.arb(1)
    if type(a) != type(ft.arb(1)):
        return float(a)**n
    elif n != 0:
        if a.lower() >= 0:
            the_power = ft.arb(0.5 * (a.lower())**n + 0.5 * (a.upper())**n,
                               0.5 * (a.upper())**n - 0.5 * (a.lower())**n)
        elif a.upper() <= 0:
            if n % 2 == 0:
                the_power = ft.arb(0.5 * (a.lower())**n + 0.5 * (a.upper())**n,
                                   0.5 * (a.lower())**n - 0.5 * (a.upper())**n)
            else:
                the_power = ft.arb(0.5 * (a.lower())**n + 0.5 * (a.upper())**n,
                                   0.5 * (a.upper())**n - 0.5 * (a.lower())**n)
        else:
            a1 = ft.arb(0.5 * a.lower(), -0.5 * a.lower())
            a2 = ft.arb(0.5 * a.upper(), 0.5 * a.upper())
            the_power2 = ft.arb(0.5 * (float(a2.upper()))**n,
                                0.5 * (float(a2.upper()))**n)
            if n % 2 == 0:
                the_power1 = ft.arb(0.5 * (a1.lower())**n,
                                    0.5 * (a1.lower())**n)
            else:
                the_power1 = ft.arb(0.5 * (a1.lower())**n,
                                    -0.5 * (a1.lower())**n)
            the_power = the_power1.union(the_power2)
        #print("power")
        #print(the_power.lower(),the_power.upper())

    return the_power
def evaluation_term(term, B):  #evaluate a term at a box B... term
    if [str(T) for T in term[0]] == ["0"] * len(term[0]):

        if type(term[1]) == type(
                ft.arb(1)):  #to avoid an error by sympy  zeros
            the_evaluation = term[1]
        else:
            the_evaluation = ft.arb(float(term[1]))

    else:
        the_evaluation = ft.arb(1)
        for i in range(len(term[0])):
            if term[0][i] != 0:
                the_evaluation = intervals_multi(
                    the_evaluation, (power_interval(B[i], term[0][i])))
                #print(B[i], term[0],i)
                #print(the_evaluation.lower())
                #ftprint([intervals_multi(the_evaluation,(power_interval(B[i],term[0][i])))])
                #input()
                #the_evaluation=(the_evaluation)*(power_interval(B[i],term[0][i]))
        if type(term[1]) == type(
                ft.arb(1)):  #to avoid an error by sympy  zeros
            the_evaluation = the_evaluation * term[1]
        else:
            the_evaluation = intervals_multi(the_evaluation,
                                             ft.arb(float(term[1])))

    return the_evaluation
Beispiel #3
0
    def _validate_root_enclosure(poly, x):
        """
        Given x known to be an enclosure of *at least one root of poly*,
        certifies that the enclosure contains a unique root, and in that
        case returns a new (possibly improved) enclosure for the same
        root.

        Returns None if uniqueness cannot be certified.
        """
        if x.is_exact() or poly.degree() == 1:
            return x
        orig = ctx.prec
        try:
            acc = x.rel_accuracy_bits()
            ctx.prec = max(acc, 32) * 2 + 10
            pure_real = x.imag == 0
            # slightly inflate enclosure - needed e.g. in case of
            # complex interval with one very narrow real/imaginary part
            eps = x.rad() * (1 / 16.)
            if pure_real:
                x += arb(0, eps)
            else:
                x += acb(arb(0, eps), arb(0, eps))
            # interval Newton steps
            xmid = x.mid()
            y = xmid - poly(xmid) / poly.derivative()(x)
            if pure_real:
                x = x.real
                y = y.real
            if x.contains_interior(y):
                return y
            return None
        finally:
            ctx.prec = orig
def evaluation_poly_list(poly_list, B):
    evaluation = ft.arb(0)
    for term in poly_list:
        value_of_term = evaluation_term(term, B)
        if type(value_of_term) == type(ft.arb(1)):
            evaluation = evaluation + value_of_term
        else:
            evaluation = evaluation + ft.arb(float(value_of_term))

    return evaluation
def gauss_seidel_dim1(a, b, x):
    Answer = x
    if 0 not in (a * ft.arb(1)):
        try:
            Answer = x.intersection((b * ft.arb(1)) / a)
        except:
            Answer = 'empty'
    else:

        Answer = special_cases_gauss_seidel(a, b, x)
    return Answer
def B_Ball_calculator(B):  # returns B_Ball
    norm_diff = ft.arb(0)  #computing \Xi (Remark 5.2.10)
    for i in range(2, len(B)):
        norm_diff += power_interval(B[i] - B[i], 2)

    max_t = float(norm_diff.upper())
    B_Ball = B[:2]
    for i in range(2, len(B)):
        B_Ball.append(B[i] + ft.arb(0, max_t))
    B_Ball += [ft.arb(0, 1)] * (len(B) - 2)
    B_Ball += [ft.arb(0.5 * max_t, 0.5 * max_t)]
    return B_Ball
def ploterr(ax,
            f,
            xab,
            yab,
            step,
            yrange=None,
            color=None,
            label=None,
            hatch=None,
            alpha=1.0):
    print "yah"
    xrad = step * 0.5
    a, b = xab
    top = 0.0
    bot = 0.0
    for xx in arange(a, b, 2 * xrad):
        xmid = xx + xrad
        X = arb(xmid, xrad)
        if abs(xmid + xrad) < 1e-10:
            X = -((-X).nonnegative_part())
        elif abs(xmid - xrad) < 1e-10:
            X = X.nonnegative_part()
        Y = f(X)
        if Y.is_finite():
            ymid = float(arb(Y.mid()))
            yrad = float(arb(Y.rad()))
            top = max(top, (ymid + yrad) * 1.2)
            bot = min(bot, (ymid - yrad) * 1.2)
            ax.add_patch(
                patches.Rectangle((xmid - xrad, ymid - yrad),
                                  2 * xrad,
                                  2 * yrad,
                                  color=color,
                                  alpha=alpha,
                                  hatch=hatch))
        else:
            ax.add_patch(
                patches.Rectangle((xmid - xrad, -1e50),
                                  2 * xrad,
                                  1e50,
                                  color=color,
                                  alpha=alpha,
                                  hatch=hatch))
    ax.set_xlim([a, b])
    if yab is None:
        ax.set_ylim([bot, top])
    else:
        ax.set_ylim(yab)
    if label is None:
        label = 'Step %s' % step
    patch1 = mpatches.Patch(color=color, label=label, alpha=alpha, hatch=hatch)
    legends.append(patch1)
Beispiel #8
0
def evlist(boxes):
    ftboxes = [[d.ftconstructor(Bi[0], Bi[1]) for Bi in B] for B in boxes]
    n = len(boxes[0])
    m = len(boxes)
    m1 = []
    m2 = []
    for B in ftboxes:
        m1.append(ft.arb(0.0002 * ft.arb.sin(B[2]) * ft.arb.cos(B[2])))
        m2.append(ft.arb(-2 * ft.arb.sin(B[2])**2 * ft.arb.cos(B[2])))
    innrer_loops = [i for i in range(m) if 0 in m1[i] and 0 in m2[i]]
    x1mon = [i for i in range(m) if 0 not in m1[i]]
    x2mon = [i for i in range(m) if 0 in m1[i] and 0 not in m2[i]]
    return [x1mon, x2mon, innrer_loops]
def subdivide(B):  #B is a list of ft.arb
    if len(B) == 1:
        children = [[ft.arb(B[0].mid() + (B[0].rad() / 2), B[0].rad() / 2)],
                    [
                        ft.arb(B[0].mid() - (0.5 * B[0].rad()),
                               0.5 * B[0].rad())
                    ]]
    else:
        B_prime = list(B)
        B_prime.remove(B_prime[len(B_prime) - 1])
        B_pri_sub = subdivide(B_prime)
        B_one_sub = subdivide([B[len(B) - 1]])
        children = cartesian_product(B_pri_sub, B_one_sub)
    return children
Beispiel #10
0
def ftprint(B, k=3):
    answer = []
    if type(B[0]) == type(ft.arb(1)):
        for Bi in B:
            if type(Bi) == type(ft.arb(0, 1)):
                answer.append(
                    [round(float(Bi.lower()), k),
                     round(float(Bi.upper()), k)])
            else:
                answer.append([Bi, Bi])
        print(answer)
    elif type(B[0]) == type([]):
        pprint(Matrix([[ [round(float(Bij.lower()),k),round(float(Bij.upper()),k) ] if \
          type(Bij)==type(ft.arb(1)) else [Bij,Bij  ] for Bij in Bi ] for Bi in B ] ))
Beispiel #11
0
def solver2(P, jac, B):
    t1 = time.time()
    S = solver(P, jac, B)
    S2 = []
    k = 2
    connected_components1 = connected_components(S)
    while len(connected_components1) != len(S):
        for component in connected_components1:
            if len(connected_components1[component]) == 1:
                S2.append(S[connected_components1[component][0]])
            else:
                union_box = S[connected_components1[component][0]]
                for i in range(1, len(connected_components1[component])):
                    union_box = box_union(
                        union_box, S[connected_components1[component][i]])
                union_box_inflated = [
                    x + y for x, y in zip(union_box, [ft.arb(0, 0.001)] *
                                          len(union_box))
                ]

                S3 = solver(P, jac, union_box_inflated, k)
                S2 = S2 + S3
        k += 1
        S = S2[:]
        S2 = []
        connected_components1 = connected_components(S)

    t2 = time.time()
    print(t2 - t1)
    return S
Beispiel #12
0
def figure3():
    global legends
    plt.clf()
    ax = plt.gca()
    legends = []
    ax.grid(True)
    k = 1
    R = -arb(-1).exp()
    ploterr(ax,
            lambda X: acb(R, X).lambertw(k).real, [-4, 4], [-5, 1],
            0.5,
            color="lightblue",
            label="$h = 0.5$",
            alpha=0.7)
    ploterr(ax,
            lambda X: acb(R, X).lambertw(k).real, [-4, 4], [-5, 1],
            0.1,
            color="blue",
            label="$h = 0.1$",
            alpha=0.5)
    ploterr(ax,
            lambda X: acb(R, X).lambertw(k).real, [-4, 4], [-5, 1],
            0.01,
            color="black",
            label="$h = 0.01$",
            alpha=1.0)
    plt.xlabel("$y$")
    plt.ylabel("$\Re(W_{%ld}(-1/e+yi))$" % k)
    ax.legend(handles=legends, loc="upper right")
    import matplotlib
    fig = matplotlib.pyplot.gcf()
    fig.set_size_inches(8, 5)
    fig.savefig('test2.png', bbox_inches="tight")
    fig.savefig('branchplot2.pdf', bbox_inches="tight")
Beispiel #13
0
def checking_smoothness(P, B, jac, wth=0.1):
    M = [coefficient_matrix_list(Pi) for Pi in P]
    list_of_boxes = [B]
    smoothness = 1
    regular_boxes = []
    while len(list_of_boxes) != 0 and width(list_of_boxes[0]) > wth:
        membership = 1
        eval_P = [polyvalnd(Mi, list_of_boxes[0]) for Mi in M]
        for eval_Pi_at_B in eval_P:
            if 0 not in ft.arb(1) * (eval_Pi_at_B):
                membership = 0
        eval_jac = matrixval(jac, list_of_boxes[0])
        full_rankness = checking_full_rank(eval_jac)
        if membership == 0 or full_rankness == 1:
            regular_boxes.append(list_of_boxes[0])
            list_of_boxes.remove(list_of_boxes[0])
        else:
            new_children = subdivide(list_of_boxes[0])
            list_of_boxes.remove(list_of_boxes[0])
            list_of_boxes = list_of_boxes + new_children
    if len(list_of_boxes) != 0:
        smoothness = -1
    print("Empty or regular boxes:", regular_boxes)
    print("Unknown-behavior boxes", list_of_boxes)
    return smoothness
Beispiel #14
0
def figure1():
    global legends
    plt.clf()
    ax = plt.gca()
    legends = []
    ax.grid(True)
    R = float(-arb(-1).exp())

    k = 0
    plotadaptive(ax,
                 lambda X: acb(X).lambertw(k).real, [R, 3], [-3, 2],
                 0.5,
                 color="lightblue",
                 label="$W_{0}(x), \\varepsilon = 0.5$",
                 alpha=0.6)
    plotadaptive(ax,
                 lambda X: acb(X).lambertw(k).real, [R, 3], [-3, 2],
                 0.1,
                 color="blue",
                 label="$W_{0}(x), \\varepsilon = 0.1$",
                 alpha=0.7)
    plotadaptive(ax,
                 lambda X: acb(X).lambertw(k).real, [R, 3], [-3, 2],
                 0.01,
                 color="black",
                 label="$W_{0}(x), \\varepsilon = 0.01$",
                 alpha=1.0)

    k = -1
    plotadaptive(ax,
                 lambda X: acb(X).lambertw(k).real, [R, 0], [-3, 2],
                 0.5,
                 color="orange",
                 label="$W_{-1}(x), \\varepsilon = 0.5$",
                 alpha=0.4)
    plotadaptive(ax,
                 lambda X: acb(X).lambertw(k).real, [R, 0], [-3, 2],
                 0.1,
                 color="red",
                 label="$W_{-1}(x), \\varepsilon = 0.1$",
                 alpha=0.8)
    #plotadaptive(ax, lambda X: acb(X).lambertw(k).real, [R, 0], [-3,2], 0.01, color="black", label="$W_{-1}(x), \\varepsilon = 0.01$", alpha=1.0)

    ax.set_xlim([-1, 3])
    ax.set_ylim([-4, 2])
    ax.axhline(y=-1, color="gray")
    ax.axvline(x=R, color="gray")

    plt.xticks([-1, R, 0, 1, 2, 3],
               ["$-1$", "$-1/e$", "$0$", "$1$", "$2$", "$3$"])
    plt.xlabel("$x$")
    plt.ylabel("$W_k(x)$")
    ax.legend(handles=legends, loc="best")
    import matplotlib
    fig = matplotlib.pyplot.gcf()
    fig.set_size_inches(8, 5)
    fig.savefig('test1aa.png', bbox_inches="tight")
    fig.savefig('branchplot1.pdf', bbox_inches="tight")
Beispiel #15
0
def checking_regularity_of_sysyem(P, B, jac, wth=0.2):
    list_of_boxes = [B]
    smoothness = 1
    regular_boxes = []
    empty_boxes = []
    regular_volume = 0
    empty_volume = 0
    unknownvolume = n_volume(B)
    while len(list_of_boxes) != 0 and width(list_of_boxes[0]) > wth:
        current_box = list_of_boxes[0]
        membership = 1
        eval_P = [evaluation_poly_list(Pi, current_box) for Pi in P]
        for eval_Pi_at_B in eval_P:
            if type(eval_Pi_at_B) != type(ft.arb(1)):
                eval_Pi_at_B = float(eval_Pi_at_B)
            if 0 not in ft.arb(1) * (eval_Pi_at_B):
                membership = 0
                break
        if membership == 0:
            empty_boxes.append(list_of_boxes[0])
            empty_volume += n_volume(list_of_boxes[0])
            unknownvolume = unknownvolume - n_volume(list_of_boxes[0])
            list_of_boxes.remove(list_of_boxes[0])
        else:
            eval_jac = [[
                ft.arb(evaluation_poly_list(jac_ij, list_of_boxes[0]))
                for jac_ij in jac_i
            ] for jac_i in jac]
            if invertibility_of_a_matrix(
                    eval_jac) == 1:  # 0 not in (ft.arb_mat(eval_jac)).det():
                #print(ft.arb_mat(eval_jac))
                regular_boxes.append(list_of_boxes[0])
                regular_volume = regular_volume + n_volume(list_of_boxes[0])
                unknownvolume = unknownvolume - n_volume(list_of_boxes[0])
                list_of_boxes.remove(list_of_boxes[0])
            else:
                new_children = subdivide(list_of_boxes[0])
                list_of_boxes.remove(list_of_boxes[0])
                list_of_boxes = list_of_boxes + new_children

    if len(list_of_boxes) != 0:
        smoothness = -1

    return smoothness
Beispiel #16
0
def matrixval(jac, X):  #jac as i_minor and X is a list of ft.arb
    #coeffs_matrix_matrix=[copy(jaci) for jaci in jac]
    evaluation_jac_X = [copy(jaci) for jaci in jac]
    for i in range(len(jac)):
        for j in range(len(jac[0])):
            evaluation_jac_X[i][j] = evaluation_poly_list(jac[i][j], X)
            if evaluation_jac_X[i][
                    j] == 0:  #fixing a bug in flint since Python cannot create arb from type <class 'sympy.core.numbers.Zero'>
                evaluation_jac_X[i][j] = ft.arb(0)
    return evaluation_jac_X
Beispiel #17
0
def interval_difference_enclosure(a, b):
    if a in b:
        Difference = 'empty'
    else:
        try:
            Intersection = a.intersection(b)
            if Intersection.upper() >= a.upper():
                Difference = ft.arb(
                    0.5 * a.lower() + 0.5 * Intersection.lower(),
                    0.5 * Intersection.lower() - 0.5 * a.lower())
            elif Intersection.lower() <= a.lower():
                Difference = ft.arb(
                    0.5 * a.upper() + 0.5 * Intersection.upper(),
                    0.5 * a.upper() - 0.5 * Intersection.upper())
            else:
                Difference = a
        except:
            Difference = a
    return Difference
def arb_trace(M):
	""" Computes the trace of the matrix M """
	# Matrix size
	n, m = arb_mat.nrows(M), arb_mat.ncols(M)
	
	# Computation
	res = arb(0)
	for i in range(n):
		res = res + M[i,i]

	return res
Beispiel #19
0
def intersection_of_bounded_with_unbounded_interval(
    x, boundary, infty
):  #returns the intersection of x with [boundary, infty] where infty= 1 or -1  is corresponding to + infty or -infty respectevly
    Intersection = x
    if infty == 1:
        if x.upper() < boundary:
            Intersection = 'empty'
        elif x.upper() >= boundary and x.lower() < boundary:
            Intersection = ft.arb(0.5 * x.upper() + 0.5 * boundary,
                                  0.5 * x.upper() - 0.5 * boundary)
        elif x.lower() >= boundary:
            Intersection = x
    else:
        if x.lower() > boundary:
            Intersection = 'empty'
        elif x.lower() <= boundary and x.upper() > boundary:
            Intersection = ft.arb((0.5 * x.lower()) + (0.5 * boundary),
                                  (0.5 * boundary) - (0.5 * x.lower()))
        elif x.upper() <= boundary:
            Intersection = x
    return Intersection
Beispiel #20
0
def intervals_multi(
    B1, B2
):  #does interval multiplication for B1,B2 if they are of different sign to avoid a bug in flint
    if type(B1) != type(ft.arb(1)):
        B1 = ft.arb(float(B1))
    if type(B2) != type(ft.arb(1)):
        B2 = ft.arb(float(B2))
    end_points = [
        B1.lower() * B2.lower(),
        B1.lower() * B2.upper(),
        B1.upper() * B2.lower(),
        B1.upper() * B2.upper()
    ]
    if 0 not in B1 and 0 not in B2:
        lower_point = min(end_points)
        upper_point = max(end_points)
        the_product = ft.arb(0.5 * (upper_point + lower_point),
                             0.5 * (upper_point - lower_point))
    else:
        the_product = B1 * B2
    return the_product
Beispiel #21
0
def invertibility_of_a_matrix(
    M
):  # M is interval matrix .. invertibility_of_a_matrix(M) returns 0 if we are sure that M is singular, 1 if we are sure that M invertable and -1 if we do not  know.. The smaller width M has the more sure we are
    Answer = 3

    L = [[
        Mij.mid() if type(Mij) == type(ft.arb(1)) else ft.arb(float(Mij))
        for Mij in Mi
    ] for Mi in M]
    T = []
    try:
        T = (Matrix(L)).inv()
    except:
        Answer = 0
    if Answer == 3:
        T_list = [[float(T[j, i]) for i in range(len(M))]
                  for j in range(len(M))]
        Pre_cond = matrix_multi(T_list, M)
        E = ft.arb_mat(T_list) * ft.arb_mat(M)
        zero_eigenvalue_detected = 0
        Gersh = gershgorin_circles(Pre_cond)

        for R in Gersh:
            if 0 in R:
                zero_eigenvalue_detected = 1
                break
        if zero_eigenvalue_detected == 0:
            Answer = 1
        if zero_eigenvalue_detected == 1:
            Answer = -1
        #print('the inver: ', Answer)
        #print([[[Mij.lower(),Mij.upper()] for Mij in Mi] for Mi in Pre_cond  ])
        #print('Gersh=',[[R.lower(),R.upper()] for R in Gersh ])

        #if 0 not in E.det():
        #    Answer=1
        #else:
        #    Answer = -1

    return Answer  #here is a problem
Beispiel #22
0
 def test_sage_examples_slow(self):
     if 0:
         x = fmpz_poly([0, 1])
         pol = x**10 + x**9 - x**7 - x**6 - x**5 - x**4 - x**3 + x + 1
         root = arb("[1.17628081825991751 +/- 3.46e-18]")
         alpha = alg(_minpoly=pol, _enclosure=root)
         lhs = alpha**630 - 1
         rhs_num = (alpha**315 - 1) * (alpha**210 - 1) * (
             alpha**126 - 1)**2 * (alpha**90 - 1) * (alpha**3 - 1)**3 * (
                 alpha**2 - 1)**5 * (alpha - 1)**3
         rhs_den = (alpha**35 - 1) * (alpha**15 - 1)**2 * (
             alpha**14 - 1)**2 * (alpha**5 - 1)**6 * alpha**68
         rhs = rhs_num / rhs_den
         assert lhs == rhs
Beispiel #23
0
def curve_tracer(
    P,
    B,
    jac,
    wth=0.001,
    wth2=1
):  #returns all list of boxes that contains smooth parts of a curve and it stops if the curve is smooth
    list_of_boxes = [B]
    smoothness = 1
    regular_boxes = []
    smoothness = 1
    while len(list_of_boxes) != 0 and width(list_of_boxes[0]) > wth:
        membership = 1
        eval_P = [evaluation_poly_list(Pi, list_of_boxes[0]) for Pi in P
                  ]  #checking whether the box contains a point of the curve
        for eval_Pi_at_B in eval_P:
            if 0 not in ft.arb(1) * (eval_Pi_at_B):
                membership = 0
        if membership == 0:
            list_of_boxes.remove(list_of_boxes[0])
            #print("empty")
        else:
            eval_jac = [[
                evaluation_poly_list(jac_ij, list_of_boxes[0])
                for jac_ij in Jac_i
            ] for Jac_i in jac]
            full_rankness = checking_full_rank(eval_jac)
            if full_rankness == 1 and width(list_of_boxes[0]) < wth2:
                #print([ [round(float(jac_ij.lower()),5),round(float(jac_ij.upper()),5)] for jac_ij in list_of_boxes[0]  ])
                #input()
                #print("regular")
                #input()
                regular_boxes.append(list_of_boxes[0])
                list_of_boxes.remove(list_of_boxes[0])
            else:
                #print('width=',width(list_of_boxes[0]))
                #print('the box',[ [round(float(jac_ij.lower()),5),round(float(jac_ij.upper()),5)] for jac_ij in list_of_boxes[0]  ])
                #pprint(Matrix([ [[round(float(jac_ij.lower()),5),round(float(jac_ij.upper()),5)] for jac_ij in jac_i] for jac_i in eval_jac  ]))
                #input()
                #print("we do not know")
                new_children = subdivide(list_of_boxes[0])
                list_of_boxes.remove(list_of_boxes[0])
                list_of_boxes = list_of_boxes + new_children
    if len(list_of_boxes) != 0:
        smoothness = -1
        #print(list_of_boxes[0])
    return [regular_boxes, list_of_boxes]
Beispiel #24
0
def polyvalnd(M, X):
    evaluation = ft.arb(0)

    if len(X) == 1:
        N = []
        for Mi in M:  #to avoid the problem: sp.Integer * arb = not correct answer
            if type(Mi) != ft.arb:
                N.append(float(Mi))
            else:
                N.append(Mi)
        evaluation = np.polynomial.polynomial.polyval(X[0], N)
    else:
        Y = copy(X[0:len(X) - 1])
        N = copy([polyvalnd(Mi, Y) for Mi in M])

        evaluation = np.polynomial.polynomial.polyval(X[len(X) - 1], N)
    return evaluation
Beispiel #25
0
def checking_regularity_of_sysyem1(P, B, jac, wth=0.2):
    M = [coefficient_matrix_list(Pi) for Pi in P]
    list_of_boxes = [B]
    smoothness = 1
    regular_boxes = []
    regular_volume = 0
    empty_volume = 0
    unknownvolume = n_volume(B)
    it = 0
    while len(list_of_boxes) != 0 and width(list_of_boxes[0]) > wth:
        #print(width(list_of_boxes[0]))
        membership = 1
        eval_P = [polyvalnd(Mi, list_of_boxes[0]) for Mi in M]

        for eval_Pi_at_B in eval_P:
            if 0 not in ft.arb(1) * (eval_Pi_at_B):
                membership = 0
                break
        if membership == 0:
            empty_volume += n_volume(list_of_boxes[0])
            unknownvolume = unknownvolume - n_volume(list_of_boxes[0])
            regular_boxes.append(list_of_boxes[0])
            list_of_boxes.remove(list_of_boxes[0])

        else:
            eval_jac = matrixval(jac, list_of_boxes[0])
            full_rankness = invertibility_of_a_matrix(eval_jac)
            if full_rankness == 1:
                regular_volume += n_volume(list_of_boxes[0])
                unknownvolume = unknownvolume - n_volume(list_of_boxes[0])
                regular_boxes.append(list_of_boxes[0])
                list_of_boxes.remove(list_of_boxes[0])

            else:
                new_children = subdivide(list_of_boxes[0])
                list_of_boxes.remove(list_of_boxes[0])
                list_of_boxes = list_of_boxes + new_children
        print("regular volume=", regular_volume)
        print("empty volume=", empty_volume)
        print("unknown volume=", unknownvolume)
        #print('Unknown box detected')
        #if len(list_of_boxes)!=0:
        #smoothness=-1

    return regular_boxes
Beispiel #26
0
 def test_guess(self):
     assert alg.guess(arb(123) / 3789, 1) == alg(123) / 3789
     assert alg.guess(arb(5) + acb(2).sqrt() * 1j,
                      2) == alg(5) + alg(2).sqrt() * alg.i()
     assert alg.guess(arb(5) / 64 + acb(0, 37) / 256,
                      2) == alg(5) / 64 + (alg(37) / 256) * alg.i()
     orig = ctx.prec
     try:
         ctx.dps = 200
         assert alg.guess(arb(2).root(6) + arb(3).root(5),
                          30) == alg(2).root(6) + alg(3).root(5)
     finally:
         ctx.prec = orig
     assert alg.guess(arb("3.1415926535897932 +/- 1e-5"), 1,
                      check=False) == alg(22) / 7
     assert alg.guess(arb("3.1415926535897932 +/- 1e-8"), 1,
                      check=False) == alg(355) / 113
def evaluation_exp(expr, B, X):
    expr_int = expr
    n = len(B_Ball)
    n = int((n + 1) / 2)
    for i in range(n):
        expr_int = expr_int.replace("x" + str(i + 1), "B_f[" + str(i) + "]")
    for i in range(n, len(X) - 1):
        expr_int = expr_int.replace("r" + str(i + 3 - n),
                                    "B_f[" + str(i) + "]")
    expr_int = expr_int.replace("t", "B_f[" + str(len(X) - 1) + "]")
    f = open("evaluation_file.py", "w")
    f.write("import flint as ft\n")
    f.write("import draft as d \n")
    f.write("from sympy.parsing.sympy_parser import parse_expr \n")
    f.write("from sympy import * \n")
    f.write("from numpy import * \n")
    f.write("import operator \n")
    f.write("def eval_func(): \n")
    for i in range(n):
        f.write(" x" + str(i + 1) + "=Symbol(\"" + str(X[i]) + "\"  )\n")
    for i in range(n, len(X) - 1):
        f.write(" r" + str(i - n + 3) + "=Symbol(\"" + str(X[i]) + "\"  )\n")
    f.write(" t" + "=Symbol(\"" + str(X[len(X) - 1]) + "\"  )\n")
    f.write(" B=" + str(B) + "\n")
    f.write(" f=srepr( parse_expr ( \"  " + str(expr) + "  \") ) \n")
    f.write(" B_f=[ d.ftconstructor(Bi[0],Bi[1]) for Bi in B ]  \n")
    for i in range(len(X)):
        f.write(" f=f.replace(\"Symbol(\'"+str(X[i])+\
         "\')\", \" B_f[ "+str(i) +"] \")  \n")
    f.write(" f=f.replace(\"Add\",\"d.sevr_add\")\n")
    f.write(" f=f.replace(\"Mul\",\"d.sevr_mul\")\n")
    f.write(" f=f.replace(\"Pow\",\"d.power_interval\")\n")
    f.write(" f=f.replace(\"Integer\",\"int\")\n")
    f.write(" f=f.replace(\"Float\",\"float\")\n")
    f.write(" f=f.replace(\", precision=53\", \"\")\n")
    #f.write("B_f=[ d.interv(d.ftconstructor(Bi[0],Bi[1])) for Bi in B ]  \n"    )
    f.write(" return eval(f) \n")
    f.close()
    #from  evaluation_file import  eval_func
    answer = ft.arb(eval_func())

    return [float(answer.lower()), float(answer.upper())]
Beispiel #28
0
def gershgorin_circles(M):  #returns Gershgorin circles of an intrival matrix M
    radius = [0] * (len(M))
    for i in range(len(M)):
        for j in range(len(M)):
            if i != j:
                radius[i] = radius[i] + abs_value(M[i][j])
    T = [
    ]  #Now we have that radius is the list of the radiuses of  The gershgorin circles
    i = 0

    for i in range(len(radius)):
        m_lower = float((M[i][i]).lower())
        m_upper = float((M[i][i]).upper())
        r_upper = float((radius[i]).upper())
        gershgorin_lower = m_upper + r_upper
        gershgorin_upper = m_lower - r_upper
        T.append(
            ft.arb(0.5 * (gershgorin_upper + gershgorin_lower),
                   0.5 * (gershgorin_upper - gershgorin_lower)))
    return T
Beispiel #29
0
def plotadaptive(ax,
                 f,
                 xab,
                 yab,
                 goal=0.1,
                 yrange=None,
                 color=None,
                 label=None,
                 hatch=None,
                 alpha=1.0):
    queue = [arb(0.5 * (xab[0] + xab[1]), 0.5 * (xab[1] - xab[0]))]
    top = 0.0
    bot = 0.0
    while queue:
        X = queue.pop()
        Y = f(X)
        xmid = float(arb(X.mid()))
        xrad = float(arb(X.rad()))
        ymid = float(arb(Y.mid()))
        yrad = float(arb(Y.rad()))
        if yrad < goal:
            top = max(top, (ymid + yrad) * 1.2)
            bot = min(bot, (ymid - yrad) * 1.2)
            ax.add_patch(
                patches.Rectangle((xmid - xrad, ymid - yrad),
                                  2 * xrad,
                                  2 * yrad,
                                  color=color,
                                  alpha=alpha,
                                  hatch=hatch))
        elif xrad > goal * 0.001:
            xa = arb(xmid - xrad * 0.5, xrad * 0.5)
            xb = arb(xmid + xrad * 0.5, xrad * 0.5)
            queue += [xa, xb]
            #ax.add_patch(patches.Rectangle((xmid-xrad, -1e50), 2*xrad, 1e50, color=color, alpha=alpha, hatch=hatch))
    ax.set_xlim([xab[0], xab[1]])
    if yab is None:
        ax.set_ylim([bot, top])
    else:
        ax.set_ylim(yab)
    patch1 = mpatches.Patch(color=color, label=label, alpha=alpha, hatch=hatch)
    legends.append(patch1)
Beispiel #30
0
def test_fmpz_poly():
    Z = flint.fmpz_poly
    assert Z() == Z([])
    assert Z() == Z([0])
    assert Z() == Z([0, flint.fmpz(0), 0])
    assert Z() == Z([0, 0, 0])
    assert Z() != Z([1])
    assert Z([1]) == Z([1])
    assert Z([1]) == Z([flint.fmpz(1)])
    assert Z(Z([1, 2])) == Z([1, 2])
    for ztype in [int, long, flint.fmpz]:
        assert Z([1, 2, 3]) + ztype(5) == Z([6, 2, 3])
        assert ztype(5) + Z([1, 2, 3]) == Z([6, 2, 3])
        assert Z([1, 2, 3]) - ztype(5) == Z([-4, 2, 3])
        assert ztype(5) - Z([1, 2, 3]) == Z([4, -2, -3])
        assert Z([1, 2, 3]) * ztype(5) == Z([5, 10, 15])
        assert ztype(5) * Z([1, 2, 3]) == Z([5, 10, 15])
        assert Z([11, 6, 2]) // ztype(5) == Z([2, 1])
        assert ztype(5) // Z([-2]) == Z([-3])
        assert ztype(5) // Z([1, 2]) == 0
        assert Z([11, 6, 2]) % ztype(5) == Z([1, 1, 2])
        assert ztype(5) % Z([-2]) == Z([-1])
        assert ztype(5) % Z([1, 2]) == 5
        assert Z([1, 2, 3])**ztype(0) == 1
        assert Z([1, 2, 3])**ztype(1) == Z([1, 2, 3])
        assert Z([1, 2, 3])**ztype(2) == Z([1, 4, 10, 12, 9])
    assert +Z([1, 2]) == Z([1, 2])
    assert -Z([1, 2]) == Z([-1, -2])
    assert raises(lambda: Z([1, 2, 3])**-1, (OverflowError, ValueError))
    assert raises(lambda: Z([1, 2, 3])**Z([1, 2]), TypeError)
    assert raises(lambda: Z([1, 2]) // Z([]), ZeroDivisionError)
    assert raises(lambda: Z([]) // Z([]), ZeroDivisionError)
    assert raises(lambda: Z([1, 2]) % Z([]), ZeroDivisionError)
    assert raises(lambda: divmod(Z([1, 2]), Z([])), ZeroDivisionError)
    assert Z([]).degree() == -1
    assert Z([]).length() == 0
    p = Z([1, 2])
    assert p.length() == 2
    assert p.degree() == 1
    assert p[0] == 1
    assert p[1] == 2
    assert p[2] == 0
    assert p[-1] == 0
    assert raises(lambda: p.__setitem__(-1, 1), ValueError)
    p[0] = 3
    assert p[0] == 3
    p[4] = 7
    assert p.degree() == 4
    assert p[4] == 7
    assert p[3] == 0
    p[4] = 0
    assert p.degree() == 1
    assert p.coeffs() == [3, 2]
    assert Z([]).coeffs() == []
    assert bool(Z([])) == False
    assert bool(Z([1])) == True
    ctx.pretty = False
    assert repr(Z([1, 2])) == "fmpz_poly([1, 2])"
    ctx.pretty = True
    assert str(Z([1, 2])) == "2*x + 1"
    p = Z([3, 4, 5])
    assert p(2) == 31
    assert p(flint.fmpq(2, 3)) == flint.fmpq(71, 9)
    assert p(Z([1, -1])) == Z([12, -14, 5])
    assert p(flint.fmpq_poly([2, 3], 5)) == flint.fmpq_poly([27, 24, 9], 5)
    assert p(flint.arb("1.1")).overlaps(flint.arb("13.45"))
    assert p(flint.acb("1.1", "1.2")).overlaps(flint.acb("6.25", "18.00"))
Beispiel #31
0
    def build(self, entries):
        from flint import ctx, arb, acb
        from . import formulas

        digits = 30
        eval_digits = 40
        count = 0
        excluded = set([Parentheses, Brackets, Braces])
        ctx.dps = eval_digits  # for local manipulations

        # expr -> arb/acb value
        expressions_values = {}
        # expr -> entries containing expr (with repetitions!)
        expressions_entries = {}

        def insert(expr, val, eid):
            expressions_values[expr] = val
            if expr in expressions_entries:
                expressions_entries[expr] += (eid, )
            else:
                expressions_entries[expr] = (eid, )

        def insert_real(expr, val, eid):
            if val == 0:
                insert(expr, val, eid)
            if val != 0:
                if val < 0:
                    insert(Neg(expr), -val, eid)
                else:
                    insert(expr, val, eid)

        # arb or acb
        def insert_arb(expr, val, eid):
            if isinstance(val, arb):
                insert_real(expr, val, eid)
            else:
                a = val.real
                b = val.imag
                if a != 0:
                    insert_real(Re(expr), a, eid)
                if b != 0:
                    insert_real(Im(expr), b, eid)
                if a != 0 and b != 0:
                    insert_real(Abs(expr), abs(val), eid)
                    insert_real(Arg(expr), val.arg(), eid)

        def insert_expr(expr, eid):
            if expr == Exp:
                insert_real(Expr("Indirect use of e: Exp(...)"),
                            ConstE.n(eval_digits, as_arb=True), eid)
            if expr.head() not in excluded:
                if expr in expressions_values:
                    val = expressions_values[expr]
                else:
                    try:
                        val = expr.n(eval_digits, as_arb=True)
                    except (ValueError, NotImplementedError):
                        return
                insert_arb(expr, val, eid)

        # todo: second passes for subexpressions, symbolic equalities?
        print("Evaluating tables...")
        for entry in entries:
            eid = entry.id()
            for expr, val in table_values(entry):
                if expr.head() == NearestDecimal:
                    expr, numdigits = expr.args()
                    if numdigits.is_integer() and int(numdigits) >= digits:
                        val = val.n(eval_digits, as_arb=True)
                        # todo ...
                        insert_arb(expr, val, eid)

        print("Evaluating declared constant values...")
        for entry in entries:
            # only look for constant equations
            variables = entry.get_arg_with_head(Variables)
            if variables is not None:
                continue
            formula = entry.get_arg_with_head(Formula)
            if formula is None:
                continue
            eid = entry.id()
            content = formula.args()[0]
            if content.head() == EqualNearestDecimal:
                expr, val, numdigits = content.args()
                if numdigits.is_integer() and int(numdigits) >= digits:
                    print(expr, val, numdigits)
                    val = val.n(eval_digits, as_arb=True)
                    insert_arb(expr, val, eid)

        print("Evaluating expressions...")
        for entry in entries:
            eid = entry.id()
            for expr in entry.subexpressions():
                insert_expr(expr, eid)

        print("Evaluating tables, 2...")
        for entry in entries:
            eid = entry.id()
            for expr, val in table_values(entry):
                if expr.head() != NearestDecimal:
                    insert_expr(expr, eid)
                    insert_expr(val, eid)
                    if val in expressions_values and expr not in expressions_values:
                        insert(expr, expressions_values[val], eid)

        # todo: handle complex numbers (need to keep symbolics above?)
        # insert symbolic equations
        print("Adding symbolic equalities...")
        for entry in entries:
            # only look for constant equations
            variables = entry.get_arg_with_head(Variables)
            if variables is not None:
                continue
            formula = entry.get_arg_with_head(Formula)
            if formula is None:
                continue
            eid = entry.id()
            content = formula.args()[0]
            if content.head() == Equal:
                for arg in content.args():
                    if arg in expressions_values:
                        for arg2 in content.args():
                            if arg2 not in expressions_values:
                                print("  ", arg2, " = ", arg)
                                insert(arg2, expressions_values[arg], eid)
                        break

        print("Building final tables...")

        # expr -> str(expr) ?
        expressions_values = dict(
            (str(expr), val) for (expr, val) in expressions_values.items())
        expressions_entries = dict(
            (str(expr), val) for (expr, val) in expressions_entries.items())

        # xxx: missing .is_int / .is_integer method
        def _arb_isint(x):
            return arb(x) == arb(x).floor() or arb(x) > 10**digits

        integer_values = set()

        # convert arb/acb values to decimal keys
        for expr in expressions_values:
            val = expressions_values[expr]
            # save integerness
            isint = _arb_isint(val)
            if val == 0:
                val = "0.0" + "0" * (digits - 2)
            else:
                val = val.str(digits, radius=False)
            expressions_values[expr] = val
            if isint:
                integer_values.add(val)

        # reverse the table
        values_expressions = {}

        # some rankings
        values_frequency = {}
        values_diversity = {}
        for expr, val in expressions_values.items():
            #if val in values_frequency:
            #    values_frequency[val] += len(expressions_entries[expr])
            #else:
            #    values_frequency[val] = len(expressions_entries[expr])

            if val in values_diversity:
                values_diversity[val] += 1
            else:
                values_diversity[val] = 1

            if val in values_expressions:
                values_expressions[val].add(expr)
            else:
                values_expressions[val] = set([expr])

        for val, expressions in values_expressions.items():
            val_entries = set()
            for expr in expressions:
                for ent in expressions_entries[expr]:
                    val_entries.add(ent)
            values_frequency[val] = len(val_entries)

        values_ordered = list(values_expressions.keys())
        values_ordered.sort(key=lambda d: arb(d))

        values_ordered_frequency = list(values_expressions.keys())
        values_ordered_frequency.sort(key=lambda d: values_frequency[d],
                                      reverse=True)
        values_ordered_diversity = list(values_expressions.keys())
        values_ordered_diversity.sort(key=lambda d: values_diversity[d],
                                      reverse=True)

        self.integer_values = integer_values
        self.values_expressions = values_expressions
        self.values_frequency = values_frequency
        self.values_diversity = values_diversity
        self.values_ordered = values_ordered
        self.values_ordered_frequency = values_ordered_frequency
        self.values_ordered_diversity = values_ordered_diversity
        self.expressions_values = expressions_values
        self.expressions_entries = expressions_entries