Пример #1
0
def _djacobi_theta2a(z, q, nd):
    """
    case z.imag != 0
    dtheta(2, z, q, nd) =
    j* q**1/4 * Sum(q**(n*n + n) * (2*n+1)*exp(j*(2*n + 1)*z), n=-inf, inf)
    max term for (2*n0+1)*log(q).real - 2* z.imag ~= 0
    n0 = int(z.imag/log(q).real - 1/2)
    """
    n = n0 = int(z.imag/log(q).real - 1/2)
    e2 = exp(2*j*z)
    e = e0 = exp(j*(2*n + 1)*z)
    a = q**(n*n + n)
    # leading term
    term = (2*n+1)**nd * a * e
    s = term
    eps1 = eps*abs(term)
    while 1:
        n += 1
        e = e * e2
        term = (2*n+1)**nd * q**(n*n + n) * e
        if abs(term) < eps1:
            break
        s += term
    e = e0
    e2 = exp(-2*j*z)
    n = n0
    while 1:
        n -= 1
        e = e * e2
        term = (2*n+1)**nd * q**(n*n + n) * e
        if abs(term) < eps1:
            break
        s += term
    return j**nd * s * nthroot(q, 4)
Пример #2
0
def _jacobi_theta3a(z, q):
    """
    case z.imag != 0
    theta3(z, q) = Sum(q**(n*n) * exp(j*2*n*z), n, -inf, inf)
    max term for n*abs(log(q).real) + z.imag ~= 0
    n0 = int(- z.imag/abs(log(q).real))
    """
    n = n0 = int(- z.imag/abs(log(q).real))
    e2 = exp(2*j*z)
    e = e0 = exp(j*2*n*z)
    s = term = q**(n*n) * e
    eps1 = eps*abs(term)
    while 1:
        n += 1
        e = e * e2
        term = q**(n*n) * e
        if abs(term) < eps1:
            break
        s += term
    e = e0
    e2 = exp(-2*j*z)
    n = n0
    while 1:
        n -= 1
        e = e * e2
        term = q**(n*n) * e
        if abs(term) < eps1:
            break
        s += term
    return s
Пример #3
0
def _calc_spouge_coefficients(a, prec):
    """
    Calculate Spouge coefficients for approximation with parameter a.
    Return a list of big integers representing the coefficients in
    fixed-point form with a precision of prec bits.
    """

    # We'll store the coefficients as fixed-point numbers but calculate
    # them as Floats for convenience. The initial terms are huge, so we
    # need to allocate extra bits to ensure full accuracy. The integer
    # part of the largest term has size ~= exp(a) or 2**(1.4*a)
    floatprec = prec + int(a*1.4)
    Float.store()
    Float.setprec(floatprec)

    c = [0] * a
    b = exp(a-1)
    e = exp(1)
    c[0] = make_fixed(sqrt(2*pi_float()), prec)
    for k in range(1, a):
        # print "%02f" % (100.0 * k / a), "% done"
        c[k] = make_fixed(((-1)**(k-1) * (a-k)**k) * b / sqrt(a-k), prec)
        # Divide off e and k instead of computing exp and k! from scratch
        b = b / (e * k)

    Float.revert()
    return c
Пример #4
0
def zeta(s):
    """
    zeta(s) -- calculate the Riemann zeta function of a real or complex
    argument s.

    """
    Float.store()
    Float._prec += 8
    si = s
    s = ComplexFloat(s)
    if s.real < 0:
        # Reflection formula (XXX: gets bad around the zeros)
        pi = pi_float()
        y = power(2, s) * power(pi, s-1) * sin(pi*s/2) * gamma(1-s) * zeta(1-s)
    else:
        p = Float._prec
        n = int((p + 2.28*abs(float(s.imag)))/2.54) + 3
        d = _zeta_coefs(n)
        if isinstance(si, (int, long)):
            t = 0
            for k in range(n):
                t += (((-1)**k * (d[k] - d[n])) << p) // (k+1)**si
            y = (Float((t, -p)) / -d[n]) / (Float(1) - Float(2)**(1-si))
        else:
            t = Float(0)
            for k in range(n):
                t += (-1)**k * Float(d[k]-d[n]) * exp(-_logk(k+1)*s)
            y = (t / -d[n]) / (Float(1) - exp(log(2)*(1-s)))
    Float.revert()
    if isinstance(y, ComplexFloat) and s.imag == 0:
        return +y.real
    else:
        return +y
Пример #5
0
def lower_gamma(a, z):
    Float.store()
    prec = Float._prec
    # XXX: may need more precision
    Float._prec += 15
    a = ComplexFloat(a)
    z = ComplexFloat(z)
    s = _lower_gamma_series(a.real, a.imag, z.real, z.imag, prec)
    y = exp(log(z)*a) * exp(-z) * s / a
    Float.revert()
    return +y
Пример #6
0
def calculate_nome(k):
    """
    Calculate the nome, q, from the value for k.

    Useful factoids:

    k**2 = m;   m is used in Abramowitz
    """
    k = convert_lossless(k)

    if k > mpf('1'):             # range error
        raise ValueError

    zero = mpf('0')
    one = mpf('1')

    if k == zero:
        return zero
    elif k == one:
        return one
    else:
        kprimesquared = one - k**2
        kprime = sqrt(kprimesquared)
        top = ellipk(kprimesquared)
        bottom = ellipk(k**2)

        argument = mpf('-1')*pi*top/bottom

        nome = exp(argument)
        return nome
