示例#1
0
def getZero(Func,
            init=(1. + 1.j, 1.1 + 1.j, 1. + 1.1j),
            solver='muller',
            ftol=1.e-3,
            tol=1.e-3,
            maxsteps=600):
    import mpmath as mp
    w0 = complex(float('nan'), float('nan'))
    try:
        w0 = mp.findroot(lambda w: Func(complex(w)),
                         init,
                         solver=solver,
                         maxsteps=maxsteps,
                         ftol=ftol,
                         tol=tol)
    except:
        try:
            w0 = mp.findroot(lambda w: Func(complex(w)),
                             init[0],
                             solver='halley',
                             maxsteps=maxsteps,
                             ftol=ftol,
                             tol=tol)
        except:
            print "Could not find zero"

    return complex(w0)
 def find_equilibrium_point(self, x):
     """For a given point x, find the corresponding y and ac values. Raises
     ValueError if no equilibrium exists"""
     self.x = x
     # Approximate solution for y
     tmpy = spi.fsolve(self.dydt, 0.1)  # Anything will do
     # if tmpy is negative, try a lower root
     k = 2
     while tmpy[0] < 0 and k < 100:
         tmpy = spi.fsolve(self.dydt, 10**-k)
         k += 1
     ysol = mpmath.findroot(self.dydt, [float(tmpy[0])], method='mnewton')
     self.y = float(ysol.real)
     # Approximate solution for ac
     tmpac = spi.fsolve(self.dxdt, 0.1)  # Anything will do
     k = 2
     while tmpac < 0 and k < 100:
         tmpac = spi.fsolve(self.dxdt, 10**-k)
         k += 1
     self.y = ysol
     acsol = mpmath.findroot(self.dxdt, [float(tmpac[0])], method='mnewton')
     sol = [float(acsol.real), x, float(ysol.real)]
     if any([i < 0 for i in sol]):
         raise ValueError
     else:
         return sol
示例#3
0
 def solver(args):
     equation, lower_boundary, upper_boundary, initial_guess, f, use_mpmath = args
     if not use_mpmath:
         warnings.filterwarnings('ignore')
         solution = root(equation, initial_guess, args=f, method='hybr')
         solution = solution.x[0]
         warnings.resetwarnings()
     else:
         equation_wrap = partial(equation, f=f)
         try:
             solution = mp.findroot(equation_wrap,
                                    (lower_boundary, upper_boundary),
                                    maxsteps=1000,
                                    solver='anderson',
                                    tol=5e-16)
         except ValueError as err:
             print err
             print 'Lowering tolerance to 5e-6'
             solution = mp.findroot(equation_wrap,
                                    (lower_boundary, upper_boundary),
                                    maxsteps=1000,
                                    solver='anderson',
                                    tol=5e-6)
         solution = np.float(solution)
     return solution
示例#4
0
def buneman_growth_rate(alphaarray, rmass):

    nalpha = alphaarray.shape[0]

    alphamin = alphaarray[0]
    alphamax = alphaarray[nalpha - 1]

    prev_root = complex(0, 0)

    growth_rate = np.zeros(nalpha)
    growth_rate_r = np.zeros(nalpha)

    def buneman_disp(x):
        return (x**-(-rmass + x**2) * (x - alphaarray[0])**2)

    new_root = mpmath.findroot(buneman_disp, prev_root, solver='newton')
    growth_rate[0] = new_root.imag
    prev_root = complex(new_root.real, new_root.imag)
    #    print(repr(prev_root))

    for i in range(1, nalpha):
        # print(repr(i))
        def buneman_disp2(x):
            return (x**2 - (-rmass + x**2) * (x - alphaarray[i])**2)

        new_root = mpmath.findroot(buneman_disp2, prev_root, solver='muller')
        growth_rate[i] = new_root.imag
        growth_rate_r[i] = new_root.real
        prev_root = complex(new_root.real, new_root.imag)

    return growth_rate, growth_rate_r
示例#5
0
    def ECM(self):
        """
        ECM Algorithm implementation
        """
        self.kVecCumul = np.cumsum(self.kVec)
        #Initial estimates
        self.arule = [1.0 * self.total_failures]
        self.brule = [1.0 * self.total_failures / self.total_time]
        self.crule = [1.0]

        self.ll_list = [self.logL(self.arule[0], self.brule[0], self.crule[0])]
        self.ll_error_list = []
        self.ll_error = 1
        self.j = 0

        limits_b = []
        limits_c = []

        while (self.ll_error > pow(10, -6)):
            print("Iteration number : {}".format(self.j))
            self.a_est = self.aMLE(self.total_failures, self.tn,
                                   self.brule[self.j], self.crule[self.j])
            self.arule.append(self.a_est)
            print("Estimated a: {}".format(self.a_est))

            limits_b = self.MLElim(self.bMLE,
                                   self.brule[self.j],
                                   c=self.crule[self.j],
                                   a=self.arule[self.j + 1])
            self.b_est = findroot(self.bMLE,
                                  limits_b,
                                  tol=1e-15,
                                  solver='illinois')
            #self.b_est = findroot(self.bMLE, self.brule[self.j], tol=1e-24, solver = 'halley')
            print("Estimated b : {}".format(self.b_est))
            self.brule.append(self.b_est)

            #if len(limits_c) == 0:
            limits_c = self.MLElim(self.cMLE,
                                   self.crule[self.j],
                                   a=self.arule[self.j + 1],
                                   b=self.brule[self.j + 1])
            self.c_est = findroot(self.cMLE,
                                  limits_c,
                                  tol=1e-15,
                                  solver='illinois')
            #self.c_est = findroot(self.cMLE, self.crule[self.j], tol=1e-24, solver = 'halley')
            print("Estimated c : {}".format(self.c_est))
            self.crule.append(self.c_est)

            self.ll_list.append(self.logL(self.a_est, self.b_est, self.c_est))
            self.j += 1
            self.ll_error = self.ll_list[self.j] - self.ll_list[self.j - 1]
            print("Log Likelihood error = {}".format(self.ll_error))
            self.ll_error_list.append(self.ll_error)

            print(
                "------------------------------------------------------------------------"
            )
        print(self.ll_list[-1], self.arule[-1], self.brule[-1], self.crule[-1])
示例#6
0
 def _findRootAttempt(self, startingEne, multipler, type):
     try:
         fun = lambda e: self._getDet(e, multipler)
         if type == 'muller':
             return complex(mpmath.findroot(fun, startingEne, solver='muller', maxsteps=10000, tol=2.16840434497100886801e-19))
         else:
             return complex(mpmath.findroot(fun, startingEne[0], solver='secant'))
     except ValueError:
         return None
示例#7
0
def jacobian_stability_analysis(J11, J12, J21, J22):
    """jacobian_stability_analysis is a function that performs the stability analysis of each equilibria found.
    For each equilibria, a jacobian is created, the eigenvalues are then found of this jacobian and returned 
    by this function."""
    f = [lambda z: ((J11 - z) * (J22 - z) - (J12) * (J21))]
    z1 = (mp.findroot(f, ([100 + 1j]), solver='muller', verify=False))
    z2 = (mp.findroot(f, ([-100 + 1j]), solver='muller', verify=False))
    eigenvalues = np.array[z1, z2]

    return eigenvalues.astype(float)
示例#8
0
文件: PyPPL.py 项目: philscher/gkc
def getZero(Func, init=(1.+1.j, 1.1+1.j, 1.+1.1j), solver='muller', ftol=1.e-3, tol=1.e-3, maxsteps=600):
  import mpmath as mp
  w0 = complex(float('nan'), float('nan'))
  try:
     w0 = mp.findroot(lambda w : Func(complex(w)), init, solver=solver, maxsteps=maxsteps, ftol=ftol, tol=tol)
  except:
   try:
     w0 = mp.findroot(lambda w : Func(complex(w)), init[0], solver='halley', maxsteps=maxsteps, ftol=ftol, tol=tol)
   except:   
     print "Could not find zero"

  return complex(w0)
def v(x,t,s,b):
    """
    inverse map of w(v) = x+i\tau --> x-t.
    """
    # c is atrificial parameter for findroot.
    c = 10**(-9)
    if x>b:
        return j*mp.findroot(lambda y: re(w(j*y,s,b)-(x-t)), [-s/2+c,0-c],"bisect")
    elif x<-b:
        return j*mp.findroot(lambda y: re(w(j*y,s,b)-(x-t)), [0+c,s/2-c],"bisect")
    else:
        return 1/2+j*mp.findroot(lambda y: re(w(1/2+j*y,s,b)-(x-t)), 0)
示例#10
0
文件: sdesolver.py 项目: amal029/eha
    def _compute_step(fxt, gxt, dq, R, dWt):
        # print('compute step:', dq)

        Winc = sum(dWt)
        gn = gxt * Winc
        # This is the max dq we can take
        # FIXME: IMP
        # This can be negative, then what happens?
        dq2 = gn**2 / (4 * fxt * R)
        dq2 = abs(dq2)
        # odq = dq
        dq = dq if dq <= dq2 else dq2
        # print('Given dq: %f, chosen dq: %f' % (odq, dq))
        # First coefficient
        a = R * (fxt**2)
        # Second coefficient
        b = ((2 * fxt * dq * R) - (gn**2))
        # Third coefficient
        c = R*(dq**2)

        # Use mpmath to get the roots
        # There can be only one root.
        f = (lambda x: a*(x**2) + (b*x) + c)
        try:
            root1 = mp.findroot(f, 0)
            # Debug
            # print('root1:', root1)
            root1 = root1 if root1 >= 0 else None
        except ValueError:
            # print(e)
            root1 = None

        # The second polynomial ax² - bx + cx = 0
        b = ((2 * fxt * dq * R) + (gn**2))
        f = (lambda x: a*(x**2) - (b*x) + c)
        try:
            root2 = mp.findroot(f, 0)
            # print('root2:', root2)
            root2 = root2 if root2 >= 0 else None
        except ValueError:
            # print(e)
            root2 = None

        # Now get Δt and δt
        Dt = root1 if root1 is not None else root2
        Dt = min(Dt, root2) if root2 is not None else Dt
        dt = Dt/R
        # print('Δt: %f, δt: %f' % (Dt, dt))

        # assert False
        return Dt, dt
