Esempio n. 1
0
def write_g_im(filename, e, sigma):
    nlines = len(e)
    with open(filename, 'w') as f:
        for iw in range(0, nlines):
            s = '{0:18.8f}{1:18.12f}{2:18.12f}\n'. \
                format(float(im(e[iw])), float(re(sigma[iw])), float(im(sigma[iw])))
            f.write(s)
Esempio n. 2
0
def cutoff(s, b):
    return abs(
        im(
            w(
                mp.findroot(
                    lambda y: diff(lambda x: im(w(x - j * s / 4, s, b)), y, 1),
                    1 / 2,
                    tol=10**(-10)) - j * s / 4, s, b)))
Esempio n. 3
0
def select():
    global lastop, a, listindex, argindex, theFile
    if lastop == 0:
        print(
            'Parse Error: SELECT. came before corresponding EXP. or LOG. at instruction '
            + str(pointer))
        print(greporig(pointer))
        left = val
        middle = a[listindex]
        right = val
        if listindex > 0:
            left = a[listindex - 1]
        if listindex < len(a) - 1:
            right = a[listindex + 1]
        print('Nearby Tape Values: ' + mpmath.nstr(left) + ',' +
              mpmath.nstr(middle) + ',' + mpmath.nstr(right))
        sys.exit()
    elif lastop == 1:
        if a[argindex] != 0 or mpmath.im(
                a[listindex]) != 0 or a[listindex] >= 0:
            try:
                a[argindex] = mpmath.power(a[argindex], a[listindex])
            except OverflowError:
                print(
                    'Number too large to represent. Try increasing precision or moving default tape value closer to 1.'
                )
                print(greporig(pointer))
            a[argindex] = mpmath.chop(a[argindex], tol)
        else:
            a[argindex] = mpmath.mpc('inf')
    else:
        if a[listindex] == 1:
            print('Tried to take a log base one at instruction ' +
                  str(pointer))
            print(greporig(pointer))
            left = val
            middle = a[listindex]
            right = val
            if listindex > 0:
                left = a[listindex - 1]
            if listindex < len(a) - 1:
                right = a[listindex + 1]
            print('Nearby Tape Values: ' + mpmath.nstr(left) + ',' +
                  mpmath.nstr(middle) + ',' + mpmath.nstr(right))
            sys.exit()
        a[argindex] = mpmath.log(a[argindex], a[listindex])
        #patch up nans when arg is infinite, since we usually want zero for the real part then
        if mpmath.isinf(mpmath.im(a[argindex])) and mpmath.isnan(
                mpmath.re(a[argindex])):
            a[argindex] = mpmath.mpc(0, mpmath.im(a[argindex]))
        a[argindex] = mpmath.chop(a[argindex], tol)
    oparg = 0
def lognormal_minmax_log(kmin, kmax, mu, sigma):
    '''returns the sum( 1/k*exp(-0.5*((lnk - mu)/sigma)^2),{k,kmin,kmax}  ) with kmax=None for infty
    '''
    #     print kmin,kmax,mu,sigma
    mpm.mp.dps = 15
    if kmax == None:
        x = mpm.log(
            mpm.sumem(
                lambda k: 1.0 / (k - kmin + 1.0) * mpm.exp(-0.5 * (mpm.log(
                    (k - kmin + 1.0)) - mu) * (mpm.log(
                        (k - kmin + 1.0)) - mu) / sigma / sigma),
                [kmin, mpm.inf]))
        if mpm.im(x) != 0:
            logS = float(mpm.fabs(x))
        else:
            logS = float(x)
    else:
        logS = (float(
            mpm.log(
                mpm.sumem(
                    lambda k: 1.0 / (k - kmin + 1.0) * mpm.exp(-0.5 * (mpm.log(
                        (k - kmin + 1.0)) - mu) * (mpm.log(
                            (k - kmin + 1.0)) - mu) / sigma / sigma),
                    [kmin, kmax]))))

    return logS
Esempio n. 5
0
def is_imag_negative(w, f):
    analitic = True
    for x in f:
        if im(x) > 0.0:
            analitic = False
            break
    return analitic
Esempio n. 6
0
def loop():
    global a, listindex, pointer, loopdict
    realpart = mpmath.re(a[listindex])
    impart = mpmath.im(a[listindex])
    if mpmath.workdps(mpmath.mp.dps * 3 / 4)(
            mpmath.chop)(realpart - impart) > 0:
        pointer = loopdict[pointer]
Esempio n. 7
0
def real_int( n ):
    if im( n ) != 0:
        raise ValueError( 'real argument expected ({})'.format( n ) )

    if n != floor( n ):
        raise ValueError( 'integer argument expected ({})'.format( n ) )

    return int( n )
Esempio n. 8
0
def real( n ):
    if isinstance( n, ( list, RPNGenerator ) ):
        return n

    if im( n ) != 0:
        raise ValueError( 'real argument expected ({})'.format( n ) )

    return n
Esempio n. 9
0
def end():
    global a, listindex, pointer, loopdict
    realpart = mpmath.re(a[listindex])
    impart = mpmath.im(a[listindex])
    if mpmath.workdps(mpmath.mp.dps * 3 / 4)(
            mpmath.chop)(realpart - impart) <= 0:
        pointer = next(key for key, value in loopdict.items()
                       if value == pointer)
Esempio n. 10
0
def real( n ):
    '''Validates that a value is real and throws an error if it isn't.'''
    if isinstance( n, ( list, RPNGenerator ) ):
        return n

    if im( n ) != 0:
        raise ValueError( 'real argument expected ({})'.format( n ) )

    return n
Esempio n. 11
0
 def generate(c, num_iterations=200):
     orbit_re = []
     orbit_im = []
     z = mpmath.mpc(real='0.0', imag='0.0')
     for _ in range(num_iterations):
         z = mpmath.fadd(mpmath.fmul(z, z), c)
         orbit_re.append(mpmath.nstr(mpmath.re(z)))
         orbit_im.append(mpmath.nstr(mpmath.im(z)))
     return [orbit_re, orbit_im]