Пример #7
0
def calculate_nome(k):
    """
    Calculate the nome, q, from the value for k.

    Useful factoids:

    k**2 = m;   m is used in Abramowitz
    """
    k = mpmathify(k)

    if abs(k) > one:             # range error
        raise ValueError

    if k == zero:
        return zero
    elif k == one:
        return one
    else:
        kprimesquared = one - k**2
        kprime = sqrt(kprimesquared)
        top = ellipk(kprimesquared)
        bottom = ellipk(k**2)

        argument = -pi*top/bottom

        nome = exp(argument)
        return nome
Пример #8
0
def calculate_nome(k):
    """
    Calculate the nome, q, from the value for k.

    Useful factoids:

    k**2 = m;   m is used in Abramowitz
    """
    k = convert_lossless(k)

    if k > mpf('1'):  # range error
        raise ValueError

    zero = mpf('0')
    one = mpf('1')

    if k == zero:
        return zero
    elif k == one:
        return one
    else:
        kprimesquared = one - k**2
        kprime = sqrt(kprimesquared)
        top = ellipk(kprimesquared)
        bottom = ellipk(k**2)

        argument = mpf('-1') * pi * top / bottom

        nome = exp(argument)
        return nome
Пример #9
0
def _djacobi_theta3a(z, q, nd):
    """
    case z.imag != 0
    djtheta3(z, q, nd) = (2*j)**nd *
      Sum(q**(n*n) * n**nd * exp(j*2*n*z), n, -inf, inf)
    max term for minimum n*abs(log(q).real) + z.imag
    """
    n = n0 = int(-z.imag/abs(log(q).real))
    e2 = exp(2*j*z)
    e = e0 = exp(j*2*n*z)
    a = q**(n*n) * e
    s = term = n**nd * a
    if n != 0:
        eps1 = eps*abs(term)
    else:
        eps1 = eps*abs(a)
    while 1:
        n += 1
        e = e * e2
        a = q**(n*n) * e
        term = n**nd * a
        if n != 0:
            aterm = abs(term)
        else:
            aterm = abs(a)
        if aterm < eps1:
            break
        s += term
    e = e0
    e2 = exp(-2*j*z)
    n = n0
    while 1:
        n -= 1
        e = e * e2
        a = q**(n*n) * e
        term = n**nd * a
        if n != 0:
            aterm = abs(term)
        else:
            aterm = abs(a)
        if aterm < eps1:
            break
        s += term
    return (2*j)**nd * s
Пример #10
0
def gamma(x):
    """
    gamma(x) -- calculate the gamma function of a real or complex
    number x.
    
    x must not be a negative integer or 0
    """
    Float.store()
    Float._prec += 2

    if isinstance(x, complex):
        x = ComplexFloat(x)
    elif not isinstance(x, (Float, ComplexFloat, Rational, int, long)):
        x = Float(x)

    if isinstance(x, (ComplexFloat, complex)):
        re, im = x.real, x.imag
    else:
        re, im = x, 0

    # For negative x (or positive x close to the pole at x = 0),
    # we use the reflection formula
    if re < 0.25:
        if re == int(re) and im == 0:
            raise ZeroDivisionError, "gamma function pole"
        Float._prec += 3
        p = pi_float()
        g = p / (sin(p*x) * gamma(1-x))
    else:
        x -= 1
        prec, a, c = _get_spouge_coefficients(Float.getprec()+7)
        s = _spouge_sum(x, prec, a, c)
        if not isinstance(x, (Float, ComplexFloat)):
            x = Float(x)
        # TODO: higher precision may be needed here when the precision
        # and/or size of x are extremely large
        Float._prec += 10
        g = exp(log(x+a)*(x+Float(0.5))) * exp(-x-a) * s

    Float.revert()
    return +g
Пример #11
0
def plotTotalTransitionRate(x,y, title):
    fig, ax = plt.subplots(1, 1, sharey=True, figsize=(5,4))
    fig.subplots_adjust(top=0.85, bottom=0.15, left=0.20, right=0.95, hspace=0.25, wspace=0.35)
    ax.plot(x,y,".-", label="data")
    [a,b] = fun.linearFit(x,y,0,len(x))
    ax.plot(x,fun.exp(x,a,b), label=r"$f(x) = "+str(a)+r"x^{"+str(b)+r"}$")
    ax.set_title(title)
    ax.set_xlabel(r"$1/k_BT$")
    ax.set_yscale("log")
    ax.legend(loc="best")
    fig.savefig(title+".svg")
    plt.close(fig)
Пример #12
0
def _jacobi_theta2a(z, q):
    """
    case z.imag != 0
    theta(2, z, q) =
    q**1/4 * Sum(q**(n*n + n) * exp(j*(2*n + 1)*z), n=-inf, inf)
    max term for minimum (2*n+1)*log(q).real - 2* z.imag
    n0 = int(z.imag/log(q).real - 1/2)
    theta(2, z, q) =
    q**1/4 * Sum(q**(n*n + n) * exp(j*(2*n + 1)*z), n=n0, inf) +
    q**1/4 * Sum(q**(n*n + n) * exp(j*(2*n + 1)*z), n, n0-1, -inf)
    """
    n = n0 = int(z.imag/log(q).real - 1/2)
    e2 = exp(2*j*z)
    e = e0 = exp(j*(2*n + 1)*z)
    a = q**(n*n + n)
    # leading term
    term = a * e
    s = term
    eps1 = eps*abs(term)
    while 1:
        n += 1
        e = e * e2
        term = q**(n*n + n) * e
        if abs(term) < eps1:
            break
        s += term
    e = e0
    e2 = exp(-2*j*z)
    n = n0
    while 1:
        n -= 1
        e = e * e2
        term = q**(n*n + n) * e
        if abs(term) < eps1:
            break
        s += term
    s = s * nthroot(q, 4)
    return s