示例#11
0
 def draw_waiting_time(self, avail_devices, failed_devices):
     self.curr_avail_devices = avail_devices
     self.curr_failed_devices = failed_devices
     self.curr_uniform_variate = random.uniform(0,1)
     
     while self.curr_uniform_variate == 0:
             self.curr_uniform_variate = random.uniform(0,1)
     
     try:
         wait_time = findroot(self.func, [0,100], solver='secant')
     except:
         wait_time = findroot(self.func, [0,100], solver='secant', maxsteps=1000)
         #wait_time = findroot(self.func, [0, 87600] , maxsteps=1000, solver='secant', verify=False)
         
     return abs(wait_time)
示例#12
0
def getPredictability(N, S, e=2):
    if (N >= e) & np.isfinite(S) & (S < np.log2(N + 1e-10)):
        f = lambda x: (((1 - x) / (N - 1))**(1 - x)) * x**x - 2**(-S)
        root = mpmath.findroot(f, 1)
        return float(root.real)
    else:
        return np.nan
示例#13
0
    def solve(self, omegamax=5e6, domega0=lambda x: 10e3):
        omega = [0]  #[0,1000.,2000.]
        ksi = [0]  #[0,omega[1]/cb, omega[2]/cb]
        domega = domega0(0)
        while omega[-1] <= omegamax and domega > 1e-6 * domega0(omega[-1]):
            xx = omega[-1] + domega
            q = lambda x: self.f(x, xx) / xx**2
            try:
                if len(omega) >= 3:
                    y0 = (xx - omega[-2]) / (omega[-1] - omega[-2]) * (
                        ksi[-1] - ksi[-2]) + ksi[-2]
                else:
                    y0 = 1.0
                y = mm.findroot(q, y0, solver='mnewton')
                omega.append(omega[-1] + domega)
                ksi.append(y.real)
                print("converged:", omega[-1])
                domega = domega0(omega[-1])
            except ValueError:
                print("not converged:", omega[-1] + domega, domega)
                domega *= 0.5

        self.ksi_omega = lambda x: np.interp(x, omega, ksi)
        self.omega = np.array(omega)
        self.ksi = np.array(ksi)
        self.omegamax = max(self.omega)
示例#14
0
def mle(x, loc=None, scale=None):
    """
    Maximum likelihood estimates for the Gumbel distribution.

    `x` must be a sequence of numbers--it is the data to which the
    Gumbel distribution is to be fit.

    If either `loc` or `scale` is not None, the parameter is fixed
    at the given value, and only the other parameter will be fit.

    Returns maximum likelihood estimates of the `loc` and `scale`
    parameters.

    Examples
    --------
    Imports and mpmath configuration:

    >>> import mpmath
    >>> mpmath.mp.dps = 20
    >>> from mpsci.distributions import gumbel_max

    The data to be fit:

    >>> x = [6.86, 14.8 , 15.65,  8.72,  8.11,  8.15, 13.01, 13.36]

    Unconstrained MLE:

    >>> gumbel_max.mle(x)
    (mpf('9.4879877926148360358863'), mpf('2.727868138859403832702'))

    If we know the scale is 2, we can add the argument `scale=2`:

    >>> gumbel_max.mle(x, scale=2)
    (mpf('9.1305625326153555632872'), mpf('2.0'))
    """
    with mpmath.extradps(5):
        x = [mpmath.mpf(xi) for xi in x]

        if scale is None and loc is not None:
            # Estimate scale with fixed loc.
            loc = mpmath.mpf(loc)
            # Initial guess for findroot.
            s0 = stats.std([xi - loc for xi in x])
            scale = mpmath.findroot(
                lambda t: _mle_scale_with_fixed_loc(t, x, loc), s0
            )
            return loc, scale

        if scale is None:
            scale = _solve_mle_scale(x)
        else:
            scale = mpmath.mpf(scale)

        if loc is None:
            ex = [mpmath.exp(-xi / scale) for xi in x]
            loc = -scale * mpmath.log(stats.mean(ex))
        else:
            loc = mpmath.mpf(loc)

        return loc, scale
示例#15
0
def _solve_mle_scale(x):
    xbar = stats.mean(x)

    # Very rough guess of the scale parameter:
    s0 = stats.std(x)
    if s0 == 0:
        # The x values are all the same.
        return s0

    # Find an interval in which there is a sign change of
    # gumbel_min._mle_scale_func.
    s1 = s0
    s2 = s0
    sign2 = mpmath.sign(_mle_scale_func(s2, x, xbar))
    while True:
        s1 = 0.9*s1
        sign1 = mpmath.sign(_mle_scale_func(s1, x, xbar))
        if (sign1 * sign2) <= 0:
            break
        s2 = 1.1*s2
        sign2 = mpmath.sign(_mle_scale_func(s2, x, xbar))
        if (sign1 * sign2) <= 0:
            break

    # Did we stumble across the root while looking for an interval
    # with a sign change?  Not likely, but check anyway...
    if sign1 == 0:
        return s1
    if sign2 == 0:
        return s2

    root = mpmath.findroot(lambda t: _mle_scale_func(t, x, xbar),
                           [s1, s2], solver='anderson')

    return root
示例#16
0
文件: main.py 项目: Revylon/Quantum
    def find_roots(self):
        # Вектор E0 - вектор начального приближения
        E_min = 0.001 * max(self.barriers_high_vector)  #+ 0.001*10**(-12)
        E_max = 0.999 * max(self.barriers_high_vector)  #- 0.001*10**(-12)

        E_list = np.linspace(E_min, E_max, 100)
        T_list = np.zeros_like(E_list)

        for energy in range(len(E_list)):
            T_list[energy] = float(
                (self.full_transfer_matrix(E_list[energy]).real))

        sign_vector = []
        zero_vector = []

        for energy in range(len(E_list)):
            if T_list[energy] > 0:
                sign_vector.append(1)
            elif T_list[energy] < 0:
                sign_vector.append(-1)

        for ind in range(len(sign_vector) - 1):
            if not sign_vector[ind] == sign_vector[ind + 1]:
                zero_vector.append(E_list[ind])

        for energy in range(len(zero_vector)):
            self.roots.append(
                float(
                    mp.findroot(lambda t: self.full_transfer_matrix(t).real,
                                zero_vector[energy],
                                solver='mnewton')).real)

        return self.roots
示例#17
0
    def exact_quadratic_forward_loewner(self):

        # Declare an empty complex array for the exact results
        self.exact_quadratic_forward = zeros(self.outer_points,
                                             dtype=complex128)

        # Define a function for generating an initial guess to be used by the non-linear solver
        def initial_guess(t):
            return 2 * 1j * sqrt(t) + (2. / 3) * t

        # Define the non-linear function for obtaining the exact solution
        def exact_solution(z, t):
            return z + 2 * log(2 - z) - 2 * log(2) - t

        # Iterate through the exact time values
        for i in range(self.outer_points):

            # Use Muller's method for finding the exact solution
            self.exact_quadratic_forward[i] = findroot(
                lambda z: exact_solution(z, self.exact_time_sol[i]),
                initial_guess(self.exact_time_sol[i]),
                solver='muller',
                tol=TOL)

        if self.save_data:

            # Create a filename for the dat file
            filename = EXACT_FORWARD_DATA_OUTPUT + self.short_properties_string + DATA_EXT

            # Create a 2D array from the real and imaginary values of the results
            results_array = column_stack((self.exact_quadratic_forward.real,
                                          self.exact_quadratic_forward.imag))

            # Save the array to the filesystem
            self.save_to_dat(filename, results_array)

        if self.save_plot:

            # Clear any preexisting plots to be safe
            plt.cla()

            # Set the plot title
            self.set_plot_title()

            # Plo the values
            plt.plot(self.exact_quadratic_forward.real,
                     self.exact_quadratic_forward.imag,
                     color='crimson')

            # Set the axes labels
            plt.xlabel(FOR_PLOT_XL)
            plt.ylabel(FOR_PLOT_YL)

            # Set the lower limit of the y-axis
            plt.ylim(bottom=0)

            # Save the plot to the filesystem
            plt.savefig(EXACT_FORWARD_PLOT_OUTPUT +
                        self.short_properties_string + PLOT_EXT,
                        bbox_inches='tight')
示例#18
0
def getPredictability(N, S):
    if N <= 3:
        return
    f = lambda x: (((1 - x) / (N - 1))**(1 - x)) * x**x - 2**(-S)
    root = mpmath.findroot(f, 1)
    res = float(root.real)
    return res
示例#19
0
 def int_interval(wrel, n, t, k):
     """
     find out the almost-singular point and
     divide the integration integrals.
     
     """
     if wrel < 1 or wrel > 1.3:
         return [0, mp.inf]
     else:
         guesses = [4, 6, 8, 10, 12, 14]
     wc = wrel * mp.sqrt(1+n)
     int_range = [0, mp.inf]
     for guess in guesses:
         try:
             root = mp.findroot(lambda zc: MaxKappa.e_l(zc, wc, n, t, k), guess)
         except ValueError:
             continue
         unique = True
         for z in int_range:
             if mp.fabs(z - mp.fabs(root)) < 1e-4:
                 unique = False
         if unique:
             int_range += [mp.fabs(root)]
     int_range = np.sort(int_range)
     return int_range
示例#20
0
def mle(x, nu=None, loc=None, scale=None):
    """
    Nakagami distribution maximum likelihood parameter estimation.

    x must be a sequence of numbers.

    Returns (nu, loc, scale).

    Currently a fixed loc *must* be given.
    """
    if loc is not None:
        _validate_x(x, loc)
        x = [t - loc for t in x]
    else:
        raise ValueError('Fitting `loc` is not implemented yet. '
                         '`loc` must be given.')

    if scale is None:
        scale = mpmath.sqrt(mpmath.fsum([t**2 for t in x])/len(x))

    if nu is None:
        R = (stats.mean([(t/scale)**2 for t in x]) -
             stats.mean([2*mpmath.log(t/scale) for t in x]) - 1)
        nu0 = _estimate_nu(R)
        nu = mpmath.findroot(lambda nu: _mle_nu_func(nu, scale, R), nu0)

    return nu, loc, scale