Esempio n. 12
0
def real_int( n ):
    '''Validates that a value is a real integer and throws an error if it
    isn't.'''
    if im( n ) != 0:
        raise ValueError( 'real argument expected ({})'.format( n ) )

    if n != floor( n ):
        raise ValueError( 'integer argument expected ({})'.format( n ) )

    return int( n )
Esempio n. 13
0
def formatOutput( output ):
    # filter out text strings
    for c in output:
        if c in '+-.':
            continue

        # anything with embedded whitespace is a string
        if c in string.whitespace or c in string.punctuation:
            return output

    #print( )
    #print( 'formatOutput 1:', output )

    # override settings with temporary settings if needed
    # if g.tempCommaMode:
    #     comma = True
    # else:
    #     comma = g.comma

    # output settings, which may be overrided by temp settings
    outputRadix = g.outputRadix
    integerGrouping = g.integerGrouping
    leadingZero = g.leadingZero

    if g.tempHexMode:
        integerGrouping = 4
        leadingZero = True
        outputRadix = 16

    if g.tempLeadingZeroMode:
        leadingZero = True

    if g.tempOctalMode:
        integerGrouping = 3
        leadingZero = True
        outputRadix = 8

    mpOutput = mpmathify( output )

    imaginary = im( mpOutput )
    real = re( mpOutput )

    result, negative = formatNumber( real, outputRadix, leadingZero, integerGrouping )

    if negative:
        result = '-' + result

    if imaginary != 0:
        strImaginary, negativeImaginary = formatNumber( imaginary, outputRadix, leadingZero )
        result = '( ' + result + ( ' - ' if negativeImaginary else ' + ' ) + strImaginary + 'j )'

    #print( 'formatOutput 2:', output )
    #print( )

    return result
Esempio n. 14
0
def formatOutput( output ):
    # filter out text strings
    for c in output:
        if c in '+-.':
            continue

        # anything with embedded whitespace is a string
        if c in string.whitespace or c in string.punctuation:
            return output

    # output settings, which may be overrided by temp settings
    outputRadix = g.outputRadix
    integerGrouping = g.integerGrouping
    leadingZero = g.leadingZero
    integerDelimiter = g.integerDelimiter

    # override settings with temporary settings if needed
    if g.tempCommaMode:
        integerGrouping = 3     # override whatever was set on the command-line
        leadingZero = False     # this one, too
        integerDelimiter = ','

    if g.tempHexMode:
        integerGrouping = 4
        leadingZero = True
        outputRadix = 16

    if g.tempLeadingZeroMode:
        leadingZero = True

    if g.tempOctalMode:
        integerGrouping = 3
        leadingZero = True
        outputRadix = 8

    mpOutput = mpmathify( output )

    imaginary = im( mpOutput )
    real = re( mpOutput )

    result, negative = formatNumber( real, outputRadix, leadingZero, integerGrouping,
                                     integerDelimiter, g.decimalDelimiter )

    if negative:
        result = '-' + result

    if imaginary != 0:
        strImaginary, negativeImaginary = \
            formatNumber( imaginary, outputRadix, leadingZero, integerGrouping, integerDelimiter, g.DecimalDelimiter )
        result = '( ' + result + ( ' - ' if negativeImaginary else ' + ' ) + strImaginary + 'j )'

    #print( 'formatOutput 2:', output )
    #print( )

    return result
def root_find_mp(func, x_loc, y_loc, step_size, points,
                 solver='halley', wordy=True, tol=1e-15):

    jump_limit = 0.1
    maxsteps = 200

    try:
        grad = ((points[-1, 1] - points[-2, 1]) +
                (points[-1, 1] - 2*points[-2, 1] + points[-3, 1])) * \
                np.abs(step_size/(points[-1, 0] - points[-2, 0]))
        root_mp = mp.findroot(func, points[-1, 1] + grad, solver, tol)
        root = float(mp.re(root_mp)) + 1j * float(mp.im(root_mp))
        if np.abs(root-points[-1, 1]) < 0.1:
            points = np.vstack([points, [x_loc, root]])
        else:
            raise ValueError('Jump of {:.5f} at x = {:.5f}, y = {:.5f}'.format(
                np.abs(root-points[-1, 1]), points[-1, 0], points[-1, 1]+grad))
        x_error = None

    except IndexError:
        if points.all() == 0:
            root_mp = mp.findroot(func, y_loc, solver, tol, maxsteps)
            root = float(mp.re(root_mp)) + 1j*float(mp.im(root_mp))
            points[0,] = x_loc, root
        elif points.shape == (1, 2):
            root_mp = mp.findroot(func, points[-1, 1], solver, tol, maxsteps)
            root = float(mp.re(root_mp)) + 1j*float(mp.im(root_mp))
            points = np.vstack([points, [x_loc, root]])
        elif points.shape == (2, 2):
            grad = (points[-1, 1] - points[-2, 1]) *\
                    np.abs(step_size/(points[-1, 0] - points[-2, 0]))
            root_mp = mp.findroot(func, points[-1, 1] + grad, solver, tol, maxsteps)
            root = float(mp.re(root_mp)) + 1j*float(mp.im(root_mp))
            if np.abs(root - points[-1, 1]) < jump_limit:
                points = np.vstack([points, [x_loc, root]])
            else:
                raise ValueError('Jump of {:.5f} at x = {:.5f}, y = {:.5f}'.format(
                    np.abs(root-points[-1, 1]), points[-1, 0], points[-1, 1]+grad))
        x_error = None

    return points, np.abs(step_size), x_error, x_loc
Esempio n. 16
0
def isKthPower(n, k):
    if not isint(k, gaussian=True):
        raise ValueError('integer argument expected')

    if k == 1:
        return 1

    if im(n):
        # I'm not sure why this is necessary...
        if re(n) == 0:
            return isKthPower(im(n), k)

        # We're looking for a Gaussian integer among any of the roots.
        for i in [autoprec(root)(n, k, i) for i in arange(k)]:
            if isint(i, gaussian=True):
                return 1

        return 0

    rootN = autoprec(root)(n, k)
    return 1 if isint(rootN, gaussian=True) else 0