Пример #13
0
    os.chdir(workingPath)
    ne = meanValues.getNumberOfEvents()
    time = meanValues.getTimes()
    T1 = 1 / (kb * temperatures)
    command = "ne/time"
    y = eval(command)
    plt.ylabel(command)
    command = "1/kb/temperatures"  #+np.log(flux**2.5)"
    x = eval(command)
    plt.xlabel(command)
    try:
        plt.semilogy(x, y, ".", label=folder + " " + str(j))

        if hex:
            a, b = f.fit(x, y, 0, 12)
            plt.semilogy(x, f.exp(x, a, b), label="fit low " + str(b))
            a, b = f.fit(x, y, 12, 17)
            plt.semilogy(x, f.exp(x, a, b), label="fit middle " + str(b))
            a, b = f.fit(x, y, 17, 30)
            plt.semilogy(x, f.exp(x, a, b), label="fit middle " + str(b))
            plt.ylim(1e9, 1e14)
        else:
            a, b = f.fit(x, y, 0, 8)
            plt.semilogy(x, f.exp(x, a, b), label="fit low " + str(b))
            a, b = f.fit(x, y, 8, 16)
            plt.semilogy(x, f.exp(x, a, b), label="fit middle " + str(b))
            a, b = f.fit(x, y, 17, 27)
            plt.semilogy(x, f.exp(x, a, b), label="fit high " + str(b))
        plt.legend(loc='best', prop={'size': 6})
        plt.savefig("ne.png")
    except ValueError:
Пример #14
0
    (lambda x, c: x * c, '$y/$c', 0),
    (lambda x, c: x / c, '$c*$y', 1),
    (lambda x, c: c / x, '$c/$y', 0),
    (lambda x, c: (x * c)**2, 'sqrt($y)/$c', 0),
    (lambda x, c: (x / c)**2, '$c*sqrt($y)', 1),
    (lambda x, c: (c / x)**2, '$c/sqrt($y)', 0),
    (lambda x, c: c * x**2, 'sqrt($y)/sqrt($c)', 1),
    (lambda x, c: x**2 / c, 'sqrt($c)*sqrt($y)', 1),
    (lambda x, c: c / x**2, 'sqrt($c)/sqrt($y)', 1),
    (lambda x, c: sqrt(x * c), '$y**2/$c', 0),
    (lambda x, c: sqrt(x / c), '$c*$y**2', 1),
    (lambda x, c: sqrt(c / x), '$c/$y**2', 0),
    (lambda x, c: c * sqrt(x), '$y**2/$c**2', 1),
    (lambda x, c: sqrt(x) / c, '$c**2*$y**2', 1),
    (lambda x, c: c / sqrt(x), '$c**2/$y**2', 1),
    (lambda x, c: exp(x * c), 'log($y)/$c', 0),
    (lambda x, c: exp(x / c), '$c*log($y)', 1),
    (lambda x, c: exp(c / x), '$c/log($y)', 0),
    (lambda x, c: c * exp(x), 'log($y/$c)', 1),
    (lambda x, c: exp(x) / c, 'log($c*$y)', 1),
    (lambda x, c: c / exp(x), 'log($c/$y)', 0),
    (lambda x, c: log(x * c), 'exp($y)/$c', 0),
    (lambda x, c: log(x / c), '$c*exp($y)', 1),
    (lambda x, c: log(c / x), '$c/exp($y)', 0),
    (lambda x, c: c * log(x), 'exp($y/$c)', 1),
    (lambda x, c: log(x) / c, 'exp($c*$y)', 1),
    (lambda x, c: c / log(x), 'exp($c/$y)', 0),
]