示例#21
0
def nodes(n):
    left  = mp.mpf(0)
    right = mp.mpf(n+(n-1)*sqrt(n)*1.01)

    i = 2
    factor = 2

    while True:
        l = [ (x,mp.laguerre(n,0,x)) for x in mp.linspace(left,right,n*factor**i)]

        intervals = []
        for j in range(len(l)-1):
            prod = l[j][1]*l[j+1][1]
            if prod < 0:
                intervals.append([l[j][0], l[j+1][0]])

        if len(intervals) == n:
            break
        i += 1

    roots = []
    f = lambda x: mp.laguerre(n,0,x)
    for ab in intervals:
        a,b = ab
        try:
            z = mp.findroot(f, (a, b), tol=1e-50, solver='bisect')
        except:
            z = bisect(f, a, b, tol=1e-50)
        roots.append( z )

    return roots
示例#22
0
    def update_mix(self):
        if self.esolute.shape != self.esolvent.shape:
            return

        eeff = np.empty(self.esolute.shape, dtype=complex)
        for i in range(len(eeff)):
            e1 = self.esolute[i]  #.real
            em = self.esolvent[i]  #.real   #THIS IS GENERALLY THE SOLVENT

            partialfunc = partial(self.fill_func_dielectric,
                                  em=em,
                                  e1=e1,
                                  v=self.Vfrac,
                                  w=self.w)

            eeff[i] = findroot(
                partialfunc,
                (0.5, 1, 2),  #This is a root that we are guessing for 3 params
                solver='muller',
            )

            #eeff[i] = scipy.optimize.newton(self.fill_func_dielectric,
            #self.Root,
            #fprime=None,
            #args=(em, e1, self.Vfrac, self.w),
            #tol=.0001,
            #maxiter=1000)


#			self.Root=eeff[i]  #Reset the root
        self.mixedarray = eeff
示例#23
0
def delta_dual_color_numeric(q, g1d, Deltac, Deltad, Omega, n, delta_starting):
    return findroot(
        lambda x: eq_dual_color_numeric(q, x, g1d, Deltac, Deltad, Omega, n),
        delta_starting,
        solver='muller',
        tol=1e-10,
        maxsteps=10000)
示例#24
0
def invcdf(p):
    """
    Inverse of the CDF of the raised cosine distribution.
    """
    with mpmath.extradps(5):
        p = mpmath.mpf(p)

        if p < 0 or p > 1:
            return mpmath.nan
        if p == 0:
            return -mpmath.pi
        if p == 1:
            return mpmath.pi

        if p < 0.094:
            x = _poly_approx(mpmath.cbrt(12 * mpmath.pi * p)) - mpmath.pi
        elif p > 0.906:
            x = mpmath.pi - _poly_approx(mpmath.cbrt(12 * mpmath.pi * (1 - p)))
        else:
            y = mpmath.pi * (2 * p - 1)
            y2 = y**2
            x = y * _p2(y2) / _q2(y2)

        solver = 'mnewton'
        x = mpmath.findroot(f=lambda t: cdf(t) - p,
                            x0=x,
                            df=lambda t: (1 + mpmath.cos(t)) / (2 * mpmath.pi),
                            df2=lambda t: -mpmath.sin(t) / (2 * mpmath.pi),
                            solver=solver)

        return x
示例#25
0
    def compute_scaling_factor(self, dim, offset, verbose=False):
        # compute the scaling factor by minimizing the KL-divergence between
        # two multivariate t distributions of dimension `dim` where one has
        # covariance I and dof lambda + offset and the other has covariance
        # alpha * I and dof lambda, against alpha.

        # We use mpmath here because the high dimensionality leads to precision
        # errors in scipy.

        def _integrand(v, alpha, m, lmd, d):
            return (mp.power(v / (1 + v), m / 2) * 1.0 /
                    (v * mp.power(1 + v, (lmd + d) / 2.0)) *
                    mp.log(1 + (lmd + d) / (alpha * lmd) * v))

        def _H(alpha, m, lmd, d):
            H2 = mp.beta(m / 2, (lmd + d) / 2) * mp.log(alpha)
            Q = mp.quad(lambda v: _integrand(v, alpha, m, lmd, d), [0, mp.inf])
            H3 = (1 + lmd / m) * Q
            return H2 + H3

        m = mp.mpf(dim)
        lmd = mp.mpf(self.lambda0)
        d = mp.mpf(offset)
        F = lambda alpha: _H(alpha, m, lmd, d)
        dF = lambda alpha: mp.diff(F, alpha)
        alpha_star = mp.findroot(dF, mp.mpf(1.0), verbose=verbose)
        return float(alpha_star)
示例#26
0
def invcdf(p, a, b, c, loc=0, scale=1):
    """
    Inverse of the CDF of the generalized exponential distribution.

    This is also known as the quantile function.
    """
    if p < 0 or p > 1:
        raise ValueError("'p' must be between 0 and 1.")
    with mpmath.extradps(5):
        p = mpmath.mpf(p)
        a, b, c, loc, scale = _validate_params(a, b, c, loc, scale)

        s = a + b
        r = b / c

        y = -mpmath.log1p(-p)
        s = a + b
        r = b / c

        def _genexpon_invcdf_rootfunc(z):
            return s*z + r*mpmath.expm1(-c*z) - y

        z0 = y / s
        z1 = (y + r) / s
        z = mpmath.findroot(_genexpon_invcdf_rootfunc,
                            (z0, z1), solver='anderson')
        x = loc + scale*z
    return x
    def generate_zeta(self):
        import mpmath
        import sys
        root_list		= {}
        for s in [complex(0.5,t) for t in range(10,100)]:
            try:
                root_complex	= mpmath.findroot(mpmath.zeta, s)
                if self.debug:
                    sys.stderr.write("[NOTICE] Found nontrivial zeta zero at %s.\n" % str(root_complex))
                root_imag	= float(root_complex.imag)
                try:
                    root_list[root_imag]
                    if self.debug:
                        sys.stderr.write("[NOTICE] Already found this zero, skipping.\n")
                    next
                except KeyError:
                    if root_imag > 1:
                        yield root_imag
                        root_list[root_imag] = True
                    else:
                        if self.debug:
                            sys.stderr.write("[NOTICE] Irrelevant zero, skipping.\n")
            except ValueError, e:
#DEBUG#                sys.stderr.write("Exception at s=%s: %s.\n" % (str(s), e.args[0])) #DEBUG#
                pass
            except OverflowError, e:
#DEBUG#                sys.stderr.write("Exception at s=%s: %s.\n" % (str(s), e.args[0])) #DEBUG#
                pass
示例#28
0
def tcaf(y):
    """
    Find an x such that x! =~ y, ie Gamma(x + 1) =~ y.
    """
    x = mpmath.findroot(lambda t: mpmath.factorial(t) - y, (1, 100),
                        solver="bisect")
    return x
示例#29
0
def v(x, t, s, b):
    # c is atrificial parameter for findroot.
    c = 10**(-10)
    if x > b:
        return j * mp.findroot(lambda y: re(w(j * y, s, b) - (x - t)),
                               [-s / 2 + c, 0 - c], "bisect")
    elif x < -b:
        return j * mp.findroot(lambda y: re(w(j * y, s, b) - (x - t)),
                               [0 + c, s / 2 - c], "bisect")
    else:
        tolerant = 10**(-20)
        normparam = 10**11
        return 1 / 2 + j * mp.findroot(
            lambda y: tanh(re(w(1 / 2 + j * y, s, b) - (x - t)) / normparam),
            0,
            tol=tolerant)
示例#30
0
def nodes(n):
    left = mp.mpf(0)
    right = mp.mpf(n + (n - 1) * sqrt(n) * 1.01)

    i = 2
    factor = 2

    while True:
        l = [(x, mp.laguerre(n, 0, x))
             for x in mp.linspace(left, right, n * factor**i)]

        intervals = []
        for j in range(len(l) - 1):
            prod = l[j][1] * l[j + 1][1]
            if prod < 0:
                intervals.append([l[j][0], l[j + 1][0]])

        if len(intervals) == n:
            break
        i += 1

    roots = []
    f = lambda x: mp.laguerre(n, 0, x)
    for ab in intervals:
        a, b = ab
        try:
            z = mp.findroot(f, (a, b), tol=1e-50, solver='bisect')
        except:
            z = bisect(f, a, b, tol=1e-50)
        roots.append(z)

    return roots
示例#31
0
	def mini(r):
		nonlocal txi, tv
		xi = [r]
		y = f(r)
		v = r*f(r) + mpmath.quad(f, [r, mpmath.inf])
		if verbose:
			print('Trying r={0} (v={1})'.format(r, v), file=sys.stderr)
		for i in itertools.count():
			xm1 = xi[i]
			h = v / xm1
			y += h
			if y >= maximum or mpmath.almosteq(y, maximum, abs_eps=mpmath.mp.eps * 2**10):
				break
			# We solve for x via secant method instead of using f's inverse.
			x = mpmath.findroot(lambda x: f(x) - y, xm1)
			xi.append(x)
		xi.append(mpmath.mpf())
		if len(xi) == nseg:
			if mpmath.almosteq(y, maximum, abs_eps=mpmath.mp.eps * 2**10):
				txi, tv = xi[::-1], v
				return 0
			# If y > maximum, then v is too large, which means r is too far
			# left, so we want to return a negative value. The opposite holds
			# true when y < maximum.
			return maximum - y
		return len(xi) - nseg + h*mpmath.sign(len(xi) - nseg)