Esempio n. 17
0
  def __call__(self, r, z=1e-10):
    """
    Returns the intensity distribution near the focal spot.
    """
    u = self.normalized_distance(z)
    v = self.normalized_radius(r)

    α = self.alpha()
    β = self.beta(u, v)

    I = 2 * α**2 * mp.exp(-α) / (mp.cosh(α) - 1) / (u**2 + 4 * α**2)

    if mp.sqrt(u**2 + 4 * α**2) < v:
      U1 = lommelU(u, v, 1)
      U2 = lommelU(u, v, 2)

      U1s = mp.re(U1)
      U1c = mp.im(U1)
      U2s = mp.re(U2)
      U2c = mp.im(U2)

      return I * ((U1c + U2s)**2 + (U1s - U2c)**2)

    if mp.sqrt(u**2 + 4 * α**2) > v:
      V0 = lommelV(u, v, 0)
      V1 = lommelV(u, v, 1)

      V0s = mp.re(V0)
      V0c = mp.im(V0)
      V1s = mp.re(V1)
      V1c = mp.im(V1)

      exp = mp.exp(α * (1 - β))
      cos = mp.cos(u * (1 + β) / 2)
      sin = mp.sin(u * (1 + β) / 2)

      return I * ((V0c - V1s - exp * cos)**2 + (V0s + V1c + exp * sin)**2)

    raise ValueError('invalid coordinates')
Esempio n. 18
0
def linear_equilibrium(mu1, mu2, complex_guess_1, complex_guess_2):
    """The linear equilibrium function finds a two dimensional vector solution. The solutions we are looking for are real.
    Many solutions that can be found are complex and because of the numerical methods in which python finds these solutions
    we have decided to use the mpmath modules. This method of finding the solution for our non linear heat flux uses
    the muller method of numerical calculation. For more information on mpmath root finding:
    http://mpmath.org/doc/1.1.0/calculus/optimization.html"""
    import numpy as np
    import sympy
    import mpmath
    #List of Constants
    I0 = 1367.0  #Solar constant W/m^2
    a = 2.8  #Unitless parameter needed for linear albedo feedback relationships more info in Budyko 1969
    b = .009  #Another parameter needed for linear feedback relationship more info in Budyko 1969
    sig = 5.67 * 10**-8  #Stephan boltzmann constant m^2 kg s^-2 K^-1
    e = .64  #Emmisivity of earth
    A = 2.7  #Heat flux parameter for linear heat forcing
    solution_array = []
    for x in mu1:
        for y in mu2:
            #Below we find the two-dimensional vector solutions in form of [polar_solution, tropical_solution]
            f = [
                lambda T1, T2:
                (.156 * x * I0 * (1 - a) + .156 * x * I0 * b * T1 - e * sig *
                 (T1**4) + (A * (T2 - T1))), lambda T1, T2:
                (.288 * y * I0 * (1 - a) + .288 * y * I0 * b * T2 - e * sig *
                 (T2**4) + (A * (T1 - T2)))
            ]
            solution = np.array(
                mpmath.findroot(f, ([complex_guess_1, complex_guess_2]),
                                solver='muller',
                                verify=False))
            if abs(mpmath.im(solution[0])) > 1e-10:
                solution[0] = np.nan
            if abs(mpmath.im(solution[1])) > 1e-10:
                solution[1] = np.nan
            solution_array.append(
                [mpmath.re(solution[0]),
                 mpmath.re(solution[1]), x, y])
    return (solution_array)
Esempio n. 19
0
    def propagate(self, T):
        """
    Returns new Gaussian beam with updated parameters from transfer matrix.
    """
        z = self.origin
        k = self.wavenumber
        q = self.parameter
        q = (T[0, 0] * q + T[0, 1]) / (T[1, 0] * q + T[1, 1])

        z = mp.re(q) + z
        w = mp.sqrt(2 * mp.im(q) / k)

        return Gaussian(waist=w, origin=z, wavelength=self.wavelength)
Esempio n. 20
0
def eigen(M,dic,order):
    M1 = M.xreplace(dic)
    with mp.workdps(int(mp.mp.dps*2)):
        M1 = M1.evalf(mp.mp.dps)
        det =(M1).det(method = 'berkowitz')
        detp = Poly(det,kz)
        co = detp.all_coeffs()
        co = [mp.mpc(str(re(k)),str(im(k))) for k in co]

        maxsteps = 3000
        extraprec = 500
        ok =0
        while ok == 0:
            try:
                sol,err = mp.polyroots(co,maxsteps =maxsteps,extraprec = extraprec,error =True)
                sol = np.array(sol)
                print("Error on polyroots =", err)
                ok=1
            except:
                maxsteps = int(maxsteps*2)
                extraprec = int(extraprec*1.5)
                print("Poly roots fail precision increased: ",maxsteps,extraprec)
    te = np.array([mp.fabs(m) < mp.mpf(10**mp.mp.dps) for m in sol])
    solr = sol[te]

    if Bound_nb == 1:
        solr = solr[[mp.im(m) < 0 for m in solr]]
    eigen1 = np.empty((len(solr),np.shape(M1)[0]),dtype = object)

    with mp.workdps(int(mp.mp.dps*2)):
        for i in range(len(solr)):
            M2 = mpmathM(M1.xreplace({kz:solr[i]}))
            eigen1[i] = null_space(M2)
        solr1 = solr

        div = [mp.fabs(x) for x in (order*kxl.xreplace(dic)*eigen1[:,4]+order*kyl.xreplace(dic)*eigen1[:,5]+solr1*eigen1[:,6])]
        testdivB = [mp.almosteq(x,0,10**(-(mp.mp.dps/2))) for x in div]
        eigen1 =eigen1[testdivB]
        solr1 = solr1[testdivB]
        if len(solr1) == 3:
            print("Inviscid semi infinite domain")
        elif len(solr1) == 6:
            print("Inviscid 2 boundaries")
        elif len(solr1) == 5:
            print("Viscous semi infinite domain")
        elif len(solr1) == 10:
            print("Viscous 2 boundaries")
        else:
            print("number of solution inconsistent,",len(solr1))

    return(solr1,eigen1,M1)