def identify(x,
Пример #15
0
    def calc_nodes(cls, prec, level, verbose=False):
        """
        The abscissas and weights for tanh-sinh quadrature are given by

            x[k] = tanh(pi/2 * sinh(t))
            w[k] = pi/2 * cosh(t) / cosh(pi/2 sinh(t))**2

        Here t varies uniformly with k: t0, t0+h, t0+2*h, ...

        The list of nodes is actually infinite, but the weights
        die off so rapidly that only a few are needed.
        """
        nodes = []

        extra = 20
        mp.prec += extra
        eps = ldexp(1, -prec - 10)
        pi4 = pi / 4

        # For simplicity, we work in steps h = 1/2^n, with the first point
        # offset so that we can reuse the sum from the previous level

        # We define level 1 to include the "level 0" steps, including
        # the point x = 0. (It doesn't work well otherwise; not sure why.)
        t0 = ldexp(1, -level)
        if level == 1:
            nodes.append((mpf(0), pi4))
            h = t0
        else:
            h = t0 * 2

        # Since h is fixed, we can compute the next exponential
        # by simply multiplying by exp(h)
        expt0 = exp(t0)
        a = pi4 * expt0
        b = pi4 / expt0
        udelta = exp(h)
        urdelta = 1 / udelta

        for k in xrange(0, 20 * 2**level + 1):
            # Reference implementation:
            # t = t0 + k*h
            # x = tanh(pi/2 * sinh(t))
            # w = pi/2 * cosh(t) / cosh(pi/2 * sinh(t))**2

            # Fast implementation. Note that c = exp(pi/2 * sinh(t))
            c = exp(a - b)
            d = 1 / c
            co = (c + d) / 2
            si = (c - d) / 2
            x = si / co
            w = (a + b) / co**2
            diff = abs(x - 1)
            if diff <= eps:
                break

            nodes.append((x, w))
            a *= udelta
            b *= urdelta

            if verbose and k % 300 == 150:
                # Note: the number displayed is rather arbitrary. Should
                # figure out how to print something that looks more like a
                # percentage
                print "Calculating nodes:", nstr(-log(diff, 10) / prec)

        mp.prec -= extra
        return nodes
Пример #16
0
loTerms = []


top = int(Decimal(2**(0+EXP_MAX_HI_TERM_VAL-EXP_NUM_OF_HI_TERMS)).exp()*FIXED_ONE)-1
for n in range(EXP_NUM_OF_HI_TERMS+1):
    cur = Decimal(2**(n+EXP_MAX_HI_TERM_VAL-EXP_NUM_OF_HI_TERMS)).exp()
    den = int((2**256-1)/(cur*top))
    num = int(den*cur)
    top = top*num//den
    bit = FIXED_ONE<<(n+EXP_MAX_HI_TERM_VAL)>>EXP_NUM_OF_HI_TERMS
    hiTerms.append(HiTerm(bit,num,den))


MAX_VAL = hiTerms[-1].bit-1
loTerms = [LoTerm(1,1)]
res = exp(MAX_VAL,hiTerms,loTerms,FIXED_ONE)
while True:
    n = len(loTerms)+1
    val = factorial(n)
    loTermsNext = [LoTerm(val//factorial(i+1),i+1) for i in range(n)]
    resNext = exp(MAX_VAL,hiTerms,loTermsNext,FIXED_ONE)
    if res < resNext:
        res = resNext
        loTerms = loTermsNext
    else:
        break


hiTermBitMaxLen = len(hex(hiTerms[-1].bit))
hiTermNumMaxLen = len(hex(hiTerms[ 0].num))
hiTermDenMaxLen = len(hex(hiTerms[ 0].den))
Пример #17
0
def start_mm1_simulation(LAMBDA, seed, packets_num, confidence_range):
    random.seed(seed)
    print("*************************")
    print("MM1 SIMULATION STARTED!!!")
    print("*************************")
    # sredni czas obslugi pakietu przez serwer
    time_of_service = 0.125
    # sredni odstep pomiedzy pakietami 0.5 - 6
    #LAMBDA = float(input("Input a LAMBDA please (0.5-6)"))
    average_time_between_packets = 1 / LAMBDA
    # czy serwer jest zajety
    is_server_busy = True
    # kolejka pakietow
    queue_of_packets = queue.Queue()
    # tablica zdarzen w symulacji
    list_of_events = []
    # czas symulacji
    clock = 0
    # licznik pakieto - ktory pakiet obslugujemy
    packetsCounter = 0
    # tablica wszystkich pakietow ktore braly udzial w symulacji
    packets = []
    # liczba obsluzonych pakietow2
    number_of_serviced_packets = 0
    # liczba pakietow ktora chcemy przesymulowac
    number_of_packets_for_simulation = packets_num

    # wygenerowanie pierwszego pakietu w symulacji
    first_packet = PacketMM1(exp(time_of_service),
                             exp(average_time_between_packets), -1, -1,
                             packetsCounter)
    packets.append(first_packet)
    packetsCounter += 1
    # wziecie pierwszego pakietu do obslugi - planowanie zakonczenia obslugi pierwszego pakietu
    list_of_events.append(
        plan_event_finish_service(
            first_packet.number_of_packet,
            first_packet.time_of_arrive,
            first_packet.time_of_service,
        ))
    # zaplanowanie zdarzenia przyjscia drugiego pakietu
    time_next_packet = exp(average_time_between_packets)
    list_of_events.append(
        plan_event_come_next_packet(clock, packetsCounter, time_next_packet))
    packets.append(
        PacketMM1(exp(time_of_service), time_next_packet, -1, -1,
                  packetsCounter))

    # sortowanie listy zdarzen po czasie
    list_of_events.sort(key=lambda Event: Event.time_of_event)

    packetsCounter += 1

    while number_of_serviced_packets < number_of_packets_for_simulation:
        # przejscie w symulacji do momentu czasu kolejnego zdarzenia
        clock = list_of_events[0].time_of_event
        # przypadek - przyszedl nowy pakiet
        if list_of_events[0].type_of_event.value == 0:
            # warunek aby nie wygenerowac wiecej pakietow niz chcemy dla symulacji
            if packetsCounter <= number_of_packets_for_simulation:
                # planujemy przyjscie kolejnego pakietu
                time_next_packet = exp(average_time_between_packets)
                # zdarzenie przyjscia kolejnego pakietu
                list_of_events.append(
                    plan_event_come_next_packet(clock, packetsCounter,
                                                time_next_packet))
                packets.append(
                    PacketMM1(exp(time_of_service), clock + time_next_packet,
                              -1, -1, packetsCounter))
                # dodanie pakietu do listy pakietow
                queue_of_packets.put(packets[packetsCounter - 1])
            # jesli serwer jest wolny - bierzemy pakiet do obslugi
            if not is_server_busy:
                is_server_busy = True
                currently_served_packet = queue_of_packets.get()
                # planujemy zdarzenie zakonczenia obslugi danego pakietu - bo bierzemy go do obslugi
                list_of_events.append(
                    plan_event_finish_service(
                        currently_served_packet.number_of_packet, clock,
                        currently_served_packet.time_of_service))
                packets[currently_served_packet.
                        number_of_packet].time_get_by_server = clock
            packetsCounter += 1
        # przypadek - zkonczono obsluge pakietu
        else:
            number_of_serviced_packets += 1
            currently_served_packet = packets[
                list_of_events[0].number_of_packet]
            packets[currently_served_packet.
                    number_of_packet].time_finish_of_service = clock
            # przypadek w ktorym nie mamy pakietow w kolejce - ustawiamy stan serwera na wolny
            if queue_of_packets.empty():
                is_server_busy = False
            # przypadek w ktorym kolejka nie jest pusta - bierzemy kolejny pakiet do obslugi
            else:
                is_server_busy = True
                currently_served_packet = queue_of_packets.get()
                packets[currently_served_packet.
                        number_of_packet].time_get_by_server = clock
                # planujemy zdarzenie zakonczenia obslugi kolejnego pakietu
                list_of_events.append(
                    plan_event_finish_service(
                        currently_served_packet.number_of_packet,
                        currently_served_packet.time_get_by_server,
                        currently_served_packet.time_of_service))
        # zdejmujemy obsluzone zdarzenie z listy
        list_of_events.pop(0)
        # sortowanie listy zdarzen po czasie
        list_of_events.sort(key=lambda Event: Event.time_of_event)

    return calculate_statistics(number_of_packets_for_simulation, packets,
                                time_of_service, average_time_between_packets,
                                confidence_range)
Пример #18
0
    def calc_nodes(self, degree, prec, verbose=False):
        r"""
        The abscissas and weights for tanh-sinh quadrature of degree
        `m` are given by

        .. math::

            x_k = \tanh(\pi/2 \sinh(t_k))

            w_k = \pi/2 \cosh(t_k) / \cosh(\pi/2 \sinh(t_k))^2

        where `t_k = t_0 + hk` for a step length `h \sim 2^{-m}`. The
        list of nodes is actually infinite, but the weights die off so
        rapidly that only a few are needed.
        """
        nodes = []

        extra = 20
        mp.prec += extra
        eps = ldexp(1, -prec-10)
        pi4 = pi/4

        # For simplicity, we work in steps h = 1/2^n, with the first point
        # offset so that we can reuse the sum from the previous degree

        # We define degree 1 to include the "degree 0" steps, including
        # the point x = 0. (It doesn't work well otherwise; not sure why.)
        t0 = ldexp(1, -degree)
        if degree == 1:
            #nodes.append((mpf(0), pi4))
            #nodes.append((-mpf(0), pi4))
            nodes.append((mpf(0), pi/2))
            h = t0
        else:
            h = t0*2

        # Since h is fixed, we can compute the next exponential
        # by simply multiplying by exp(h)
        expt0 = exp(t0)
        a = pi4 * expt0
        b = pi4 / expt0
        udelta = exp(h)
        urdelta = 1/udelta

        for k in xrange(0, 20*2**degree+1):
            # Reference implementation:
            # t = t0 + k*h
            # x = tanh(pi/2 * sinh(t))
            # w = pi/2 * cosh(t) / cosh(pi/2 * sinh(t))**2

            # Fast implementation. Note that c = exp(pi/2 * sinh(t))
            c = exp(a-b)
            d = 1/c
            co = (c+d)/2
            si = (c-d)/2
            x = si / co
            w = (a+b) / co**2
            diff = abs(x-1)
            if diff <= eps:
                break

            nodes.append((x, w))
            nodes.append((NEG(x), w))

            a *= udelta
            b *= urdelta

            if verbose and k % 300 == 150:
                # Note: the number displayed is rather arbitrary. Should
                # figure out how to print something that looks more like a
                # percentage
                print "Calculating nodes:", nstr(-log(diff, 10) / prec)

        mp.prec -= extra
        return nodes
Пример #19
0
 def exp(self):
     return F.exp(self)
Пример #20
0
    def calc_nodes(self, degree, prec, verbose=False):
        r"""
        The abscissas and weights for tanh-sinh quadrature of degree
        `m` are given by

        .. math::

            x_k = \tanh(\pi/2 \sinh(t_k))

            w_k = \pi/2 \cosh(t_k) / \cosh(\pi/2 \sinh(t_k))^2

        where `t_k = t_0 + hk` for a step length `h \sim 2^{-m}`. The
        list of nodes is actually infinite, but the weights die off so
        rapidly that only a few are needed.
        """
        nodes = []

        extra = 20
        mp.prec += extra
        eps = ldexp(1, -prec-10)
        pi4 = pi/4

        # For simplicity, we work in steps h = 1/2^n, with the first point
        # offset so that we can reuse the sum from the previous degree

        # We define degree 1 to include the "degree 0" steps, including
        # the point x = 0. (It doesn't work well otherwise; not sure why.)
        t0 = ldexp(1, -degree)
        if degree == 1:
            #nodes.append((mpf(0), pi4))
            #nodes.append((-mpf(0), pi4))
            nodes.append((mpf(0), pi/2))
            h = t0
        else:
            h = t0*2

        # Since h is fixed, we can compute the next exponential
        # by simply multiplying by exp(h)
        expt0 = exp(t0)
        a = pi4 * expt0
        b = pi4 / expt0
        udelta = exp(h)
        urdelta = 1/udelta

        for k in xrange(0, 20*2**degree+1):
            # Reference implementation:
            # t = t0 + k*h
            # x = tanh(pi/2 * sinh(t))
            # w = pi/2 * cosh(t) / cosh(pi/2 * sinh(t))**2

            # Fast implementation. Note that c = exp(pi/2 * sinh(t))
            c = exp(a-b)
            d = 1/c
            co = (c+d)/2
            si = (c-d)/2
            x = si / co
            w = (a+b) / co**2
            diff = abs(x-1)
            if diff <= eps:
                break

            nodes.append((x, w))
            nodes.append((NEG(x), w))

            a *= udelta
            b *= urdelta

            if verbose and k % 300 == 150:
                # Note: the number displayed is rather arbitrary. Should
                # figure out how to print something that looks more like a
                # percentage
                print "Calculating nodes:", nstr(-log(diff, 10) / prec)

        mp.prec -= extra
        return nodes
Пример #21
0
    def calc_nodes(cls, prec, level, verbose=False):
        """
        The abscissas and weights for tanh-sinh quadrature are given by

            x[k] = tanh(pi/2 * sinh(t))
            w[k] = pi/2 * cosh(t) / cosh(pi/2 sinh(t))**2

        Here t varies uniformly with k: t0, t0+h, t0+2*h, ...

        The list of nodes is actually infinite, but the weights
        die off so rapidly that only a few are needed.
        """
        nodes = []

        extra = 20
        mp.prec += extra
        eps = ldexp(1, -prec-10)
        pi4 = pi/4

        # For simplicity, we work in steps h = 1/2^n, with the first point
        # offset so that we can reuse the sum from the previous level

        # We define level 1 to include the "level 0" steps, including
        # the point x = 0. (It doesn't work well otherwise; not sure why.)
        t0 = ldexp(1, -level)
        if level == 1:
            nodes.append((mpf(0), pi4))
            h = t0
        else:
            h = t0*2

        # Since h is fixed, we can compute the next exponential
        # by simply multiplying by exp(h)
        expt0 = exp(t0)
        a = pi4 * expt0
        b = pi4 / expt0
        udelta = exp(h)
        urdelta = 1/udelta

        for k in xrange(0, 20*2**level+1):
            # Reference implementation:
            # t = t0 + k*h
            # x = tanh(pi/2 * sinh(t))
            # w = pi/2 * cosh(t) / cosh(pi/2 * sinh(t))**2

            # Fast implementation. Note that c = exp(pi/2 * sinh(t))
            c = exp(a-b)
            d = 1/c
            co = (c+d)/2
            si = (c-d)/2
            x = si / co
            w = (a+b) / co**2
            diff = abs(x-1)
            if diff <= eps:
                break

            nodes.append((x, w))
            a *= udelta
            b *= urdelta

            if verbose and k % 300 == 150:
                # Note: the number displayed is rather arbitrary. Should
                # figure out how to print something that looks more like a
                # percentage
                print "Calculating nodes:", nstr(-log(diff, 10) / prec)

        mp.prec -= extra
        return nodes
Пример #22
0
  (lambda x,c: x*c, '$y/$c', 0),
  (lambda x,c: x/c, '$c*$y', 1),
  (lambda x,c: c/x, '$c/$y', 0),
  (lambda x,c: (x*c)**2, 'sqrt($y)/$c', 0),
  (lambda x,c: (x/c)**2, '$c*sqrt($y)', 1),
  (lambda x,c: (c/x)**2, '$c/sqrt($y)', 0),
  (lambda x,c: c*x**2, 'sqrt($y)/sqrt($c)', 1),
  (lambda x,c: x**2/c, 'sqrt($c)*sqrt($y)', 1),
  (lambda x,c: c/x**2, 'sqrt($c)/sqrt($y)', 1),
  (lambda x,c: sqrt(x*c), '$y**2/$c', 0),
  (lambda x,c: sqrt(x/c), '$c*$y**2', 1),
  (lambda x,c: sqrt(c/x), '$c/$y**2', 0),
  (lambda x,c: c*sqrt(x), '$y**2/$c**2', 1),
  (lambda x,c: sqrt(x)/c, '$c**2*$y**2', 1),
  (lambda x,c: c/sqrt(x), '$c**2/$y**2', 1),
  (lambda x,c: exp(x*c), 'log($y)/$c', 0),
  (lambda x,c: exp(x/c), '$c*log($y)', 1),
  (lambda x,c: exp(c/x), '$c/log($y)', 0),
  (lambda x,c: c*exp(x), 'log($y/$c)', 1),
  (lambda x,c: exp(x)/c, 'log($c*$y)', 1),
  (lambda x,c: c/exp(x), 'log($c/$y)', 0),
  (lambda x,c: log(x*c), 'exp($y)/$c', 0),
  (lambda x,c: log(x/c), '$c*exp($y)', 1),
  (lambda x,c: log(c/x), '$c/exp($y)', 0),
  (lambda x,c: c*log(x), 'exp($y/$c)', 1),
  (lambda x,c: log(x)/c, 'exp($c*$y)', 1),
  (lambda x,c: c/log(x), 'exp($c/$y)', 0),
]

def identify(x, constants=[], tol=None, maxcoeff=1000, full=False,
    verbose=False):
                possibles.append(values[index][1]) # read possibles from slot 1
                percent.append(values[index][0]) # read ratio from slot 0
                temp.append(values[index][2]) # read temperature from slot 2
            except KeyError:
                pass
        kbT = 1/kb/np.array(temp)
        plt.semilogy(kbT, possibles, "-x", label=index)

        # try to fit
        if len(possibles) > 1:
            try:
                popt = curve_fit(f.exp, kbT, possibles, p0=[10e5, -0.01])
                a = popt[0][0]
                b = popt[0][1]
                minusEnergy = b
                plt.semilogy(kbT, f.exp(kbT, a,b), label="fit {0:.4g}e^{1:.4f}".format(a,b))
                percentMean = np.mean(percent)
                # index is the process, from x to y
                x,y = mkl.getXy(index, len(energies))
                if (verbose):
                    print("/",index, mkl.getXy(index, len(energies)))
                    print(percentMean,energies[x][y],minusEnergy)
                    print(percentMean*(energies[x][y]-minusEnergy))
                sumEnergy += percentMean*(energies[x][y]-minusEnergy)
            except RuntimeError:
                pass

    print("Energy from multiplicities is", sumEnergy)
    plt.legend(loc='upper left', prop={'size':6})
    plt.savefig("aeStudy.png")
Пример #24
0
def mm1_with_crash(seed, lambda_in, max_packets):
    random.seed(seed)
    # sredni czas obslugi pakietu przez serwer
    time_of_service = 0.125
    # sredni odstep pomiedzy pakietami 0.5 - 4
    LAMBDA = lambda_in
    average_time_between_packets = 1 / LAMBDA
    # czy serwer jest zajety
    is_server_busy = True
    # czy serwer ma awarie
    is_server_dead = False
    # sredni czas dzialania serwera = 40
    c_on = 40
    # sredni czas NIE dzialania serwera = 35
    c_off = 35
    event_list = []
    clock = 0
    # licznik pakieto - ktory pakiet obslugujemy
    packetsCounter = 0
    # tablica wszystkich pakietow ktore braly udzial w symulacji
    packets = []
    packets_buffor = []
    # liczba obsluzonych pakietow
    number_of_serviced_packets = 0
    # liczba pakietow ktora chcemy przesymulowac
    number_of_packets_for_simulation = max_packets

    first_packet = Packet(time_of_service=exp(time_of_service),
                          time_of_arrival=exp(average_time_between_packets))
    packets.append(first_packet)
    packets_buffor.append(first_packet)
    # wziecie pierwszego pakietu do obslugi - planowanie zakonczenia obslugi pierwszego pakietu
    packet_end_event = Event(time=exp(time_of_service),
                             obj=first_packet,
                             type='end_packet')
    # zaplanowanie zdarzenia przyjscia drugiego pakietu
    event_list.append(packet_end_event)
    time_next_packet = exp(average_time_between_packets)
    next_packet = Packet(time_of_arrival=time_next_packet,
                         time_of_service=exp(time_of_service))
    event_list.append(
        Event(time=time_next_packet, obj=next_packet, type='new_packet'))
    packets.append(next_packet)
    # zaplanowanie pierwszej awarii
    crash_duration1 = exp(c_off)
    crash = CrashOn(crash_duration1)
    event_list.append(Event(time=exp(c_on), obj=crash, type='crash_on'))
    # sortowanie listy zdarzen po czasie
    event_list.sort(key=lambda Event: Event.time)
    crash_list = []
    packet_delay_list = []
    time_of_service_list = []
    buffer_size_list = []

    packetsCounter += 1

    while number_of_serviced_packets < number_of_packets_for_simulation:
        if number_of_serviced_packets % 10000 == 0:
            # print(f'{100*number_of_serviced_packets/number_of_packets_for_simulation} %')
            pass
        event_list.sort(key=lambda Event: Event.time)
        event = event_list.pop(0)
        clock = event.time
        #print(f'TIME: {clock} EVENT: {event.type}')
        if event.type == 'end_packet':
            number_of_serviced_packets += 1
            curr_p = event.obj
            curr_p.finish_of_service = clock
            # print(f'PROCESSED ARRIVE: {curr_p.time_of_arrival} AT: {curr_p.finish_of_service}')
            #print(f'END PACKET {curr_p.time_of_arrival}')
            if len(packets_buffor) == 0:
                is_server_busy = False
            elif not is_server_dead:
                is_server_busy = True
                curr_p = packets_buffor.pop(0)
                event_list.append(
                    Event(time=clock + curr_p.time_of_service,
                          type='end_packet',
                          obj=curr_p))
        elif event.type == 'new_packet':
            # print('NEW PACKET')
            # obecny pakiet trafia na bufor
            packets_buffor.append(event.obj)
            buffer_size_list.append(len(packets_buffor))
            # nastepny pakiet
            t_delay = exp(average_time_between_packets)
            packet_delay_list.append(t_delay)
            tof_temp = exp(time_of_service)
            time_of_service_list.append(tof_temp)
            next_p = Packet(time_of_arrival=clock + t_delay,
                            time_of_service=tof_temp)
            event_list.append(
                Event(time=next_p.time_of_arrival,
                      obj=next_p,
                      type='new_packet'))
            packets.append(next_p)
            # jesli wszystko ok to przetwarzamy najstarszy pakiet
            if not is_server_busy and not is_server_dead:
                curr_p = packets_buffor.pop(0)
                event_list.append(
                    Event(time=clock + curr_p.time_of_service,
                          type='end_packet',
                          obj=curr_p))
        elif event.type == 'crash_on':

            is_server_dead = True
            curr_crash = event.obj
            #print(f'CRASH ON {clock} FOR {curr_crash.duration}')
            event_list.append(
                Event(time=clock + curr_crash.duration,
                      type='crash_off',
                      obj=None))
            crash_list.append(curr_crash.duration)
            for a in event_list:
                if a.type == 'end_packet':
                    a.time += curr_crash.duration
        elif event.type == 'crash_off':
            #print(f'CRASH OFF {clock}')
            is_server_dead = False
            crash_duration = exp(c_off)
            curr_crash = CrashOn(crash_duration)
            event_list.append(
                Event(time=exp(c_on) + clock, obj=curr_crash, type='crash_on'))

    sum_time = 0
    sum_processed = 0
    delays_list = []
    #rozbieg
    packets_less = packets[round(len(packets) * 0.1):]
    for p in packets_less:
        if p.finish_of_service != 0:
            sum_time += (p.finish_of_service - p.time_of_arrival)
            delays_list.append((p.finish_of_service - p.time_of_arrival))
            sum_processed += 1
    average = sum_time / sum_processed

    propability_off = c_off / (c_off + c_on)
    propability_on = c_on / (c_off + c_on)

    LAMBDA = 1 / average_time_between_packets
    #u - intensywnosc obslugi klientow - odwrotnosc czasu obslugi klienta
    u = 1 / time_of_service
    # p - srednie obciazenie systemu = LAMBDA/U
    p = LAMBDA / (u * propability_on)
    if p != 1:
        # Sredni czas oczekiwania w systemie - kalkulacje teoretyczne
        teoretical_average_delay = (p + LAMBDA * c_off * propability_off) / (
            LAMBDA * (1 - p))
        return average, teoretical_average_delay, delays_list
    else:
        return average, None, None
Пример #25
0
 def g(t):
     rei = radius*exp(j*t)
     z = x + rei
     return f(z) / rei**n
Пример #26
0
def evalf(expr):
    """
    evalf(expr) attempts to evaluate a SymPy expression to a Float or
    ComplexFloat with an error smaller than 10**(-Float.getdps())
    """

    if isinstance(expr, (Float, ComplexFloat)):
        return expr
    elif isinstance(expr, (int, float)):
        return Float(expr)
    elif isinstance(expr, complex):
        return ComplexFloat(expr)

    expr = Basic.sympify(expr)

    if isinstance(expr, (Rational)):
        y = Float(expr)
    elif isinstance(expr, Real):
        y = Float(str(expr))

    elif expr is I:
        y = ComplexFloat(0,1)

    elif expr is pi:
        y = constants.pi_float()

    elif expr is E:
        y = functions.exp(1)

    elif isinstance(expr, Mul):
        factors = expr[:]
        workprec = Float.getprec() + 1 + len(factors)
        Float.store()
        Float.setprec(workprec)
        y = Float(1)
        for f in factors:
            y *= evalf(f)
        Float.revert()

    elif isinstance(expr, Pow):
        base, expt = expr[:]
        workprec = Float.getprec() + 8 # may need more
        Float.store()
        Float.setprec(workprec)
        base = evalf(base)
        expt = evalf(expt)
        if expt == 0.5:
            y = functions.sqrt(base)
        else:
            y = functions.exp(functions.log(base) * expt)
        Float.revert()

    elif isinstance(expr, Basic.exp):
        Float.store()
        Float.setprec(Float.getprec() + 3)
        #XXX: how is it possible, that this works:
        x = evalf(expr[0])
        #and this too:
        #x = evalf(expr[1])
        #?? (Try to uncomment it and you'll see)
        y = functions.exp(x)
        Float.revert()

    elif isinstance(expr, Add):
        # TODO: this doesn't yet work as it should.
        # We need some way to handle sums whose results are
        # very close to 0, and when necessary, repeat the
        # summation with higher precision
        reqprec = Float.getprec()
        Float.store()
        Float.setprec(10)
        terms = expr[:]
        approxterms = [abs(evalf(x)) for x in terms]
        min_mag = min(x.exp for x in approxterms)
        max_mag = max(x.exp+bitcount(x.man) for x in approxterms)
        Float.setprec(reqprec - 10 + max_mag - min_mag + 1 + len(terms))
        workprec = Float.getdps()
        y = 0
        for t in terms:
            y += evalf(t)
        Float.revert()

    else:
        # print expr, expr.__class__
        raise NotImplementedError

    # print expr, y

    return +y