示例#32
0
def _solve(func):
    """
    Solve func(nc) = 0.  func must be an increasing function.
    """
    with mpmath.extradps(5):
        # We could just as well call the variable `x` instead of `nc`, but we
        # always call this function with functions for which nc (the
        # noncentrality parameter) is the variable for which we are solving.
        nc = mpmath.mp.one
        value = func(nc)
        if value == 0:
            return nc

        # Multiplicative factor by which to increase or decrease nc when
        # searching for a bracketing interval.
        factor = mpmath.mpf(2)
        # Find a bracketing interval.
        if value > 0:
            nc /= factor
            while func(nc) > 0:
                nc /= factor
            lo = nc
            hi = factor*nc
        else:
            nc *= factor
            while func(nc) < 0:
                nc *= factor
            lo = nc/factor
            hi = nc

        # lo and hi bracket the solution for nc.
        nc = mpmath.findroot(func, (lo, hi), solver='illinois')
        return nc
示例#33
0
 def long_interval(w, n, t):
     """
     Return the interval of integration for longitudinal impedance, which
     is of the form [0, root, inf], where root satisfies
     d_l(root, w, n, t) = 0.
     
     """
     if w < mp.sqrt(1+n):
         return [0, mp.inf]
     if n == 0:
         guesses = [4, 6, 8, 10]
     else:
         guesses = [4, 6, 8, 10, 12, 14]
     int_range = [0, mp.inf]    
     for guess in guesses:
         try:
             root = mp.findroot(lambda z: BiMax.d_l(z, w, n, t), guess)
         except ValueError:
             continue
         unique = True
         for z in int_range:
             if mp.fabs(z - mp.fabs(root)) < 1e-4:
                 unique = False
         if unique:
             int_range += [mp.fabs(root)]
     int_range = np.sort(int_range)
     return int_range
示例#34
0
    def update_mix(self):
        if self.esolute.shape != self.esolvent.shape:
            return
        
        eeff=np.empty(self.esolute.shape, dtype=complex)
        for i in range(len(eeff)):
            e1 = self.esolute[i]#.real    
            em = self.esolvent[i]#.real   #THIS IS GENERALLY THE SOLVENT
            
            partialfunc = partial(self.fill_func_dielectric, em=em, e1=e1, v=self.Vfrac, w=self.w)
            
            
            eeff[i] = findroot(partialfunc, 
                               (0.5, 1, 2),  #This is a root that we are guessing for 3 params
                               solver='muller',
                               )            
            
            #eeff[i] = scipy.optimize.newton(self.fill_func_dielectric, 
                                            #self.Root,
                                            #fprime=None, 
                                            #args=(em, e1, self.Vfrac, self.w),
                                            #tol=.0001, 
                                            #maxiter=1000)
#			self.Root=eeff[i]  #Reset the root
        self.mixedarray=eeff
def system12_minimizer(p, l, kdpl1, kdpl2):
    p = mpf(p)
    l = mpf(l)
    kdpl1 = mpf(kdpl1)
    kdpl2 = mpf(kdpl2)
    if almosteq(kdpl1, mpf_zero, mpf_tol):
        kdpl1 += mpf_tol
    if almosteq(kdpl2, mpf_zero, mpf_tol):
        kdpl2 += mpf_tol

    def f(p_f, l_f):
        pl1 = p_f * l_f / kdpl1
        pl2 = p_f * l_f / kdpl2
        pl12 = (pl1 * l_f + pl2 * l_f) / (kdpl1 + kdpl2)
        return p - (p_f + pl1 + pl2 + pl12), l - (l_f + pl1 + pl2 + 2 * pl12)

    p_f, l_f = findroot(f, [mpf_zero, mpf_zero], tol=mpf_tol, maxsteps=1e6)
    pl1 = (p_f * l_f) / kdpl1
    pl2 = (p_f * l_f) / kdpl2
    return {
        "pf": p_f,
        "lf": l_f,
        "pl1": pl1,
        "pl2": pl2,
        "pl12": (pl1 * l_f + pl2 * l_f) / (kdpl1 + kdpl2),
    }
def system02_minimizer(p, l, i, kdpl, kdpi):
    kdpl = mpf(kdpl)
    kdpi = mpf(kdpi)
    if almosteq(kdpl, mpf_zero, mpf_tol):
        kdpl += mpf_tol
    if almosteq(kdpi, mpf_zero, mpf_tol):
        kdpi += mpf_tol
    p = mpf(p)
    l = mpf(l)
    i = mpf(i)

    def f(p_f, l_f, i_f):
        pl = p_f * l_f / kdpl
        pi = p_f * i_f / kdpi
        return p - (p_f + pl + pi), l - (l_f + pl), i - (i_f + pi)

    p_f, l_f, i_f = findroot(f, [mpf_zero, mpf_zero, mpf_zero],
                             tol=mpf_tol,
                             maxsteps=1e6)
    return {
        "pf": p_f,
        "lf": l_f,
        "if": i_f,
        "pl": (p_f * l_f) / kdpl,
        "pi": (p_f * i_f) / kdpi,
    }
示例#37
0
def solve(f, x0=None, nseg=128, verbose=False):
	"""Find r, v, and the x coordinates for f."""
	r = x0
	if r is None:
		if verbose:
			print('Calculating initial guess... ', end='', file=sys.stderr)
		# The area we seek is nseg equal-area rectangles surrounding f(x), not
		# f(x) itself, but we can get a good approximation from it.
		v = mpmath.quad(f, [0, mpmath.inf]) / nseg
		r = mpmath.findroot(lambda x: x*f(x) + mpmath.quad(f, [x, mpmath.inf]) - v, x0=1, x1=100, maxsteps=100)
		if verbose:
			print(r, file=sys.stderr)
	# We know that f(0) is the maximum because f must decrease monotonically.
	maximum = f(0)
	txi = []
	tv = mpmath.mpf()
	def mini(r):
		nonlocal txi, tv
		xi = [r]
		y = f(r)
		v = r*f(r) + mpmath.quad(f, [r, mpmath.inf])
		if verbose:
			print('Trying r={0} (v={1})'.format(r, v), file=sys.stderr)
		for i in itertools.count():
			xm1 = xi[i]
			h = v / xm1
			y += h
			if y >= maximum or mpmath.almosteq(y, maximum, abs_eps=mpmath.mp.eps * 2**10):
				break
			# We solve for x via secant method instead of using f's inverse.
			x = mpmath.findroot(lambda x: f(x) - y, xm1)
			xi.append(x)
		xi.append(mpmath.mpf())
		if len(xi) == nseg:
			if mpmath.almosteq(y, maximum, abs_eps=mpmath.mp.eps * 2**10):
				txi, tv = xi[::-1], v
				return 0
			# If y > maximum, then v is too large, which means r is too far
			# left, so we want to return a negative value. The opposite holds
			# true when y < maximum.
			return maximum - y
		return len(xi) - nseg + h*mpmath.sign(len(xi) - nseg)
	r = mpmath.findroot(mini, r)
	assert len(txi) == nseg
	if verbose:
		print('Done calculating r, v, x[i].', file=sys.stderr)
	return r, tv, txi
示例#38
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)))
示例#39
0
文件: rootoftools.py 项目: glyg/sympy
    def _eval_evalf(self, prec):
        """Evaluate this complex root to the given precision. """
        with workprec(prec):
            g = self.poly.gen
            if not g.is_Symbol:
                d = Dummy('x')
                func = lambdify(d, self.expr.subs(g, d))
            else:
                func = lambdify(g, self.expr)

            interval = self._get_interval()
            if not self.is_real:
                # For complex intervals, we need to keep refining until the
                # imaginary interval is disjunct with other roots, that is,
                # until both ends get refined.
                ay = interval.ay
                by = interval.by
                while interval.ay == ay or interval.by == by:
                    interval = interval.refine()

            while True:
                if self.is_real:
                    x0 = mpf(str(interval.center))
                else:
                    x0 = mpc(*map(str, interval.center))
                try:
                    root = findroot(func, x0, verify=False)
                    # If the (real or complex) root is not in the 'interval',
                    # then keep refining the interval. This happens if findroot
                    # accidentally finds a different root outside of this
                    # interval because our initial estimate 'x0' was not close
                    # enough.
                    if self.is_real:
                        a = mpf(str(interval.a))
                        b = mpf(str(interval.b))
                        if a == b:
                            root = a
                            break
                        if not (a < root < b):
                            raise ValueError("Root not in the interval.")
                    else:
                        ax = mpf(str(interval.ax))
                        bx = mpf(str(interval.bx))
                        ay = mpf(str(interval.ay))
                        by = mpf(str(interval.by))
                        if ax == bx and ay == by:
                            root = ax + S.ImaginaryUnit * by
                            break
                        if not (ax < root.real < bx and ay < root.imag < by):
                            raise ValueError("Root not in the interval.")
                except ValueError:
                    interval = interval.refine()
                    continue
                else:
                    break

        return Float._new(root.real._mpf_,
                          prec) + I * Float._new(root.imag._mpf_, prec)
示例#40
0
    def _eval_evalf(self, prec):
        """Evaluate this complex root to the given precision. """
        with workprec(prec):
            g = self.poly.gen
            if not g.is_Symbol:
                d = Dummy('x')
                func = lambdify(d, self.expr.subs(g, d))
            else:
                func = lambdify(g, self.expr)

            interval = self._get_interval()
            if not self.is_real:
                # For complex intervals, we need to keep refining until the
                # imaginary interval is disjunct with other roots, that is,
                # until both ends get refined.
                ay = interval.ay
                by = interval.by
                while interval.ay == ay or interval.by == by:
                    interval = interval.refine()

            while True:
                if self.is_real:
                    x0 = mpf(str(interval.center))
                else:
                    x0 = mpc(*map(str, interval.center))
                try:
                    root = findroot(func, x0, verify=False)
                    # If the (real or complex) root is not in the 'interval',
                    # then keep refining the interval. This happens if findroot
                    # accidentally finds a different root outside of this
                    # interval because our initial estimate 'x0' was not close
                    # enough.
                    if self.is_real:
                        a = mpf(str(interval.a))
                        b = mpf(str(interval.b))
                        if a == b:
                            root = a
                            break
                        if not (a < root < b):
                            raise ValueError("Root not in the interval.")
                    else:
                        ax = mpf(str(interval.ax))
                        bx = mpf(str(interval.bx))
                        ay = mpf(str(interval.ay))
                        by = mpf(str(interval.by))
                        if ax == bx and ay == by:
                            root = ax + S.ImaginaryUnit*by
                            break
                        if not (ax < root.real < bx and ay < root.imag < by):
                            raise ValueError("Root not in the interval.")
                except ValueError:
                    interval = interval.refine()
                    continue
                else:
                    break

        return Float._new(root.real._mpf_, prec) + I*Float._new(root.imag._mpf_, prec)