Esempio n. 21
0
def isKthPower( n, k ):
    if not isint( k, gaussian=True ) and isint( k ):
        raise ValueError( 'integer arguments expected' )

    if k == 1:
        return 1
    elif k < 1:
        raise ValueError( 'a positive power k is expected' )

    if im( n ):
        # I'm not sure why this is necessary...
        if re( n ) == 0:
            return isKthPower( im( n ), k )

        # We're looking for a Gaussian integer among any of the roots.
        for i in [ autoprec( root )( n, k, i ) for i in arange( k ) ]:
            if isint( i, gaussian=True ):
                return 1

        return 0
    else:
        rootN = autoprec( root )( n, k )
        return 1 if isint( rootN, gaussian=True ) else 0
Esempio n. 22
0
def non_linear_albedo_solver(mu1, mu2, guess_1, guess_2):
    """This solution is a modeling of a situation where solar intensity is decreased sufficiently until the earth
    produces enough ice that the earth will reflect sufficient radiation to keep the earth in an ice age.
    Ice ages are still subject to a heat flux, the below function finds the equilibria for the ice ages for
    made with a non-linear heat flux."""
    import numpy as np
    import sympy
    import mpmath
    #List of Constants
    I0 = 1367.0  #Solar constant W/m^2
    a = 2.8  #Unitless parameter needed for linear albedo feedback relationships more info in Budyko 1969
    b = .009  #Another parameter needed for linear feedback relationship more info in Budyko 1969
    sig = 5.67 * 10**-8  #Stephan boltzmann constant m^2 kg s^-2 K^-1
    e = .64  #Emmisivity of earth
    A = 600  #Heat flux parameter for non-linear heat forcing
    solution_array = []
    for x in mu1:
        for y in mu2:
            #Below we find the two-dimensional vector solutions in form of [polar_solution, tropical_solution]
            f = [
                lambda T1, T2: (.156 * x * I0 * (1 - .75) - e * sig * (T1**4) +
                                (A / (T2 - T1))), lambda T1, T2:
                (.288 * y * I0 * (1 - .75) - e * sig * (T2**4) + (A /
                                                                  (T1 - T2)))
            ]
            solution = np.array(
                mpmath.findroot(f, ([guess_1, guess_2]),
                                solver='muller',
                                verify=False))
            if abs(mpmath.im(solution[0])) > 1e-10:
                solution[0] = np.nan
            if abs(mpmath.im(solution[1])) > 1e-10:
                solution[1] = np.nan
            solution_array.append(
                [mpmath.re(solution[0]),
                 mpmath.re(solution[1]), x, y])
    return (solution_array)
def point_finder_mp(func, x_range, y_range, args=None, solver='muller'):
    points = []
    for x_loc in x_range:
        arguments = [x_loc if i is None else i for i in list(args)]
        flip_func = partial(lambda *args: func(*args[::-1]), *arguments[::-1])
        for y_loc in y_range:
            if solver == 'muller':
                y_loc = [y_loc - 1e-10, y_loc, y_loc + 1e-10]
            try:
                root = mp.findroot(flip_func, y_loc, solver, tol=1e-20)
                root = float(mp.re(root)) + float(mp.im(root)) * 1j
                if not np.isclose(root, points, atol=1e-6).any():
                    points.append([x_loc, root])
            except (RuntimeError, ZeroDivisionError, ValueError):
                pass
    return np.array(points)
Esempio n. 24
0
    def validateReal(self, argument):
        if not isinstance(argument, (complex, mpc, mpf, int, float)):
            raise ValueError(
                f'\'type\' { type( argument ) } found, numeric value expected')

        if im(argument) != 0:
            raise ValueError('real argument expected ({})'.format(argument))

        if self.min is not None and argument < self.min:
            raise ValueError(
                f'argument value is { argument }, minimum valid value is { self.min }.'
            )

        if self.max is not None and argument > self.max:
            raise ValueError(
                f'argument value is { argument }, maximum valid value is { self.max }.'
            )

        return argument
Esempio n. 25
0
def weibull_minmax_log(kmin, kmax, gamma, b):
    '''returns the sum( k^(gamma-1)*exp(-b*(k)^gamma),{k,kmin,kmax}  ) with kmax=None for infty
    '''
    gamma = float(gamma)
    b = float(b)
    mpm.mp.dps = 15
    if kmax == None:
        x = mpm.sumem(lambda k: k**(gamma - 1.0) * mpm.exp(-b * k**gamma),
                      [kmin, mpm.inf])
        if mpm.im(x) != 0:
            logS = float(mpm.fabs(x))
        else:
            logS = float(x)
    else:
        logS = float(
            mpm.log(
                mpm.sumem(lambda k: k**(gamma - 1.0) * mpm.exp(-b * k**gamma),
                          [kmin, kmax])))
    return logS
Esempio n. 26
0
def drawbox():
    global a, listindex, centerx, centery, pixdict, z, red, green, blue, canv, verbose
    if verbose:
        print('Outputting: ' + mpmath.nstr(mpmath.chop(a[listindex])))
    if mpmath.isnan(a[listindex]) or mpmath.isinf(a[listindex]):
        return
    try:
        x = int(mpmath.nint(mpmath.re(a[listindex]))) + centerx
        y = int(mpmath.nint(mpmath.im(a[listindex]))) + centery
        if (x, y) in pixdict:
            canv.delete(pixdict[(x, y)])
            del pixdict[(x, y)]
        pixdict[(x, y)] = canv.create_rectangle(x * z - z + 1,
                                                y * z - z + 1,
                                                x * z + 1,
                                                y * z + 1,
                                                fill=rgb(red, green, blue),
                                                width=0)
    except OverflowError:
        #the number is so huge it's not going to be displayed anyway, so just suppress the error and move on
        pass
Esempio n. 27
0
    def validateInt(self, argument):
        if not isinstance(argument, (complex, mpc, mpf, int, float)):
            raise ValueError(
                f'\'type\' { type( argument ) } found, integer value expected')

        if im(argument) != 0:
            raise ValueError('real argument expected ({})'.format(argument))

        if argument != floor(argument):
            raise ValueError('integer argument expected ({})'.format(argument))

        if self.min is not None and argument < self.min:
            raise ValueError(
                f'argument value is { int( argument ) }, but the minimum valid value is { int( self.min ) }.'
            )

        if self.max is not None and argument > self.max:
            raise ValueError(
                f'argument value is { int( argument ) }, but the maximum valid value is { int( self.max ) }.'
            )

        return argument
Esempio n. 28
0
    def test_takagi_fact(self):
        N_REPEAT = 1000
        N_DIM_UPPER = 2
        for _ in range(N_REPEAT):
            for n in range(2, N_DIM_UPPER + 1):
                ar = mpmath.randmatrix(n)
                ai = mpmath.randmatrix(n)
                a = ar + 1j * ai
                A = a + a.T

                vs, Q = takagi_fact.takagi_fact(A)

                diag = mpmath.diag(vs)
                qtaq = Q.T * A * Q

                unit = mpmath.diag([1 for _ in range(n)])
                qdaq = Q.H * Q

                for i, j in itertools.product(range(n), repeat=2):
                    self.assertAlmostEqual(mpmath.im(diag[i, j]), 0)
                    self.assertAlmostEqual(diag[i, j], qtaq[i, j])
                    self.assertAlmostEqual(unit[i, j], qdaq[i, j])
Esempio n. 29
0
    def get_godoghraph(self):
        w_den = tf(self.w.den[0][0], [1])

        print(w_den)

        array = []
        x = []
        y = []

        j = sqrt(-1)
        length_of_array = 2
        for q in arange(0, length_of_array, 0.01):
            array.append(w_den(q * j))

        for i in array:
            x.append(re(i))
            y.append(im(i))

        plt.plot(x, y, "r")
        plt.title('Godograph')
        plt.ylabel('jY')
        plt.xlabel('X')
        plt.grid(True)
        plt.show()
Esempio n. 30
0
def F2_cubic(hstar,kappa):
    '''
    F2 function corresponding to a cubic viscosity profile (Nieuwstadt 1983)

    Parameters
    ----------
    hstar: float
        Non-dimensional boundary-layer height
        hstar = h*fc/utau
    kappa: float
        Von Karman constant

    Returns
    -------
    F2: float
        Value of F2 function
    '''
    C = hstar/kappa
    alpha = 0.5+0.5*np.sqrt(1+4j*C)
    F2 = np.zeros((1),dtype=np.float64)
    F2[0] = 1./kappa*(mpmath.im( mpmath.digamma(alpha+1)+
                                 mpmath.digamma(alpha-1)-
                                 2*mpmath.digamma(1.0) ) )
    return np.asscalar(F2)
Esempio n. 31
0
    def nCDF(self, x):

        if np.isscalar(x):
            x = np.array([x])

        p = np.zeros(x.size)

        for i, xx in enumerate(x):

            gil_pelaez = lambda t: mp.im(
                self.char_fn(t) * mp.exp(-1j * t * xx)) / t

            cutoff = self.find_cutoff(1e-30)
            # Instead of finding roots, break up quadrature into degrees proportional to the
            # expected number of oscillations of e^(i xx t) within t = [0, cutoff]
            nosc = cutoff / (1 / max(10, np.abs(xx - self.mean())))

            I = mp.quad(gil_pelaez, np.linspace(0, cutoff, nosc), maxdegree=10)
            p[i] = float(1 / 2 - 1 / mp.pi * I)

        if p.size == 1:
            return p[0]
        else:
            return p
Esempio n. 32
0
def handleOutput(valueList, indent=0, file=sys.stdout):
    '''
    Once the evaluation of terms is complete, the results need to be
    translated into output.

    If the result is a list or a generator, special formatting turns those
    into text output.  Date-time values and measurements also require special
    formatting.

    Setting file to an io.StringIO objects allows for 'printing' to a string,
    which is used by makeHelp.py to generate actual rpn output for the examples.
    '''
    if valueList is None:
        return file

    indentString = ' ' * indent

    if len(valueList) != 1:
        if g.checkForSingleResults:
            print('valueList', valueList)
            raise ValueError('unexpected multiple results!')

        valueList = [valueList]

    if isinstance(valueList[0], RPNFunction):
        print(indentString +
              'rpn:  unexpected end of input in function definition',
              file=file)
    else:
        mp.pretty = True
        result = valueList.pop()

        if result is nan:
            return file

        if g.comma:
            g.integerGrouping = 3  # override whatever was set on the command-line
            g.leadingZero = False  # this one, too
            g.integerDelimiter = ','
        else:
            g.integerDelimiter = ' '

        if isinstance(result, RPNGenerator):
            formatListOutput(result.getGenerator(), indent=indent, file=file)
        elif isinstance(result, list):
            formatListOutput(result, indent=indent, file=file)
        else:
            # single result
            if isinstance(result, RPNDateTime):
                outputString = formatDateTime(result)
            elif isinstance(result, str):
                result = checkForVariable(result)
                outputString = result
            else:
                # output the answer with all the extras according to command-line arguments
                # handle the units if we are displaying a measurement
                if isinstance(result, RPNMeasurement):
                    outputString = formatOutput(
                        nstr(result.value,
                             g.outputAccuracy,
                             min_fixed=-g.maximumFixed - 1))
                    outputString += ' ' + formatUnits(result)
                # handle a complex output (mpmath type: mpc)
                elif isinstance(result, mpc):
                    #print( 'result', result, type( result ) )
                    #print( 'im', im( result ), type( im( result ) ) )
                    #print( 're', re( result ), type( re( result ) ) )

                    if im(result) > 0:
                        outputString = '(' + formatOutput( nstr( mpmathify( re( result ) ),
                                                                 g.outputAccuracy, min_fixed=-g.maximumFixed - 1 ) ) + \
                                       ' + ' + formatOutput( nstr( mpmathify( im( result ) ),
                                                                   g.outputAccuracy,
                                                                   min_fixed=-g.maximumFixed - 1 ) ) + 'j)'
                    elif im(result) < 0:
                        outputString = '(' + formatOutput( nstr( mpmathify( re( result ) ),
                                                                 g.outputAccuracy, min_fixed=-g.maximumFixed - 1 ) ) + \
                                       ' - ' + formatOutput( nstr( fneg( mpmathify( im( result ) ) ),
                                                                   g.outputAccuracy,
                                                                   min_fixed=-g.maximumFixed - 1 ) ) + 'i)'
                    else:
                        outputString = formatOutput(
                            nstr(re(result),
                                 g.outputAccuracy,
                                 min_fixed=-g.maximumFixed - 1))
                # otherwise, it's a plain old mpf
                else:
                    outputString = formatOutput(
                        nstr(result,
                             g.outputAccuracy,
                             min_fixed=-g.maximumFixed - 1))

            print(indentString + outputString, file=file)

        # handle --identify
        if g.identify:
            handleIdentify(result, file)

        saveResult(result)

    if g.timer or g.tempTimerMode:
        print('\n' + indentString + '{:.3f} seconds'.format(
            (time_ns() - g.startTime) / 1_000_000_000),
              file=file)

    return file