示例#41
0
    def _eval_evalf(self, prec):
        """Evaluate this complex root to the given precision. """
        with workprec(prec):
            g = self.poly.gen
            if not g.is_Symbol:
                d = Dummy('x')
                func = lambdify(d, self.expr.subs(g, d), "mpmath")
            else:
                func = lambdify(g, self.expr, "mpmath")

            try:
                interval = self.interval
            except KeyError:
                return super()._eval_evalf(prec)

            while True:
                if self.is_extended_real:
                    a = mpf(str(interval.a))
                    b = mpf(str(interval.b))
                    if a == b:
                        root = a
                        break
                    x0 = mpf(str(interval.center))
                else:
                    ax = mpf(str(interval.ax))
                    bx = mpf(str(interval.bx))
                    ay = mpf(str(interval.ay))
                    by = mpf(str(interval.by))
                    x0 = mpc(*map(str, interval.center))
                    if ax == bx and ay == by:
                        root = x0
                        break

                try:
                    root = findroot(func, x0)
                    # If the (real or complex) root is not in the 'interval',
                    # then keep refining the interval. This happens if findroot
                    # accidentally finds a different root outside of this
                    # interval because our initial estimate 'x0' was not close
                    # enough. It is also possible that the secant method will
                    # get trapped by a max/min in the interval; the root
                    # verification by findroot will raise a ValueError in this
                    # case and the interval will then be tightened -- and
                    # eventually the root will be found.
                    if self.is_extended_real:
                        if (a <= root <= b):
                            break
                    elif (ax <= root.real <= bx and ay <= root.imag <= by
                          and (interval.ay > 0 or interval.by < 0)):
                        break
                except (ValueError, UnboundLocalError):
                    pass
                self.refine()
                interval = self.interval

        return ((Float._new(root.real._mpf_, prec) if not self.is_imaginary
                 else 0) + I * Float._new(root.imag._mpf_, prec))
示例#42
0
    def _eval_evalf(self, prec):
        """Evaluate this complex root to the given precision."""
        with workprec(prec):
            g = self.poly.gen
            if not g.is_Symbol:
                d = Dummy('x')
                func = lambdify(d, self.expr.subs({g: d}), "mpmath")
            else:
                func = lambdify(g, self.expr, "mpmath")

            try:
                interval = self.interval
            except DomainError:
                return super()._eval_evalf(prec)

            while True:
                if self.is_extended_real:
                    a = mpf(str(interval.a))
                    b = mpf(str(interval.b))
                    if a == b:
                        root = a
                        break
                    x0 = mpf(str(interval.center))
                else:
                    ax = mpf(str(interval.ax))
                    bx = mpf(str(interval.bx))
                    ay = mpf(str(interval.ay))
                    by = mpf(str(interval.by))
                    x0 = mpc(*map(str, interval.center))
                    if ax == bx and ay == by:
                        root = x0
                        break

                try:
                    root = findroot(func, x0)
                    # If the (real or complex) root is not in the 'interval',
                    # then keep refining the interval. This happens if findroot
                    # accidentally finds a different root outside of this
                    # interval because our initial estimate 'x0' was not close
                    # enough. It is also possible that the secant method will
                    # get trapped by a max/min in the interval; the root
                    # verification by findroot will raise a ValueError in this
                    # case and the interval will then be tightened -- and
                    # eventually the root will be found.
                    if self.is_extended_real:
                        if (a <= root <= b):
                            break
                    elif (ax <= root.real <= bx and ay <= root.imag <= by
                          and (interval.ay > 0 or interval.by < 0)):
                        break
                except (ValueError, UnboundLocalError):
                    pass
                self.refine()
                interval = self.interval

        return ((Float._new(root.real._mpf_, prec) if not self.is_imaginary else 0) +
                I*Float._new(root.imag._mpf_, prec))
示例#43
0
 def solver(args):
     equation, lower_boundary, upper_boundary, initial_guess, f, use_mpmath = args
     if not use_mpmath:
         warnings.filterwarnings('ignore')
         solution = root(equation, initial_guess, args=f, method='hybr')
         solution = solution.x[0]
         warnings.resetwarnings()
     else:
         equation_wrap = partial(equation, f=f)
         try:
             solution = mp.findroot(equation_wrap, (lower_boundary, upper_boundary),
                                    maxsteps=1000, solver='anderson', tol=5e-16)
         except ValueError as err:
             print err
             print 'Lowering tolerance to 5e-6'
             solution = mp.findroot(equation_wrap, (lower_boundary, upper_boundary),
                                    maxsteps=1000, solver='anderson', tol=5e-6)
         solution = np.float(solution)
     return solution
示例#44
0
def besselJZeros(m, a, b):
  require_mpmath()
  if not hasattr(mpmath, 'besseljzero'):
    besseljn = lambda x: mpmath.besselj(m, x)
    results = [mpmath.findroot(besseljn, mpmath.pi*(kp - 1./4 + 0.5*m)) for kp in range(a, b+1)]
  else:
    results = [mpmath.besseljzero(m, i) for i in xrange(a, b+1)]
  # Check that we haven't found double roots or missed a root. All roots should be separated by approximately pi
  assert all([0.6*mpmath.pi < (b - a) < 1.4*mpmath.pi for a, b in zip(results[:-1], results[1:])]), "Separation of Bessel zeros was incorrect."
  return results
def printAnaRoots(V, fndStates):
  print "\n\nFor V=" + str(V)
  def denumWrap(k):
    return denum(k,a,V)
  for state in fndStates:
    try:
      root = mpm.findroot(denumWrap, state)
      diff = abs(root-state)
      print str(root.real) + "\t" + str(root.imag) + "\t" + str(diff)
    except ValueError:
      print "Not Fnd"
示例#46
0
def getIslandWidth(x,y,Psi):
    from scipy import interpolate
    import mpmath as mp      
    Nx = len(x)
    Ny = len(y)
    XPointValue_1 = Psi[0,Nx/2]
    XPointValue_2 = Psi[-1,Nx/2]

    
    # Interpolate Psi
    Psi_inter = interpolate.splrep(x,Psi[Ny/2,:],s=0)

    # Find zero
    def W(x) : 
      return XPointValue_1 - interpolate.splev(float(x),Psi_inter,der=0)
    try:
        w1 = float(mp.findroot(W,  1))
        w2 = float(mp.findroot(W, -1))
    except:
        w1 = 0.
        w2 = 0.
    return (w1, w2) 
示例#47
0
 def find_s_min(S_max, N, B):
     '''Kraft, Burrows and Nousek suggest to integrate from N-B in both
     directions at once, so that S_min and S_max move similarly (see the article
     for details). Here, this is implemented differently:
     Treat S_max as the optimization parameters in func and then calculate the
     matching s_min that has has eqn7(S_max) = eqn7(S_min) here.
     '''
     y_S_max = eqn7(S_max, N, B)
     if eqn7(0, N, B) >= y_S_max:
         return 0.
     else:
         def eqn7ysmax(x):
             return eqn7(x, N, B) - y_S_max
         return findroot(eqn7ysmax , (N - B) / 2.)
def diodeResistorIMPLICITfunction(x, b, c=None):

    """
    Возвращает ток, текущей по цепи

    коэффициенты модели: Ток утечки Is, коэффициент неидеальности N, омическое сопротивление, последовательное диоду R
    входные параметры: напряжение, приложенное источником к системе резистор-диод
    +-----------|||||---------->|--------- -
    Резистор подключен до диода

    ===ОГРАНИЧЕНИЯ===
    #Сочетание боьльших напряжений  (>1В) и нулевого сопротивления даёт идиотский результат (единицу, то есть метод не отрабатывает)
    Аналогичное нехорошее поведение может повстречаться и при прочих сочетаниях. Этот момент должно иметь в виду

    :return:
    """

    global numnone
    global resultsOfEstimation
    # V=x[0] #напряжение на диоде
    # Is=b[0]
    # N=b[1]
    # R=b[2]
    FT = 0.02586419  # подогнанное по pspice

    dfdy = lambda y, x, b, c=None: np.array(
        [[-1 - b[0] * b[2] * math.exp((-b[2] * y[0] + x[0]) / (FT * b[1])) / (FT * b[1])]]
    )
    # function=lambda y,x,b,c=None: [b[0]*(math.exp((x[0]-y[0]*b[2])/(FT*b[1])) -1)-y[0]] #в подготовленном для взятия производной виде

    function = lambda y: func(y, x, b, c)

    solvinit = [1]

    #    solx=optimize.root(function, solvinit, args=(x,b,c), jac=dfdy, method='lm').x

    try:
        solx = [mpm.findroot(function, solvinit, verify=False, solver="secant", verbose=False)]
    except BaseException as e:
        print("Error in findroot=", e)
        return None

    # if solx-solvinit==[0]*len(solx):
    #     numnone+=1
    #     return None

    return solx