Esempio n. 33
0
def color():
    global red, green, blue
    red = int(mpmath.fdiv(mpmath.re(a[listindex]), 256))
    green = int(mpmath.fmod(mpmath.re(a[listindex]), 256))
    blue = int(mpmath.fmod(mpmath.im(a[listindex]), 256))
Esempio n. 34
0
def handleOutput( valueList, indent=0, file=sys.stdout ):
    '''
    Once the evaluation of terms is complete, the results need to be
    translated into output.

    If the result is a list or a generator, special formatting turns those
    into text output.  Date-time values and measurements also require special
    formatting.

    Setting file to an io.StringIO objects allows for 'printing' to a string,
    which is used by makeHelp.py to generate actual rpn output for the examples.
    '''
    if valueList is None:
        return file

    indentString = ' ' * indent

    if len( valueList ) != 1:
        if g.checkForSingleResults:
            print( 'valueList', valueList )
            raise ValueError( 'unexpected multiple results!' )

        valueList = [ valueList ]

    if isinstance( valueList[ 0 ], RPNFunction ):
        print( indentString + 'rpn:  unexpected end of input in function definition', file=file )
    else:
        mp.pretty = True
        result = valueList.pop( )

        if result is nan:
            return file

        if g.comma:
            g.integerGrouping = 3     # override whatever was set on the command-line
            g.leadingZero = False     # this one, too
            g.integerDelimiter = ','
        else:
            g.integerDelimiter = ' '

        if isinstance( result, RPNGenerator ):
            formatListOutput( result.getGenerator( ), indent=indent, file=file )
        elif isinstance( result, list ):
            formatListOutput( result, indent=indent, file=file )
        else:
            # single result
            if isinstance( result, RPNDateTime ):
                outputString = formatDateTime( result )
            elif isinstance( result, str ):
                result = checkForVariable( result )
                outputString = result
            else:
                # output the answer with all the extras according to command-line arguments
                # handle the units if we are displaying a measurement
                if isinstance( result, RPNMeasurement ):
                    outputString = formatOutput( nstr( result.value, g.outputAccuracy, min_fixed=-g.maximumFixed - 1 ) )
                    outputString += ' ' + formatUnits( result )
                # handle a complex output (mpmath type: mpc)
                elif isinstance( result, mpc ):
                    #print( 'result', result, type( result ) )
                    #print( 'im', im( result ), type( im( result ) ) )
                    #print( 're', re( result ), type( re( result ) ) )
                    imaginary = im( result )

                    if im( result ) > 0:
                        outputString = '(' + formatOutput( nstr( mpmathify( re( result ) ), g.outputAccuracy, min_fixed=-g.maximumFixed - 1 ) ) + \
                                       ' + ' + formatOutput( nstr( mpmathify( im( result ) ), g.outputAccuracy, min_fixed=-g.maximumFixed - 1 ) ) + 'j)'
                    elif im( result ) < 0:
                        outputString = '(' + formatOutput( nstr( mpmathify( re( result ) ), g.outputAccuracy, min_fixed=-g.maximumFixed - 1 ) ) + \
                                       ' - ' + formatOutput( nstr( fneg( mpmathify( im( result ) ) ), g.outputAccuracy, min_fixed=-g.maximumFixed - 1 ) ) + 'i)'
                    else:
                        outputString = formatOutput( nstr( re( result ), g.outputAccuracy, min_fixed=-g.maximumFixed - 1 ) )
                # otherwise, it's a plain old mpf
                else:
                    outputString = formatOutput( nstr( result, g.outputAccuracy, min_fixed=-g.maximumFixed - 1 ) )

            print( indentString + outputString, file=file )

            # handle --identify
            if g.identify:
                handleIdentify( result, file )

        saveResult( result )

    if g.timer or g.tempTimerMode:
        print( '\n' + indentString + '{:.3f} seconds'.format( time.process_time( ) - g.startTime ), file=file )
Esempio n. 35
0
def plot_process(child_conn, initial_value, dps, f_string,
                 stop_iteration_near):
    #Allows plot interactivity while main thread keeps chugging away on function iteration
    points = [initial_value]
    num_point_display_history = [float('inf')]

    # Top level definitions
    baseline_figsize = (20, 10)
    main_plot_left = 0.04
    main_plot_right = 0.99
    main_plot_top = 0.95
    main_plot_bottom = 0.06
    plain_descriptor = f_string + ', beginning from ' + str(
        initial_value) + ', ' + str(dps) + ' decimal places precision'
    iteration_prefix = 'Iteration {0} of '
    iteration_postfix = ', iteration {0}'
    point_value_string = lambda point: '\n' + mpmath.nstr(point, 30)
    xlabel_1 = 'real value'
    ylabel_1 = 'imaginary value'
    xlabel_0 = 'iterative imaginary values'
    ylabel_0 = 'iteration'
    xlabel_3 = 'iteration'
    ylabel_3 = 'iterative real values'
    label_2 = 'display\nhistory\n(#points)'
    title = iteration_prefix.format(0) + plain_descriptor + point_value_string(
        initial_value)
    grid_spec_width_ratios = [3, 50]
    grid_spec_height_ratios = [30, 4]

    # initialize live displayed plot
    # real monitor = 12.75 in tall x 21.75+1/8 in wide, 1080p, 100dpi plot display seems ok.
    fig = plt.figure(dpi=100, figsize=baseline_figsize)
    gs = matplotlib.gridspec.GridSpec(2,
                                      2,
                                      width_ratios=grid_spec_width_ratios,
                                      height_ratios=grid_spec_height_ratios)
    gs.update(left=main_plot_left,
              right=main_plot_right,
              top=main_plot_top,
              bottom=main_plot_bottom)

    ax_1 = plt.subplot(gs[1])
    x, y = list(
        zip(*[(float(mpmath.re(point)), float(mpmath.im(point)))
              for point in points]))
    plot_1, = plt.plot(x,
                       y,
                       zorder=2,
                       markevery=[-1],
                       marker='o',
                       markersize=5,
                       markerfacecolor='red',
                       markeredgecolor='red')
    plt.axis('scaled')  # force equal axes even on plot window resize
    plt.xlabel(xlabel_1)
    plt.ylabel(ylabel_1)
    plt.title(title)

    ax_0 = plt.subplot(gs[0])
    plot_0, = plt.plot(y, list(range(len(y))), zorder=2)
    plt.xlabel(xlabel_0)
    plt.ylabel(ylabel_0)

    ax_3 = plt.subplot(gs[3])
    plot_3, = plt.plot(list(range(len(x))), x, zorder=2)
    plt.xlabel(xlabel_3)
    plt.ylabel(ylabel_3)

    ax_2 = plt.subplot(gs[2])
    num_point_display_history_box = matplotlib.widgets.TextBox(ax_2,
                                                               label_2,
                                                               initial='inf')

    def num_point_display_history_box_submit(text):
        if text == 'inf':
            num_point_display_history[0] = float('inf')
            num_point_display_history_box_save.set_val(text)
        else:
            try:
                parsed_text = int(text)
                assert parsed_text > 0
                num_point_display_history[0] = parsed_text
                num_point_display_history_box_save.set_val(text)
            except:
                print('unacceptable num_point_display_history entry "' + text +
                      '"')

    num_point_display_history_box.on_submit(
        num_point_display_history_box_submit)

    plt.show(block=False)

    # initialize saved plot
    fig_save = plt.figure(dpi=100, figsize=baseline_figsize)
    gs_save = matplotlib.gridspec.GridSpec(
        2,
        2,
        width_ratios=grid_spec_width_ratios,
        height_ratios=grid_spec_height_ratios)
    gs_save.update(left=main_plot_left,
                   right=main_plot_right,
                   top=main_plot_top,
                   bottom=main_plot_bottom)

    ax_1_save = plt.subplot(gs_save[1])
    x_save, y_save = list(
        zip(*[(float(mpmath.re(point)), float(mpmath.im(point)))
              for point in points]))
    plot_1_save, = plt.plot(x_save, y_save, zorder=2)
    plt.axis('scaled')  # force equal axes even on plot window resize
    plt.xlabel(xlabel_1)
    plt.ylabel(ylabel_1)
    plt.title(title)

    ax_0_save = plt.subplot(gs_save[0])
    plot_0_save, = plt.plot(y_save, list(range(len(y_save))), zorder=2)
    plt.xlabel(xlabel_0)
    plt.ylabel(ylabel_0)

    ax_3_save = plt.subplot(gs_save[3])
    plot_3_save, = plt.plot(list(range(len(x_save))), x_save, zorder=2)
    plt.xlabel(xlabel_3)
    plt.ylabel(ylabel_3)

    ax_2_save = plt.subplot(gs_save[2])
    num_point_display_history_box_save = matplotlib.widgets.TextBox(
        ax_2_save, label_2, initial='inf')

    # configure saved image filenames
    save_name_string_addition = ', stop_iteration_near ' + str(
        stop_iteration_near)
    sanitized_save_name = sanitize_file_name(
        plain_descriptor) + save_name_string_addition
    save_name_iteration_base = 'points/' + sanitized_save_name + iteration_postfix + '.png'
    save_name_final = 'points/Final ' + sanitized_save_name + '.png'

    child_conn.send(True)  # signal main thread ready for a new color map

    while (1):
        if child_conn.poll():
            # collect new data
            point, iteration = child_conn.recv()
            points.append(point)

            if num_point_display_history[0] == float('inf'):
                displayed_points = points
            else:
                displayed_points = points[-num_point_display_history[0]:]

            # update displayed figure
            x, y = list(
                zip(*[(float(mpmath.re(point)), float(mpmath.im(point)))
                      for point in displayed_points]))
            ax_1.set_title(
                iteration_prefix.format(iteration) + plain_descriptor +
                point_value_string(point))

            plot_0.set_data(y, list(range(len(y))))
            plot_1.set_data(x, y)
            plot_3.set_data(
                list(range(len(x))),
                x,
            )
            for ax in [ax_0, ax_1, ax_3]:
                ax.relim()
                ax.autoscale()
            fig.canvas.draw()
            fig.canvas.draw()  # intentionally repeated
            fig.canvas.flush_events()

            # save figure on each iteration
            x_save, y_save = list(
                zip(*[(float(mpmath.re(point)), float(mpmath.im(point)))
                      for point in displayed_points]))
            ax_1_save.set_title(
                iteration_prefix.format(iteration) + plain_descriptor +
                point_value_string(point))
            plot_0_save.set_data(y_save, list(range(len(y_save))))
            plot_1_save.set_data(x_save, y_save)
            plot_3_save.set_data(
                list(range(len(x_save))),
                x_save,
            )
            for ax in [ax_0_save, ax_1_save, ax_3_save]:
                ax.relim()
                ax.autoscale()
            fig_save.canvas.draw()
            fig_save.canvas.draw()  # intentionally repeated
            fig_save.canvas.flush_events()
            fig_save.savefig(save_name_final, dpi=100, bbox_inches='tight')
            shutil.copyfile(save_name_final,
                            save_name_iteration_base.format(iteration))

            # signal main thread ready for a new color map
            child_conn.send(True)
        else:
            background_plt_pause(0.01)
Esempio n. 36
0
def getImaginary( n ):
    return im( n )