示例#49
0
def getGrowthNakata(ky_list, Setup, init = -0.07 -.015j):
  
  results = []
  
  eta_e     = Setup['eta_e']
  kx        = Setup['kx']
  v_te      = Setup['v_te']
  rho_te2   = Setup['rho_te2']
  tau       = Setup['tau']
  theta     = Setup['theta']

  for ky in ky_list:
    
    kp  = mp.sqrt(2.) * theta * ky 
    # Dispersion Relation Equation (9)
    if ky > 2.5 : init = 0.01 - 0.01j
    def DispersionRelation(w):
        ko2 = kx**2 + ky**2
        def Lambda(b): return mp.exp(b) * (1. + tau - Gamma0(b))
        #def Lambda(b): return mp.exp(b) * (tau + b/(1.+b))
      
        #zeta = w / (kp * v_te)
        zeta = w / (kp * v_te)
        w_star_e = ky * pylab.sqrt(rho_te2) * v_te
 
        # Take care of extra pie due to normalization
        #return  1. + Lambda(ko2 * rho_te2) + zeta * Z(zeta) - ky/kp *  eta_e * zeta - ky/kp * ( eta_e * zeta**2 +\
        return  1. + Lambda(ko2 * rho_te2) + zeta * Z(zeta) - ky/kp *  eta_e * zeta - ky/kp * ( eta_e * zeta**2 +\
                    (1. - eta_e/2. * (1. + ko2 * rho_te2)))*Z(zeta) * mp.sqrt(mp.pi)
                    #(1. - eta_e/2. * (1. + ko2 * rho_te2)))*Z(zeta) 

    try:
        omega = complex(mp.findroot(DispersionRelation, init, solver='muller', maxsteps=1000))
        #omega = complex(PT.zermuller(DispersionRelation, 0., -0.2 - 0.05j, dx=.001)[0])

    except:
        omega = .0
        print "Not found : ", ky,  "  Theta : ", theta
    results.append(float(pylab.real(omega))  + 1.j * pylab.imag(omega))

  return (pylab.array(ky_list), pylab.array(results))
示例#50
0
def _mpmath_kraft_burrows_nousek(N, B, CL):
    '''Upper limit on a poisson count rate

    The implementation is based on Kraft, Burrows and Nousek in
    `ApJ 374, 344 (1991) <http://adsabs.harvard.edu/abs/1991ApJ...374..344K>`_.
    The XMM-Newton upper limit server used the same formalism.

    Parameters
    ----------
    N : int
        Total observed count number
    B : float
        Background count rate (assumed to be known with negligible error
        from a large background area).
    CL : float
       Confidence level (number between 0 and 1)

    Returns
    -------
    S : source count limit

    Notes
    -----
    Requires the `mpmath <http://mpmath.org/>`_ library.  See
    `~astropy.stats.scipy_poisson_upper_limit` for an implementation
    that is based on scipy and evaluates faster, but runs only to about
    N = 100.
    '''
    from mpmath import mpf, factorial, findroot, fsum, power, exp, quad

    N = mpf(N)
    B = mpf(B)
    CL = mpf(CL)

    def eqn8(N, B):
        sumterms = [power(B, n) / factorial(n) for n in range(int(N) + 1)]
        return 1. / (exp(-B) * fsum(sumterms))

    eqn8_res = eqn8(N, B)
    factorial_N = factorial(N)

    def eqn7(S, N, B):
        SpB = S + B
        return eqn8_res * (exp(-SpB) * SpB**N / factorial_N)

    def eqn9_left(S_min, S_max, N, B):
        def eqn7NB(S):
            return eqn7(S, N, B)
        return quad(eqn7NB, [S_min, S_max])

    def find_s_min(S_max, N, B):
        '''
        Kraft, Burrows and Nousek suggest to integrate from N-B in both
        directions at once, so that S_min and S_max move similarly (see
        the article for details). Here, this is implemented differently:
        Treat S_max as the optimization parameters in func and then
        calculate the matching s_min that has has eqn7(S_max) =
        eqn7(S_min) here.
        '''
        y_S_max = eqn7(S_max, N, B)
        if eqn7(0, N, B) >= y_S_max:
            return 0.
        else:
            def eqn7ysmax(x):
                return eqn7(x, N, B) - y_S_max
            return findroot(eqn7ysmax, (N - B) / 2.)

    def func(s):
        s_min = find_s_min(s, N, B)
        out = eqn9_left(s_min, s, N, B)
        return out - CL

    S_max = findroot(func, N - B, tol=1e-4)
    S_min = find_s_min(S_max, N, B)
    return float(S_min), float(S_max)
示例#51
0
def solveDispersion(ky):

    L = zeros((Nx,Nx), dtype=complex)
    
    def setup_L(w):
        L[:,:] = 0.
        iCode.setupMatrixPy(species, w, ky, X, kx_list, Ls, Ln, Nx, L, dk*dx, lambda_D2)
        return L


    def solveEquation(w):

        w = complex(w)

        L = setup_L(w)
        
        # Get Minium absolute eigenvalue. 
        # 
        # The non-linear eigenvalue problem obeys 
        # det(L) = 0. This requirement is equal
        # to an eigenvalue 0 for the linear eigenvalue
        # problem det(L'- lambda I) = 0, which is identical
        # to the non-linear requirenement once lambda = 0.
        # 
        # [ This is less sensitive (and thus numerically less demanding) 
        # than caluculating directly the determinant
        
        
        val = getMinEigenvalue(L)

        #val = det(A)   
        #(sign, logdet) = np.linalg.slogdet(L)
        #val = sign * logdet

        print ky, " w   :  %.8f+%.8f j" % (real(complex(w)), imag(complex(w))) ,  "  Determinant : %.2e " %  abs(val)

        return val	
    
    try :
            #omega = complex(mp.findroot(solveEquation, (w0, w0+0.05, w0-0.005j), solver='muller', tol=1.e-15, ftol=1.e-15, maxsteps=5000))
            omega = complex(mp.findroot(solveEquation, (w0, w0-0.01, w0+0.001j), solver='muller', tol=1.e-15, ftol=1.e-15, maxsteps=5000))
    except:
            return float('nan') + 1.j * float('nan')
            #traceback.print_exc(file=sys.stdout)
    try:
        # n = 0
        
        # solution found for w0, get solution vector
        werr = solveEquation(omega)
        
        L = setup_L(omega)

        # We found our eigenvalue omega, now we use the
        # inverse iteration to find the closest eigenvector
        # to the eigenvalue
        L__lambda_I = L - omega * eye(Nx)

        # Start with random inital eigenvector
        b = 1. * rand(Nx) + 1.j * rand(Nx)

        # Convergence is fast thus large iteration number not required
        # However, how to best check the error ? 
        # e.g. A dot phi
        # Tested also, Rayleigh-Quotient Iteration but less successfull.
        for n in range(128):

            # rescale b
            b = b/real(sqrt(vdot(b,b)))
            # inverse iteration 
            b = solve(L__lambda_I, b)

            # calculate error
            r = dot(L,b)
            residual = real(sqrt(vdot(r,r)))
            print("I-I Residual : %.2e " % residual )
            if (residual < 1.e-9) : break
       
        clf()
        
        fig = gkcStyle.newFigure(ratio='1.41:1', basesize=9)
        
        
        fig.suptitle("$\omega_0$ = %.4f %.4fi  $\pm$ %.2e %.2e i" % (real(omega), imag(omega), real(werr), imag(werr)))
        
        ###################### Plot Fourier Modes ##########3
        plot(kx_list, real(b), 'r.-', label="real")
        plot(kx_list, imag(b),  '.-', label="imag", color=gkcStyle.color_indigo)
        
        xlim((min(kx_list), max(kx_list))) 

        xlabel("$k_x$")
        ylabel("$\phi(k_x)$")
        legend(ncol=2).draw_frame(0)
        
        savefig(str(ky) + "_Plot1.pdf", bbox_inches='tight')
        ################### Plot real modes ########3
        clf()

        # We have to transform to FFTW format, which has
        # form of [ k=0, k=1, ..., k = N/2, k = -(N/2-1), ..., k=-1 ] 
        F = append(append(b[Nx/2], b[Nx/2+1:]), b[:Nx/2])
        K = np.fft.ifft(F)
        K = append(append(K[Nx/2], K[Nx/2+1:]), K[:Nx/2])


        # Correct for phase
        K = K * exp(-1.j*arctan2(imag(sum(K)),real(sum(K))))
        #print " Phase : " , arctan2(imag(sum(K)),real(sum(K)))

        #F_list = append(append(kx_list[Nx/2], kx_list[Nx/2+1:]), kx_list[:Nx/2])
        #print "fft kx_list -----------> " , F_list
        
        plot(X, real(K), 'r.-', label='real')
        plot(X, imag(K),  '.-', label='imag', color=gkcStyle.color_indigo)
        plot(X,  abs(K),  'g-', label='abs', linewidth=5., alpha=0.5)
        
        xlim((min(X), max(X)))

        xlabel("$x$")
        ylabel("$\phi(x)$")
        legend(ncol=2).draw_frame(0)
        
        savefig(str(ky) + "_Plot2.pdf", bbox_inches='tight')
        ################ Plot Contour
        clf()
        y = linspace(0., Ly, 512)
        KxKy = zeros((Nx, 65), dtype=complex)
        nky = ky * Ly / (2.*pi)
        KxKy[:,nky] = K
        #np.fft.ifft(F)
        XY = np.fft.irfft(KxKy, axis=1, n=512)
        
        xlabel("$x$")
        ylabel("$y$")
        contourf(X, y, XY.T, 20, vmin=-abs(XY).max(), vmax=abs(XY).max())
        #contourf(X, y, XY.T, 20, vmin=-abs(XY).max(), vmax=abs(XY).max())
        colorbar()
        
        savefig(str(ky) + "_Plot3.pdf", bbox_inches='tight')

        # append and normalize
        sol.append(np.fft.ifft(b/abs(b).max()))
    except:
          traceback.print_exc(file=sys.stdout)
    return omega