Esempio n. 37
0
def solveQuarticPolynomialOperator( _a, _b, _c, _d, _e ):
    # pylint: disable=invalid-name
    '''
    This function applies the quartic formula to solve a polynomial
    with coefficients of a, b, c, d, and e.
    '''
    if mp.dps < 50:
        mp.dps = 50

    # maybe it's really an order-3 polynomial
    if _a == 0:
        return solveCubicPolynomial( _b, _c, _d, _e )

    # degenerate case, just return the two real and two imaginary 4th roots of the
    # constant term divided by the 4th root of a
    if _b == 0 and _c == 0 and _d == 0:
        e = fdiv( _e, _a )

        f = root( _a, 4 )

        x1 = fdiv( root( fneg( e ), 4 ), f )
        x2 = fdiv( fneg( root( fneg( e ), 4 ) ), f )
        x3 = fdiv( mpc( 0, root( fneg( e ), 4 ) ), f )
        x4 = fdiv( mpc( 0, fneg( root( fneg( e ), 4 ) ) ), f )

        return [ x1, x2, x3, x4 ]

    # otherwise we have a regular quartic to solve
    b = fdiv( _b, _a )
    c = fdiv( _c, _a )
    d = fdiv( _d, _a )
    e = fdiv( _e, _a )

    # we turn the equation into a cubic that we can solve
    f = fsub( c, fdiv( fmul( 3, power( b, 2 ) ), 8 ) )
    g = fsum( [ d, fdiv( power( b, 3 ), 8 ), fneg( fdiv( fmul( b, c ), 2 ) ) ] )
    h = fsum( [ e, fneg( fdiv( fmul( 3, power( b, 4 ) ), 256 ) ),
                fmul( power( b, 2 ), fdiv( c, 16 ) ), fneg( fdiv( fmul( b, d ), 4 ) ) ] )

    roots = solveCubicPolynomial( 1, fdiv( f, 2 ), fdiv( fsub( power( f, 2 ), fmul( 4, h ) ), 16 ),
                                  fneg( fdiv( power( g, 2 ), 64 ) ) )
    y1 = roots[ 0 ]
    y2 = roots[ 1 ]
    y3 = roots[ 2 ]

    # pick two non-zero roots, if there are two imaginary roots, use them
    if y1 == 0:
        root1 = y2
        root2 = y3
    elif y2 == 0:
        root1 = y1
        root2 = y3
    elif y3 == 0:
        root1 = y1
        root2 = y2
    elif im( y1 ) != 0:
        root1 = y1

        if im( y2 ) != 0:
            root2 = y2
        else:
            root2 = y3
    else:
        root1 = y2
        root2 = y3

    # more variables...
    p = sqrt( root1 )
    q = sqrt( root2 )
    r = fdiv( fneg( g ), fprod( [ 8, p, q ] ) )
    s = fneg( fdiv( b, 4 ) )

    # put together the 4 roots
    x1 = fsum( [ p, q, r, s ] )
    x2 = fsum( [ p, fneg( q ), fneg( r ), s ] )
    x3 = fsum( [ fneg( p ), q, fneg( r ), s ] )
    x4 = fsum( [ fneg( p ), fneg( q ), r, s ] )

    return [ chop( x1 ), chop( x2 ), chop( x3 ), chop( x4 ) ]
Esempio n. 38
0
def solveQuarticPolynomial( _a, _b, _c, _d, _e ):
    if mp.dps < 50:
        mp.dps = 50

    # maybe it's really an order-3 polynomial
    if _a == 0:
        return solveCubicPolynomial( _b, _c, _d, _e )

    # degenerate case, just return the two real and two imaginary 4th roots of the
    # constant term divided by the 4th root of a
    elif _b == 0 and _c == 0 and _d == 0:
        e = fdiv( _e, _a )

        f = root( _a, 4 )

        x1 = fdiv( root( fneg( e ), 4 ), f )
        x2 = fdiv( fneg( root( fneg( e ), 4 ) ), f )
        x3 = fdiv( mpc( 0, root( fneg( e ), 4 ) ), f )
        x4 = fdiv( mpc( 0, fneg( root( fneg( e ), 4 ) ) ), f )

        return [ x1, x2, x3, x4 ]

    # otherwise we have a regular quartic to solve
    b = fdiv( _b, _a )
    c = fdiv( _c, _a )
    d = fdiv( _d, _a )
    e = fdiv( _e, _a )

    # we turn the equation into a cubic that we can solve
    f = fsub( c, fdiv( fmul( 3, power( b, 2 ) ), 8 ) )
    g = fsum( [ d, fdiv( power( b, 3 ), 8 ), fneg( fdiv( fmul( b, c ), 2 ) ) ] )
    h = fsum( [ e, fneg( fdiv( fmul( 3, power( b, 4 ) ), 256 ) ),
                fmul( power( b, 2 ), fdiv( c, 16 ) ), fneg( fdiv( fmul( b, d ), 4 ) ) ] )

    y1, y2, y3 = solveCubicPolynomial( 1, fdiv( f, 2 ), fdiv( fsub( power( f, 2 ), fmul( 4, h ) ), 16 ),
                                       fneg( fdiv( power( g, 2 ), 64 ) ) )

    # pick two non-zero roots, if there are two imaginary roots, use them
    if y1 == 0:
        root1 = y2
        root2 = y3
    elif y2 == 0:
        root1 = y1
        root2 = y3
    elif y3 == 0:
        root1 = y1
        root2 = y2
    elif im( y1 ) != 0:
        root1 = y1

        if im( y2 ) != 0:
            root2 = y2
        else:
            root2 = y3
    else:
        root1 = y2
        root2 = y3

    # more variables...
    p = sqrt( root1 )
    q = sqrt( root2 )
    r = fdiv( fneg( g ), fprod( [ 8, p, q ] ) )
    s = fneg( fdiv( b, 4 ) )

    # put together the 4 roots
    x1 = fsum( [ p, q, r, s ] )
    x2 = fsum( [ p, fneg( q ), fneg( r ), s ] )
    x3 = fsum( [ fneg( p ), q, fneg( r ), s ] )
    x4 = fsum( [ fneg( p ), fneg( q ), r, s ] )

    return [ chop( x1 ), chop( x2 ), chop( x3 ), chop( x4 ) ]
Esempio n. 39
0
def write_g_re(filename, e, sigma):
    with open(filename, 'w') as f:
        for ene, s in zip(e, sigma):
            f.write('{0:18.8f}{1:18.12f}{2:18.12f}\n'.format(
                float(re(ene)), float(re(s)), float(im(s))))