示例#52
0
def comp_N_m_mp(obs_rates, t, merge_threshold, useMigration):
    """This function estimates the N and m parameters for the various time slices. The 
    time slices are given in a vector form 't'. t specifies the length of the time slice, not
    the time from present to end of time slice (not cumulative but atomic)
    Also, the obs_rates are given, for each time slice are given in columns of the obs_rates
    matrix. Both obs_rates and time slice lengths are given from present to past.
    """
    FTOL = 10.0
    PTOL = 1e-20
    EPSILON = 1e-11
    RESTARTS = 10
    FLIMIT = 1e-20
    numslices = len(t)
    nr = obs_rates.rows + 1
    numdemes = int(np.real(np.sqrt(8 * nr - 7)) / 2)
    print 'Starting iterations'
    P0 = mp.eye(nr)
    xopts = []
    pdlist = []
    for i in xrange(numslices):
        bestxopt = None
        bestfval = 1e+200
        print 'Running for slice ', i
        if i > 0:
            x0 = xopt[0:nr - 1].copy()
            try:
                xopt = mp.findroot(lambda x: compute_Frob_norm_mig(x, t[i], obs_rates[:, i], P0, make_merged_pd(pdlist)), x0)
                fun = compute_Frob_norm_mig(xopt, t[i], obs_rates[:, i], P0, make_merged_pd(pdlist))
                bestxopt = xopt
                bestfval = fun
            except ValueError as e:
                print 'Error:', e.message

            for lll in xrange(numdemes * (numdemes - 1) / 2):
                x01 = x0[0:nr - 1].copy()
                x01[numdemes + lll] = 0.0099
                try:
                    xopt = mp.findroot(lambda x: compute_Frob_norm_mig(x, t[i], obs_rates[:, i], P0, make_merged_pd(pdlist)), x01)
                    fun = compute_Frob_norm_mig(xopt, t[i], obs_rates[:, i], P0, make_merged_pd(pdlist))
                    if fun < bestfval:
                        bestfval = fun
                        bestxopt = xopt
                except ValueError as e:
                    print 'Error:', e.message

        reestimate = True
        while reestimate:
            pdslice = make_merged_pd(pdlist)
            print 'pdslice:', pdslice
            N0_inv = np.random.uniform(5e-05, 0.001, numdemes)
            m0 = np.random.uniform(0.008, 0.001, numdemes * (numdemes - 1) / 2)
            x0 = [ mp.convert(rrr) for rrr in N0_inv ]
            for zz in range(len(m0)):
                x0.append(mp.convert(m0[zz]))

            lims = [(1e-15, 0.1)] * numdemes
            lims += [(1e-15, 0.1)] * (numdemes * (numdemes - 1) / 2)
            try:
                xopt = mp.findroot(lambda x: compute_Frob_norm_mig(x, t[i], obs_rates[:, i], P0, make_merged_pd(pdlist)), x0)
                fun = compute_Frob_norm_mig(xopt, t[i], obs_rates[:, i], P0, make_merged_pd(pdlist))
                if fun < bestfval:
                    bestfval = fun
                    bestxopt = xopt
            except ValueError as e:
                print 'Error:', e.message

            N0_inv = np.random.uniform(5e-05, 0.001, numdemes)
            m0 = np.random.uniform(1e-08, 0.001, numdemes * (numdemes - 1) / 2)
            x0 = [ mp.convert(rrr) for rrr in N0_inv ]
            for zz in range(len(m0)):
                x0.append(mp.convert(m0[zz]))

            nrestarts = 0
            try:
                xopt = mp.findroot(lambda x: compute_Frob_norm_mig(x, t[i], obs_rates[:, i], P0, make_merged_pd(pdlist)), x0)
                fun = compute_Frob_norm_mig(xopt, t[i], obs_rates[:, i], P0, make_merged_pd(pdlist))
                if fun < bestfval:
                    bestxopt = xopt
                    bestfval = fun
            except ValueError as e:
                print 'Error:', e.message

            print nrestarts
            while nrestarts < RESTARTS and bestfval > FLIMIT:
                N0_inv = np.random.uniform(5e-05, 0.001, numdemes)
                m0 = np.random.uniform(1e-08, 0.001, numdemes * (numdemes - 1) / 2)
                x0 = mp.zeros(len(N0_inv) + len(m0))
                for zz in range(len(N0_inv)):
                    x0[zz] = N0_inv[zz]

                for zz in range(len(m0)):
                    x0[zz + len(N0_inv)] = m0[i]

                try:
                    xopt = mp.findroot(lambda x: compute_Frob_norm_mig(x, t[i], obs_rates[:, i], P0, make_merged_pd(pdlist)), x0)
                    fun = compute_Frob_norm_mig(xopt, t[i], obs_rates[:, i], P0, make_merged_pd(pdlist))
                    if fun < bestfval:
                        bestfval = fun
                        bestxopt = xopt
                except ValueError as e:
                    print 'Error:', e.message

                print nrestarts
                nrestarts += 1

            print bestfval, i, bestxopt[0:numdemes], bestxopt[numdemes:]
            Ne_inv = bestxopt[0:numdemes]
            mtemp = bestxopt[numdemes:]
            popdict = find_pop_merges(Ne_inv, mtemp, t[i], P0, merge_threshold, useMigration)
            reestimate = False
            if len(popdict) < numdemes:
                print 'Merging populations and reestimating parameters:', popdict
                print bestxopt
                P0 = converge_pops(popdict, P0)
                reestimate = True
                pdlist.append(popdict)
                numdemes = len(popdict)
                nr = numdemes * (numdemes + 1) / 2 + 1
                lims[:] = []
                bestfval = 1e+200
                bestxopt = None
            else:
                modXopt = [ 1.0 / x for x in bestxopt[0:numdemes] ]
                cnt = 0
                for ii in xrange(numdemes):
                    for jj in xrange(ii + 1, numdemes):
                        modXopt.append(bestxopt[numdemes + cnt])
                        cnt = cnt + 1

                xopts.append(np.array(modXopt))
                Ne_inv = bestxopt[0:numdemes]
                mtemp = bestxopt[numdemes:]

        m = np.zeros((numdemes, numdemes))
        cnt = 0
        for ii in xrange(numdemes):
            for jj in xrange(ii + 1, numdemes):
                m[ii, jj] = m[jj, ii] = mtemp[cnt]
                cnt += 1

        Q = comp_pw_coal_cont(m, Ne_inv)
        P = expM(t[i] * Q)
        print 'est rates', i
        print np.real(P0 * P)[0:-1, -1]
        print 'obs rates', i
        print np.real(obs_rates[:, i])
        print 'Min func value', bestfval
        P0 = P0 * conv_scrambling_matrix(P)
        ist = raw_input('Waiting for input...')

    return (xopts, pdlist)
示例#53
0
def liquido2bruto_sem_inss(liq):
    func = lambda bruto: bruto_sem_inss2liquido(bruto) - liq
    return findroot(func, liq)
示例#54
0
if len(sys.argv) < 5:
  print "Not enough arguments"
else:
  t = int(sys.argv[1])
  a = float(sys.argv[2])
  V = float(sys.argv[3])
  start = complex(sys.argv[4])
  if len(sys.argv) == 6:
    end = float(sys.argv[5])
  
def denumWrap(k):
  return denum(k,a,V)
  
if t == 1:
  print mpm.findroot(denumWrap, start)
else:
  xs = []
  Ss_real = []
  Ss_imag = []
  if t == 2:
    k = start
    dk = (end-start.real) / POINTS
    for i in range(POINTS):
      xs.append(k.real)
      calValues(k, a, V, Ss_real, Ss_imag)
      k += dk
    name = "Analytical S matrix for Radial Well, V0="+str(V)+", a="+str(a)+", k.imag="+str(k.imag)
    sp.plotSingle(name,xs,[Ss_real,Ss_imag],"k.real","",legends=["S.real","S.imag"],path="Results/"+name+".png")
  elif t == 3:
    k = start
from __future__ import print_function
from functools import partial

from mpmath import mp, mpf, findroot, nstr, log


def poly(x, n):
    power_of_2 = 1 << n
    x_mp = mpf(x)

    return x ** 3 - power_of_2 * x ** 2 + n


if __name__ == "__main__":

    f = poly
    mp.prec = 10000

    roots = [findroot(partial(f, n=n), float(2 ** n)) for n in range(1, 30 + 1)]
    a_pelo = [(1 << n) - n for n in range(1, 30 + 1)]

    for i, r in enumerate(roots):
        print(i + 1, nstr(r, 50), a_pelo[i])
示例#56
0
文件: SolveOK.py 项目: philscher/gkc
def solveDispersion(ky):
    A = zeros((Nx,Nx), dtype=complex)
    
    def setupA(w):
        A[:,:] = 0.

        iCode.setupMatrixPy(species, w, ky, X, kx_list, Ls, Ln, Nx, A, dk*dx, lambda_D2)
        return A


    def solveEquation(w):
        global D_min, w_min

        A = setupA(complex(w))
        #print A 
        #val = SlepcDet.getMinAbsEigenvalue(A)
        val = SlepcDet.getMinAbsEigenvaluLA(A)

        #val = det(A)   
        #(sign, logdet) = np.linalg.slogdet(A)
        #val = sign * logdet

        if abs(val) < abs(D_min) : w_min = complex(w) 

        print ky, " w   :  %.3f+%.3f j" % (real(complex(w)), imag(complex(w))) ,  "  Determinant : %.2e " %  abs(val)

        if val != val: return 0. + 0.j
        return val	
    
    try :
            w0=  -0.01 + 0.02j
            w_damp = complex(mp.findroot(solveEquation, (w0, w0-0.005j, w0+0.005), solver='muller', tol=1.e-8, ftol=1.e-8, maxsteps=5000))
            #w_damp = PyPPL.getZero(solveEquation, init=(w0, w0+0.01j, w0+0.02), solver='muller', tol=1.e-9, ftol=1.e-6, maxsteps=5000)
    except:
          traceback.print_exc(file=sys.stdout)
    try:
        #for n in range(Nx):
        n = 0
        global w_min
        print "-----------------> ", w_min
        
        # solution found for w0, get solution vector
        werr = solveEquation(w_min)
        A = setupA(w_min)

        #print A
        
    
        #S = solve(A, append(1.+0.j,zeros(Nx-1, dtype=complex)))
        #S = solve(A, append(1.+0.j, append(zeros(Nx-2, dtype=complex), 1.+0.j)))
        #b = append(0., append(1.+0., zeros(Nx-2, dtype=complex)))
        #b = zeros(Nx, dtype=complex)
        #b = ones(Nx, dtype=complex)
        #b[:] = 0. ; 
        #b[0] = 1.
        #S, err = solve(A, b), 0.
        #S, err = sla.lgmres(A,b, tol=1.e-9)

        # We found our eigenvalue w_min, now we use the
        # inverse iteration to find the closest eigenvector
  
        I = (1.+0.j) * eye(Nx)
        b = (1.+1.j) * ones(Nx, dtype=complex)

        for n in range(4096):
            b_prev = b
            b = solve(A - w_min * I, b)
            # RESCALE
            b  = b / sum(abs(b))
            if (abs(sum( sqrt(sum(b**2)/sum(b_prev**2))   * b_prev - b    )) < 1.e-10) : break
            #print("Eigv Error : %.2e Abs : %.2e " % (abs(sum( sqrt(sum(b**2)/sum(b_prev**2))   * b_prev - b    )), sum(abs(b))) )
         
        #print "Sol : " , b

        clf()
        
        gkcStyle.newFigure(ratio='2.33:1', basesize=12)
        
        subplot(131)
        fig.suptitle("$\omega_0$ = %.4f %.4fi  $\pm$ %.2e %.2e i" % (real(w_min), imag(w_min), real(werr), imag(werr)))
        
        ###################### Plot Fourier Modes ##########3
        b = -real(b) + 1.j * imag(b)
        plot(kx_list, real(b), 'r.-', label="real")
        plot(kx_list, imag(b),  '.-', label="imag", color=gkcStyle.color_indigo)
        xlim((min(kx_list), max(kx_list))) 

        xlabel("$k_x$")
        ylabel("$\phi(k_x)$")
        legend(ncol=2).draw_frame(0)
        
        ################### Plot real modes ########3
        subplot(132)
        
        # Remove High frequency modes
        #b[:3] = 0.;
        #b[-4:] = 0.;
        # We have to transform to FFTW format 
        F = append(append(b[Nx/2], b[Nx/2+1:]), b[:Nx/2])
        print "F--------------->", F 
        plot(X,real(np.fft.ifft(F)), 'r.-', label='real')
        plot(X,imag(np.fft.ifft(F)),  '.-', label='imag', color=gkcStyle.color_indigo)
        
        xlim((min(X), max(X)))
        xlabel("$x$")
        ylabel("$\phi(x)$")
        legend(ncol=2).draw_frame(0)
        
        ################ Plot Contour
        subplot(133)
        y = linspace(0., Ly, 128)
        KxKy = zeros((Nx, 65), dtype=complex)
        nky = ky * Ly / (2.*pi)
        KxKy[:,nky] = np.fft.ifft(F)
        XY = np.fft.irfft(KxKy, axis=1)
        
        xlabel("$x$")
        ylabel("$y$")
        contourf(X, y, XY.T, 20, vmin=-abs(XY).max(), vmax=abs(XY).max())
        colorbar()
        
        savefig("Plot2_" + str(ky) + ".png", bbox_inches='tight')

        # append and normalize
        sol.append(np.fft.ifft(b/abs(b).max()))
    except:
#species = [  Species(name= "Adiab"),   Species(m=1.,q=1.,T=1.,n=1.,eta=5., name="Ion"),  Species(m=0.0025,q=-1.,T=1.,n=1., eta=0., name="Electron") ]
          traceback.print_exc(file=sys.stdout)
    return w_min, abs(solveEquation(w_min))
示例#57
0
    def _eval_evalf(self, prec):
        """Evaluate this complex root to the given precision. """
        with workprec(prec):
            g = self.poly.gen
            if not g.is_Symbol:
                d = Dummy('x')
                func = lambdify(d, self.expr.subs(g, d))
            else:
                func = lambdify(g, self.expr)

            interval = self._get_interval()
            if not self.is_real:
                # For complex intervals, we need to keep refining until the
                # imaginary interval is disjunct with other roots, that is,
                # until both ends get refined.
                ay = interval.ay
                by = interval.by
                while interval.ay == ay or interval.by == by:
                    interval = interval.refine()

            while True:
                if self.is_real:
                    a = mpf(str(interval.a))
                    b = mpf(str(interval.b))
                    if a == b:
                        root = a
                        break
                    x0 = mpf(str(interval.center))
                else:
                    ax = mpf(str(interval.ax))
                    bx = mpf(str(interval.bx))
                    ay = mpf(str(interval.ay))
                    by = mpf(str(interval.by))
                    if ax == bx and ay == by:
                        # the sign of the imaginary part will be assigned
                        # according to the desired index using the fact that
                        # roots are sorted with negative imag parts coming
                        # before positive (and all imag roots coming after real
                        # roots)
                        deg = self.poly.degree()
                        i = self.index  # a positive attribute after creation
                        if (deg - i) % 2:
                            if ay < 0:
                                ay = -ay
                        else:
                            if ay > 0:
                                ay = -ay
                        root = mpc(ax, ay)
                        break
                    x0 = mpc(*map(str, interval.center))

                try:
                    root = findroot(func, x0)
                    # If the (real or complex) root is not in the 'interval',
                    # then keep refining the interval. This happens if findroot
                    # accidentally finds a different root outside of this
                    # interval because our initial estimate 'x0' was not close
                    # enough. It is also possible that the secant method will
                    # get trapped by a max/min in the interval; the root
                    # verification by findroot will raise a ValueError in this
                    # case and the interval will then be tightened -- and
                    # eventually the root will be found.
                    #
                    # It is also possible that findroot will not have any
                    # successful iterations to process (in which case it
                    # will fail to initialize a variable that is tested
                    # after the iterations and raise an UnboundLocalError).
                    if self.is_real:
                        if (a <= root <= b):
                            break
                    elif (ax <= root.real <= bx and ay <= root.imag <= by):
                        break
                except (UnboundLocalError, ValueError):
                    pass
                interval = interval.refine()

        return (Float._new(root.real._mpf_, prec)
                + I*Float._new(root.imag._mpf_, prec))
示例#58
0
    def eval_approx(self, n):
        """Evaluate this complex root to the given precision.

        This uses secant method and root bounds are used to both
        generate an initial guess and to check that the root
        returned is valid. If ever the method converges outside the
        root bounds, the bounds will be made smaller and updated.
        """
        prec = dps_to_prec(n)
        with workprec(prec):
            g = self.poly.gen
            if not g.is_Symbol:
                d = Dummy('x')
                if self.is_imaginary:
                    d *= I
                func = lambdify(d, self.expr.subs(g, d))
            else:
                expr = self.expr
                if self.is_imaginary:
                    expr = self.expr.subs(g, I*g)
                func = lambdify(g, expr)

            interval = self._get_interval()
            while True:
                if self.is_real:
                    a = mpf(str(interval.a))
                    b = mpf(str(interval.b))
                    if a == b:
                        root = a
                        break
                    x0 = mpf(str(interval.center))
                    x1 = x0 + mpf(str(interval.dx))/4
                elif self.is_imaginary:
                    a = mpf(str(interval.ay))
                    b = mpf(str(interval.by))
                    if a == b:
                        root = mpc(mpf('0'), a)
                        break
                    x0 = mpf(str(interval.center[1]))
                    x1 = x0 + mpf(str(interval.dy))/4
                else:
                    ax = mpf(str(interval.ax))
                    bx = mpf(str(interval.bx))
                    ay = mpf(str(interval.ay))
                    by = mpf(str(interval.by))
                    if ax == bx and ay == by:
                        root = mpc(ax, ay)
                        break
                    x0 = mpc(*map(str, interval.center))
                    x1 = x0 + mpc(*map(str, (interval.dx, interval.dy)))/4
                try:
                    # without a tolerance, this will return when (to within
                    # the given precision) x_i == x_{i-1}
                    root = findroot(func, (x0, x1))
                    # If the (real or complex) root is not in the 'interval',
                    # then keep refining the interval. This happens if findroot
                    # accidentally finds a different root outside of this
                    # interval because our initial estimate 'x0' was not close
                    # enough. It is also possible that the secant method will
                    # get trapped by a max/min in the interval; the root
                    # verification by findroot will raise a ValueError in this
                    # case and the interval will then be tightened -- and
                    # eventually the root will be found.
                    #
                    # It is also possible that findroot will not have any
                    # successful iterations to process (in which case it
                    # will fail to initialize a variable that is tested
                    # after the iterations and raise an UnboundLocalError).
                    if self.is_real or self.is_imaginary:
                        if not bool(root.imag) == self.is_real and (
                                a <= root <= b):
                            if self.is_imaginary:
                                root = mpc(mpf('0'), root.real)
                            break
                    elif (ax <= root.real <= bx and ay <= root.imag <= by):
                        break
                except (UnboundLocalError, ValueError):
                    pass
                interval = interval.refine()

        # update the interval so we at least (for this precision or
        # less) don't have much work to do to recompute the root
        self._set_interval(interval)
        return (Float._new(root.real._mpf_, prec) +
            I*Float._new(root.imag._mpf_, prec))
示例#59
0
f = simplify(pQ.pos_from(pP) & N.z)

print("f = {}\n".format(msprint(f)))

# calculate the derivative of f for use with Newton-Raphson
df = f.diff(theta)
print("df/dθ = {}\n".format(msprint(df)))

# constraint function for zero steer/lean configuration and
# using the benchmark parameters
f0 = lambdify(theta, f.subs({phi: 0, delta: 0}).subs(benchmark_parameters))
df0 = lambdify(theta, df.subs({phi: 0, delta: 0}).subs(benchmark_parameters))

print("verifying constraint equations are correct")
print("for zero steer/lean, pitch should be pi/10")
findroot(f0, 0.3, solver="newton", tol=1e-8, verbose=True, df=df0)

# convert to moore parameters
c_sym = symbols('x[1] pitch x[2] m_rr m_rf m_d1 m_d3 m_d2')
c_sym_dict = dict(zip([phi, theta, delta, rR, rF, cR, cF, ls], c_sym))

fc = ccode(f.subs(c_sym_dict))
dfc = ccode(df.subs(c_sym_dict))

cpp_math = {
    'cos': 'std::cos',
    'sin': 'std::sin',
    'pow': 'std::pow',
    'sqrt': 'std::sqrt',
}
示例#60
0
def bruto_sem_inss2bruto(bruto_sem_inss):
    func = lambda bruto: bruto - bruto_sem_inss - inss(bruto)
    return findroot(func, bruto_sem_inss)