Ejemplo n.º 1
0
def zcyl(n, Bi):
    try:
        Bi.ito("")
    except:
        pass
    if n == 1:
        lb = 0
        ub = 2.4
        return ridder(fcyl, lb, ub, args=(Bi, ))
    else:
        lb = 0.005 + (n - 1) * np.pi
        ub = 2.35 + (n - 1) * np.pi
        return ridder(fcyl, lb, ub, args=(Bi, ))
Ejemplo n.º 2
0
def zwal(n, Bi):
    try:
        Bi.ito("")
    except:
        pass
    if n == 1:
        lb = 0
        ub = (2 * n - 1) * np.pi / 2
        return ridder(fwal, lb, ub, args=(Bi, ))
    else:
        lb = (2 * n - 1) * np.pi / 2 - np.pi * 0.9999
        ub = (2 * n - 1) * np.pi / 2 * 0.9999
        return ridder(fwal, lb, ub, args=(Bi, ))
Ejemplo n.º 3
0
    def pressurizingSysMass(oxVol, methVol, disp=False):
        mtHe = []
        mHe = []
        vOut = (4 / 3) * np.pi * (d / 2)**3

        def volumeHe(pressHe):
            return (4 / 3) * np.pi * ((d / 2) * (1 - pressHe * 1.5 /
                                                 (2 * s_al)))**3

        def hePressure(press, ind):
            return pr[ind] * ((oxVol[ind] + methVol[ind]) +
                              volumeHe(press)) - press * volumeHe(press)

        for i in range(0, len(pc)):
            pHe = opt.ridder(hePressure, 10000, 100000000, args=i)
            vHe = volumeHe(pHe)
            mHe.append((vHe * pHe / (rHe * 300)) * 4)
            mtHe.append((vOut - vHe) * rho_al)
        if (disp):
            parameters.extend([
                "He Volume(l)", "He Pressure (MPA)", "He Tank Mass(kg)",
                "He Mass"
            ])
            values.extend([vHe, pHe, mtHe, mHe])
        return mtHe + mHe
Ejemplo n.º 4
0
def has_solution(interpolated_vec, t_last, t_current, alpha_obst):
    try:
        t = ridder(lambda t: interpolated_vec(t)[0][0] - alpha_obst, t_last,
                   t_current)
        return True, t
    except:
        return False, 0
Ejemplo n.º 5
0
    def find_friction(self):

        # Finds zeroes, X - friction velocity, Z - height, Karman's constant = 0.4
        z = 10
        f = lambda x: x / 0.4 * np.log(z /
                                       (0.684 / x + 428e-7 * x**2 - 443e-4))
        root = optimize.ridder(f, 1e-8, 80)
        return root
Ejemplo n.º 6
0
def zsph(n, Bi):
    try:
        Bi.ito("")
    except:
        pass
    lb = n * np.pi - 0.9999 * np.pi
    ub = n * np.pi * 0.9999
    return ridder(fsph, lb, ub, args=(Bi, ))
Ejemplo n.º 7
0
    def bsmRidder(self, a=-0.1, b=3):
        if self.f(a) * self.f(b) > 0:
            print('No root! Change the lower and upper value!\n')
            return self.sigma, np.nan

        for i in range(self.maxIter):
            if self.f(a) * self.f(b) < 0:
                return ridder(self.f, a, b, args=(), xtol=2e-12, rtol=8.8817841970012523e-16, maxiter=100, full_output=True, disp=True)
Ejemplo n.º 8
0
    def calcModesLoaded(self, f0, n_vec, N, C_j, C_0, C_s, E_c, E_j):
        # eq_even = lambda omega_l: -1020.0*np.sqrt(2)*C_s*omega_l*np.sqrt(E_c/(E_j*(-np.cos(np.pi*n/N) + 1)*(C_0/(2*C_j) - np.cos(np.pi*n/N) + 1))) - np.tan(np.pi*n*omega_l/(2*f0*np.sqrt((-np.cos(np.pi*n/N) + 1)/(C_0/(2*C_j) - np.cos(np.pi*n/N) + 1))))
        # eq_odd = lambda omega_l: -np.tan(np.pi*n*omega_l/(2*f0*np.sqrt((-np.cos(np.pi*n/N) + 1)/(C_0/(2*C_j) - np.cos(np.pi*n/N) + 1)))) + 0.000490196078431373*np.sqrt(2)/(C_s*omega_l*np.sqrt(E_c/(E_j*(-np.cos(np.pi*n/N) + 1)*(C_0/(2*C_j) - np.cos(np.pi*n/N) + 1))))

        sol = np.array([])
        eps = 1e2

        for n in n_vec:

            if n % 2 == 0:  # even numbers
                # eq = lambda w_l_num: eq_even_num(nn,N_num,C0_num,Cj_num,Cs_num,w0_num,Ec_num,Ej_num,w_l_num)
                eq = lambda omega_l: -1020.0 * np.sqrt(2) * C_s * omega_l * np.sqrt(
                    E_c / (E_j * (-np.cos(np.pi * n / N) + 1) * (C_0 / (2 * C_j) - np.cos(np.pi * n / N) + 1))
                ) - np.tan(
                    np.pi
                    * n
                    * omega_l
                    / (2 * f0 * np.sqrt((-np.cos(np.pi * n / N) + 1) / (C_0 / (2 * C_j) - np.cos(np.pi * n / N) + 1)))
                )
                sol = np.append(
                    sol, opt.ridder(eq, self.unloadedModes[n - 1] * (1 - 1 / n) + eps, self.unloadedModes[n - 1] - eps)
                )
            else:
                # eq = lambda w_l_num: eq_odd_num(nn,N_num,C0_num,Cj_num,Cs_num,w0_num,Ec_num,Ej_num,w_l_num)
                eq = lambda omega_l: -np.tan(
                    np.pi
                    * n
                    * omega_l
                    / (2 * f0 * np.sqrt((-np.cos(np.pi * n / N) + 1) / (C_0 / (2 * C_j) - np.cos(np.pi * n / N) + 1)))
                ) + 0.000490196078431373 * np.sqrt(2) / (
                    C_s
                    * omega_l
                    * np.sqrt(
                        E_c / (E_j * (-np.cos(np.pi * n / N) + 1) * (C_0 / (2 * C_j) - np.cos(np.pi * n / N) + 1))
                    )
                )
                if n == 1:
                    sol = np.append(sol, opt.ridder(eq, eps, self.unloadedModes[n - 1] - eps))
                else:
                    sol = np.append(
                        sol,
                        opt.ridder(eq, self.unloadedModes[n - 1] * (1 - 2 / n) + eps, self.unloadedModes[n - 1] - eps),
                    )

        return sol
Ejemplo n.º 9
0
def make_exponential_levels(dz_min, top, n_levels):
    level_rate = ridder(
        exponential_levels_error, 1.000000000000001, 2.0, args=(dz_min, top, n_levels)
    )
    level_list = [0.0]
    for level in range(1, n_levels):
        level_list = level_list + [
            dz_min * ((1.0 - level_rate ** level) / (1.0 - level_rate))
        ]
    level_list[n_levels - 1] = top
    return np.array(level_list)
Ejemplo n.º 10
0
 def flash_PVF_zs(self, P, VF, zs):
     try:
         # In some caases, will find a false root - resort to iterations which
         # are always between Pdew and Pbubble if this happens
         T = brenth(self._P_VF_err_2, min(self.Tms), min(self.Tcs), args=(P, VF, zs), maxiter=500)
         V_over_F, xs, ys = self._flash_sequential_substitution_TP(T=T, P=P, zs=zs)
         assert abs(V_over_F-VF) < 1E-6
     except:
         T = ridder(self._P_VF_err, min(self.Tms), min(self.Tcs), args=(P, VF, zs))
         V_over_F, xs, ys = self._flash_sequential_substitution_TP(T=T, P=P, zs=zs)
     return 'l/g', xs, ys, V_over_F, T
Ejemplo n.º 11
0
 def flash_PVF_zs(self, P, VF, zs):
     try:
         # In some caases, will find a false root - resort to iterations which
         # are always between Pdew and Pbubble if this happens
         T = brenth(self._P_VF_err_2, min(self.Tms), min(self.Tcs), args=(P, VF, zs), maxiter=500)
         V_over_F, xs, ys = self._flash_sequential_substitution_TP(T=T, P=P, zs=zs)
         assert abs(V_over_F-VF) < 1E-6
     except:
         T = ridder(self._P_VF_err, min(self.Tms), min(self.Tcs), args=(P, VF, zs))
         V_over_F, xs, ys = self._flash_sequential_substitution_TP(T=T, P=P, zs=zs)
     return 'l/g', xs, ys, V_over_F, T
Ejemplo n.º 12
0
 def __init__(self, unfold: lib.Unfolding, alpha):
     assert len(unfold.omegas) == 1
     assert alpha is None or len(alpha) == 1
     # ----
     self.aMax = alpha[0]
     self.unfold = unfold
     aMax = alpha[0]
     pMax = unfold.alpha_prob(alpha)
     # Calculate credible intervals for α
     self.ci1Sigma = (
         ridder(lambda x: unfold.alpha_prob([x]) - pMax + 0.5, aMax / 10,
                aMax),
         ridder(lambda x: unfold.alpha_prob([x]) - pMax + 0.5, aMax,
                aMax * 10),
     )
     self.ci2Sigma = (
         ridder(lambda x: unfold.alpha_prob([x]) - pMax + 2, aMax / 10,
                aMax),
         ridder(lambda x: unfold.alpha_prob([x]) - pMax + 2, aMax,
                aMax * 10),
     )
Ejemplo n.º 13
0
Archivo: mpb.py Proyecto: fesc3555/meep
    def test_point_defect_state(self):

        ms = self.init_solver()
        ms.geometry_lattice = mp.Lattice(size=mp.Vector3(5, 5))
        ms.geometry = [mp.Cylinder(0.2, material=mp.Medium(epsilon=12))]

        ms.geometry = mp.geometric_objects_lattice_duplicates(
            ms.geometry_lattice, ms.geometry)
        ms.geometry.append(mp.Cylinder(0.2, material=mp.air))

        ms.resolution = 16
        ms.k_points = [mp.Vector3(0.5, 0.5)]

        ms.num_bands = 50
        ms.run_tm()

        mpb.fix_efield_phase(ms, 25)
        mpb.output_efield_z(ms, 25)

        mpb.fix_dfield_phase(ms, 25)
        ms.get_dfield(25)
        ms.compute_field_energy()
        c = mp.Cylinder(1.0, material=mp.air)
        e = ms.compute_energy_in_objects([c])
        self.assertAlmostEqual(0.6227482574427817, e, places=3)

        ms.num_bands = 1
        ms.target_freq = (0.2812 + 0.4174) / 2
        ms.tolerance = 1e-8
        ms.run_tm()

        expected_brd = [
            ((0.37730041222979477, mp.Vector3(0.5, 0.5, 0.0)),
             (0.37730041222979477, mp.Vector3(0.5, 0.5, 0.0))),
        ]

        self.check_band_range_data(expected_brd, ms.band_range_data)

        old_geometry = ms.geometry  # save the 5x5 grid with a missing rod

        def rootfun(eps):
            ms.geometry = old_geometry + [
                mp.Cylinder(0.2, material=mp.Medium(epsilon=eps))
            ]
            ms.run_tm()
            return ms.get_freqs()[0] - 0.314159

        rooteps = ridder(rootfun, 1, 12)
        rootval = rootfun(rooteps)

        self.assertAlmostEqual(5.288830111797463, rooteps, places=3)
        self.assertAlmostEqual(9.300716530269426e-9, rootval, places=3)
Ejemplo n.º 14
0
def wavenumber(T, h):
    '''Returns wavelength given a period, depth of water,
    and two bounds on k. It should be noted that the bounds as a function of k
    less the angular frequency squared should be of different sign. The bounds
    are written inside this function and should be changed later.'''
    k_bound1 = 0
    k_bound2 = 20

    def _dispersion_k(k):
        return (g.magnitude * k * np.tanh(k * h) - (((2 * np.pi) / T))**2)

    root = optimize.ridder(_dispersion_k, k_bound1, k_bound2)
    return (root)
Ejemplo n.º 15
0
 def bsmRidder(self, a=1e-15, b=2):
     for i in range(self.maxIter):
         if self.f(a) * self.f(b) < 0:
             return ridder(self.f,
                           a,
                           b,
                           args=(),
                           xtol=2e-12,
                           rtol=8.8817841970012523e-16,
                           maxiter=100,
                           full_output=False,
                           disp=True)
         else:
             b -= 0.1
Ejemplo n.º 16
0
def choose_r(G=None):
    '''
    Find value of r that sets difference to zero between fraction of distribution on neighbors and non-neighbors to zero.
    Derived from Hotnet2.

    @parameter G - a graph

    @return G - a graph
    '''
    A = nx.to_numpy_array(G)
    r = ridder(lambda r: difference(A, r), a=0.01, b=0.99, xtol=0.001)

    G.graph['r'] = r
    return G
Ejemplo n.º 17
0
def find_ztran(zlist, klist, xps):
    ztran = []
    for k in range(len(klist)):
        this_xps = xps[:, k]

        xps_fn_z = interp1d(zlist, this_xps)
        try:
            sol = ridder(xps_fn_z, 9, 12.3)
        except:
            sol = np.nan
        this_ztran = float(sol)
        ztran.append(this_ztran)

    return klist, np.array(ztran)
Ejemplo n.º 18
0
def MMMallowTheta(ranks_cplt, median):
    """
    :return: the MLE theta parameter in Mallows distribution
    """
    Nsamp = len(ranks_cplt)
    Nclass = len(ranks_cplt[0])
    distances = [discordant(ranks_cplt[i], median) for i in range(Nsamp)]
    distances = np.array(distances, dtype=np.float16)
    dev = np.mean(distances)
    try:
        theta = ridder(MallowsThetaDev, 1e-5, 1e+5, args=(dev, Nclass))
        return theta
    except ValueError, e:
        print "!!!Not well chosen median"
        raise e
Ejemplo n.º 19
0
def calc_u_g(feh, g_r, u_g_range = [0.7, 1.7]):
    """
    Use relation from Bond et al 2010 to compute the expected u-g color given
    stellar metalicity and g-r color.
    # g-r in range 0.25 to 0.58
    """

    if np.size(feh) > 1:
        result = []
        for metal, color in zip(feh, g_r):
            func = sdss_metal(metal, color)
            try:
                u_g = ridder(func, u_g_range[0], u_g_range[1])
            except:
                u_g = np.nan
            result.append(u_g)
        result = np.array(result)
    else:
        func = sdss_metal(feh, g_r)
        try:
            result = ridder(func, u_g_range[0], u_g_range[1])
        except:
            result = np.nan
    return result
Ejemplo n.º 20
0
def _make_exponential_levels(dz_min, z_top, n_levels):
    """
    Makes exponentially distributed levels
    """
    if dz_min is None:
        raise Exception("For exponential levels `dz_min` must be a float")
    level_rate = ridder(
        exponential_levels_error, 1.000000000000001, 2.0, args=(dz_min, z_top, n_levels)
    )
    level_list = [0.0]
    for level in range(1, n_levels):
        level_list = level_list + [
            dz_min * ((1.0 - level_rate**level) / (1.0 - level_rate))
        ]
    level_list[n_levels - 1] = z_top
    return np.array(level_list)
Ejemplo n.º 21
0
    def identify_damping(self, w, verb=False):
        """
        Identify damping at circular frequency `w` (rad/s)

        """
        M = np.abs(self.morlet_integrate(self.n1, w)) /\
            np.abs(self.morlet_integrate(self.n2, w))
        if self._root_finding == "close":
            return self.n1 * self.n2 / 2 / np.pi /\
                np.sqrt(self.k * self.k * (self.n2 *\
                self.n2 - self.n1 * self.n1)) *\
                np.sqrt(np.log(np.sqrt(self.n1 / self.n2) * M))
        else:
            # eq (19):
            eqn = lambda x: np.exp(4 * np.pi**2 * self.k**2\
                * x**2 * (self.n2**2 -\
                self.n1**2) / self.n1**2 / self.n2**2) *\
                np.sqrt(self.n2 / self.n1) *\
                (erf(2 * np.pi * self.k * x / self.n1 +\
                            self.n1 / 4)\
                    -erf(2 * np.pi * self.k * x / self.n1 -\
                            self.n1 / 4)) /\
                (erf(2 * np.pi * self.k * x / self.n2 +\
                            self.n2 / 4)\
                    -erf(2 * np.pi * self.k * x / self.n2 -\
                            self.n2 / 4)) - M

            try:
                # dmp, r = newton(eqn, self.x0, maxiter=10, full_output=True, disp=False)
                dmp, r = ridder(eqn, self.x0[0], self.x0[1], xtol=1e-6, maxiter=10,\
                                full_output=True, disp=False)
                if not r.converged:
                    dmp = np.NaN
                    if verb:
                        print(
                            'Newton-Ralphson: maximum iterations limit reached!'
                        )
            except RuntimeWarning:
                if verb:
                    print('Newton-Ralphson raised Warning.')
            except ValueError:
                dmp = np.NaN

            return dmp
Ejemplo n.º 22
0
    def find_steady_state(self, a, b, method='brentq', **kwargs):
        """
        Compute the equilibrium value of capital stock (per unit
        effective labor).

        Parameters
        ----------
        a : float
            One end of the bracketing interval [a,b].
        b : float
            The other end of the bracketing interval [a,b]
        method : str (default=`brentq`)
            Method to use when computing the steady state. Supported
            methods are `bisect`, `brenth`, `brentq`, `ridder`. See
            `scipy.optimize` for more details (including references).
        kwargs : optional
            Additional keyword arguments. Keyword arguments are method
            specific see `scipy.optimize` for details.

        Returns
        -------
        x0 : float
            Zero of `f` between `a` and `b`.
        r : RootResults (present if ``full_output = True``)
            Object containing information about the convergence. In
            particular, ``r.converged`` is True if the routine
            converged.

        """
        if method == 'bisect':
            result = optimize.bisect(self.evaluate_k_dot, a, b, **kwargs)
        elif method == 'brenth':
            result = optimize.brenth(self.evaluate_k_dot, a, b, **kwargs)
        elif method == 'brentq':
            result = optimize.brentq(self.evaluate_k_dot, a, b, **kwargs)
        elif method == 'ridder':
            result = optimize.ridder(self.evaluate_k_dot, a, b, **kwargs)
        else:
            mesg = ("Method must be one of : 'bisect', 'brenth', 'brentq', " +
                    "or 'ridder'.")
            raise ValueError(mesg)

        return result
Ejemplo n.º 23
0
    def find_steady_state(self, a, b, method='brentq', **kwargs):
        """
        Compute the equilibrium value of capital stock (per unit
        effective labor).

        Parameters
        ----------
        a : float
            One end of the bracketing interval [a,b].
        b : float
            The other end of the bracketing interval [a,b]
        method : str (default=`brentq`)
            Method to use when computing the steady state. Supported
            methods are `bisect`, `brenth`, `brentq`, `ridder`. See
            `scipy.optimize` for more details (including references).
        kwargs : optional
            Additional keyword arguments. Keyword arguments are method
            specific see `scipy.optimize` for details.

        Returns
        -------
        x0 : float
            Zero of `f` between `a` and `b`.
        r : RootResults (present if ``full_output = True``)
            Object containing information about the convergence. In
            particular, ``r.converged`` is True if the routine
            converged.

        """
        if method == 'bisect':
            result = optimize.bisect(self.evaluate_k_dot, a, b, **kwargs)
        elif method == 'brenth':
            result = optimize.brenth(self.evaluate_k_dot, a, b, **kwargs)
        elif method == 'brentq':
            result = optimize.brentq(self.evaluate_k_dot, a, b, **kwargs)
        elif method == 'ridder':
            result = optimize.ridder(self.evaluate_k_dot, a, b, **kwargs)
        else:
            mesg = ("Method must be one of : 'bisect', 'brenth', 'brentq', " +
                    "or 'ridder'.")
            raise ValueError(mesg)

        return result
Ejemplo n.º 24
0
def graph(xmin, xmax):
    h = abs(xmin - xmax) / 100
    dx = 0.01

    xlist = mlab.frange(xmin, xmax, dx)
    ylist = [func(x) for x in xlist]

    x2 = []
    y2 = []
    x3 = []
    y3 = []
    x4 = [xmin, xmax]
    y4 = [func(xmin), func(xmax)]

    x = sym.Symbol('x')
    f = x**3 - 5 * x**2 + 6
    f_dif = sym.diff(f, x, 1)
    extr = sym.solve(f_dif, x)
    for k in extr:
        x2.append(float(k))
        y2.append(func(float(k)))
    f_2dif = sym.diff(f_dif, x, 1)
    peregib = sym.solve(f_2dif, x)
    for k in peregib:
        x3.append(float(k))
        y3.append(func(float(k)))

    rootsx = []
    rootscount = 0
    while xmin < xmax:
        if func(xmin) * func(xmin + h) < 0:
            rootsx.append(sp.ridder(func, xmin, xmin + h))
            rootscount += 1
        xmin += h

    pylab.plot(xlist, ylist)
    pylab.grid(True)
    pylab.plot(rootsx, [0] * rootscount, 'bo', label="Roots")
    pylab.plot(x2, y2, 'ro', label="Extrema")
    pylab.plot(x3, y3, 'go', label="Inflection points")
    pylab.plot(x4, y4, 'yo', label="min/max")
    pylab.legend()
    pylab.show()
    def find_values(self, func, method, **kwargs):
        """
        Provides an interface to the various methods for finding the root of 
        a univariate or multivariate function in scipy.optimize.
    
        Arguments:
            
            method:   (str) For univariate functions method must be one of: 
                      'brentq', 'brenth', 'ridder', 'bisect', or 'newton'; for
                      multivariate function method must be one of: 'hybr', 'lm',
                      'broyden1', 'broyden2', 'anderson', 'linearmixing', 
                      'diagbroyden', 'excitingmixing', 'krylov'.
            
            **kwargs: (dict) Dictionary of method specific keyword arguments.
        
        """
        # list of valid multivariate root-finding methods
        multivariate_methods = [
            'hybr', 'lm', 'broyden1', 'broyden2', 'anderson', 'linearmixing',
            'diagbroyden', 'excitingmixing', 'krylov'
        ]
        # univariate methods
        if method == 'brentq':
            res = optimize.brentq(func, args=self.model.args, **kwargs)
        elif method == 'brenth':
            res = optimize.brenth(func, args=self.model.args, **kwargs)
        elif method == 'ridder':
            res = optimize.ridder(func, args=self.model.args, **kwargs)
        elif method == 'bisect':
            res = optimize.bisect(func, args=self.model.args, **kwargs)
        elif method == 'newton':
            res = optimize.newton(func, args=self.model.args, **kwargs)

        # multivariate methods are handled by optimize.root
        elif method in multivariate_methods:
            res = optimize.root(func, args=self.model.args, **kwargs)
        else:
            raise ValueError, 'Unrecognized method!'

        return res
Ejemplo n.º 26
0
 def find_values(self, func, method, **kwargs):
     """
     Provides an interface to the various methods for finding the root of 
     a univariate or multivariate function in scipy.optimize.
 
     Arguments:
         
         method:   (str) For univariate functions method must be one of: 
                   'brentq', 'brenth', 'ridder', 'bisect', or 'newton'; for
                   multivariate function method must be one of: 'hybr', 'lm',
                   'broyden1', 'broyden2', 'anderson', 'linearmixing', 
                   'diagbroyden', 'excitingmixing', 'krylov'.
         
         **kwargs: (dict) Dictionary of method specific keyword arguments.
     
     """ 
     # list of valid multivariate root-finding methods
     multivariate_methods = ['hybr', 'lm', 'broyden1', 'broyden2', 
                             'anderson', 'linearmixing', 'diagbroyden', 
                             'excitingmixing', 'krylov']  
     # univariate methods     
     if method == 'brentq':
         res = optimize.brentq(func, args=self.model.args, **kwargs)
     elif method == 'brenth':
         res = optimize.brenth(func, args=self.model.args, **kwargs)
     elif method == 'ridder':
         res = optimize.ridder(func, args=self.model.args, **kwargs)
     elif method == 'bisect':
         res = optimize.bisect(func, args=self.model.args, **kwargs)
     elif method == 'newton':
         res = optimize.newton(func, args=self.model.args, **kwargs)
     
     # multivariate methods are handled by optimize.root
     elif method in multivariate_methods:
         res = optimize.root(func, args=self.model.args, **kwargs)
     else:
         raise ValueError, 'Unrecognized method!'
 
     return res
Ejemplo n.º 27
0
def segment_body(body, granularity=0.5):
    descs = []
    for xi, xf in zip(body.layer_boundaries[:-1], body.layer_boundaries[1:]):
        f_density = body.get_density(xf, right=True)
        gran = np.abs(f_density -
                      body.get_density(xi, right=False)) / body.get_density(
                          xi, right=False)
        if gran < granularity:  # the percent difference within a layer is small
            descs.append((xi, xf, body.get_average_density(0.5 * (xi + xf))))
        else:
            start = xi
            s_density = body.get_density(start, right=True)
            while np.abs(f_density - s_density) / s_density - granularity > 0:
                func = lambda x: np.abs(
                    body.get_density(x, right=True) - s_density
                ) / s_density - granularity
                end = ridder(func, start, xf)
                wrap = lambda x: body.get_density(x, right=True)
                I = quad(wrap, start, end, full_output=1)
                avg_density = I[0] / (end - start)
                descs.append((start, end, avg_density))
                start = end
                s_density = body.get_density(start)
    return descs
Ejemplo n.º 28
0
def _df_k2(k2, p, nu1, TOL):
    """
    Return `nu2` such that the integral of 
    F(nu1,nu2) from -infty to `x` is `p`
    
    `x` is k2**2 * nu2/ ( nu1*(nu2+1) )
    
    """

    # We have `k2` the integral limit, so `pf` gives us `p`
    # we must vary the `nu2` argument until the
    # returned value equals `p`.
    # `fdtr` returns the integral of F probability density from -infty to `x`
    def fn(nu2):
        x = k2**2 * nu2 / (nu1 * (nu2 + 1))
        # return pf(x,nu1,nu2) - p
        return special.fdtr(nu1, nu2, x) - p

    # dof here is nu2-1 and cannot be less than 2
    # This setting of `lo` is not a strict bound, because
    # the calculation will succeed, we just don't want to
    # go there.

    lo = 1 - 1E-3
    fn_lo = fn(lo)
    if fn_lo > 0.0:
        raise RuntimeError("dof < 2 cannot be calculated")

    upper_limit = (20, 50, 1E2, 1E3, inf_dof)
    for hi in upper_limit:
        if fn(hi) > 0.0:
            return optimize.ridder(fn, lo, hi)
        else:
            lo = hi

    return inf
def ridd(f):
    return opt.ridder(f, -2, 2)
Ejemplo n.º 30
0
from scipy import optimize


def f(x):
    return 2 * x**4 + 24 * x**3 + 61 * x**2 - 16 * x + 1


root1 = optimize.ridder(f, -9, -8)
root2 = optimize.ridder(f, -6, -4)
root3 = optimize.ridder(f, -1, 0.122)
root4 = optimize.ridder(f, 0.122, 1)

print(root1)
print(root2)
print(root3)
print(root4)
Ejemplo n.º 31
0
import scipy.optimize as sp
import numpy as np 

def f(x):
    return 2*x**4 + 24*x**3 + 61*x**2 - 16*x + 1

result = []

result.append(sp.ridder(f, -5, 8))
result.append(sp.ridder(f, -9, -6))

print(result)

# znalazłem 2 miejsca zerowe
Ejemplo n.º 32
0
    cur_data = data[datetime_start:cur_end]
    resampled_data = cur_data.resample(sample_size,how = 'mean',base = 0)
    resampled_data = resampled_data.interpolate()
    
    #### Solve for numerical value of time and displacement
    time_delta = resampled_data.index - resampled_data.index[0]
    t = map(lambda x: x/np.timedelta64(1,'D'),time_delta)
    x =np.array(resampled_data.meas.values)
    
    #### Solve for the interpolation function of resampled time series    
    f = interpolate.interp1d(t,x)
    
    #### Compute for t1, t2 and t3
    t1 = t[0]
    t3 = t[-1]
    t2 = optimize.ridder(lambda y:f(y)-0.5*(f(t1)+f(t3)),t1,t3)
    
    #### Compute for time to failure tr based from Saito (1979)
    tr = (t2**2.0 - t1*t3) / (2.0*t2 - (t1 + t3))
    
    rup_x.append(cur_data.meas.values[-1])
    rup_t.append(tr)

#Solve for t x for whole data
all_time_delta = data.index - data.index[0]
all_t = map(lambda x:  x/np.timedelta64(1,'D'),all_time_delta)
all_x = data.meas.values

#Plot the results

#Tableu 20 Colors
Ejemplo n.º 33
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
        j = 0
        while (self.ll_error > np.power(10.0, -7)):
            self.a_est = self.aMLE(self.total_failures, self.tn, self.brule[j],
                                   self.crule[j])
            self.arule.append(self.a_est)
            #print("Estimated a: {}".format(self.a_est))

            if j == 0:
                limits_b = self.MLElim(self.bMLE, self.brule[j],
                                       self.arule[j + 1], self.crule[j],
                                       self.tVec)
            else:
                #limits_b = self.MLElim(self.bMLE, self.brule[j], self.arule[j+1], self.crule[j], self.tVec)
                limits_b = [self.brule[j] / 2, self.brule[j] * 2]
            b_args = (self.arule[j + 1], self.crule[j], self.tVec)
            #self.b_est = root(self.bMLE, self.brule[j], b_args, method='krylov')
            self.b_est = ridder(self.bMLE, limits_b[0], limits_b[1], b_args)
            #print("Estimated b : {}".format(self.b_est))
            self.brule.append(self.b_est)

            c_args = (self.arule[j + 1], self.brule[j + 1], self.tVec)
            #self.c_est = fsolve(self.cMLE, self.crule[j], c_args)
            if j == 0:
                #print("j is 0 <-------------------------------------------------------------")
                limits = self.MLElim(self.cMLE, self.crule[j],
                                     self.arule[j + 1], self.brule[j + 1],
                                     self.tVec)
            else:
                #limits = self.MLElim(self.cMLE, self.crule[j], self.arule[j+1], self.brule[j+1], self.tVec)
                limits = [self.crule[j] / 2, self.crule[j] * 2]

            #print("c limits:")
            #print(limits)
            self.c_est = ridder(self.cMLE, limits[0], limits[1], c_args)
            #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))
            j += 1
            self.ll_error = self.ll_list[j] - self.ll_list[j - 1]
            self.ll_error_list.append(self.ll_error)
        print('Total iterations : {} '.format(j))
        print(self.ll_list[-1], self.arule[-1], self.brule[-1], self.crule[-1])
        return {
            'll': self.ll_list[-1],
            'a': self.arule[-1],
            'b': self.brule[-1],
            'c': self.crule[-1]
        }
Ejemplo n.º 34
0
global y
y = np.array([
    -0.5403, -0.0104, 0.9423, 1.7445, 1.3073, -0.7718, -2.4986, -0.7903, 2.7334
])

global cs
cs = CubicSpline(x, y)

plt.scatter(x, y)
x_range = np.arange(1, 3, 0.001)

plt.plot(x_range, cs(x_range), label='f(x)')
plt.plot(x_range, cs(x_range, 1), label="f'(x)")

result = f_prim(2.1, cs)
print(f"y'(2.1)= {result}")

root_list = [
    o.ridder(f, 1.2, 1.3),
    o.ridder(f, 2.1, 2.2),
    o.ridder(f, 2.8, 2.9)
]

print(f"Miejsca zerowe funkcji f(x): {root_list}")

plt.scatter(2.1, result, label='f\'(2.1)')
plt.scatter(root_list, np.zeros(len(root_list)), label='f(x)=0')
plt.legend()
plt.grid()
plt.show()
Ejemplo n.º 35
0
 def get_a(self, u , qf, qy, Ef, Lf, Af, phi, z, k, l):
     return ridder(self.u_a_residuum, 1e-12, self.get_umax[1], args = (u, qf, qy, Ef, Lf, Af, phi, z, k, l))
Ejemplo n.º 36
0
def getTheta(x):
    return [optimize.ridder(lambda x: 1. / 8. * (x - np.sin(x)) - xi, 0, 2 * np.pi) for xi in x]
Ejemplo n.º 37
0
ms.compute_field_energy()  # compute the energy density from D
c = mp.Cylinder(1.0, material=mp.air)
print("energy in cylinder: {}".format(ms.compute_energy_in_objects([c])))

print_heading('5x5 point defect, targeted solver')

ms.num_bands = 1  # only need to compute a single band, now!
ms.target_freq = (0.2812 + 0.4174) / 2
ms.tolerance = 1e-8
ms.run_tm()

# Tuning the Point-defect Mode

print_heading('Tuning the 5x5 point defect')

old_geometry = ms.geometry  # save the 5x5 grid with a missing rod


def rootfun(eps):
    # add the cylinder of epsilon = eps to the old geometry:
    ms.geometry = old_geometry + [mp.Cylinder(0.2, material=mp.Medium(epsilon=eps))]
    ms.run_tm()  # solve for the mode (using the targeted solver)
    print("epsilon = {} gives freq. =  {}".format(eps, ms.get_freqs()[0]))
    return ms.get_freqs()[0] - 0.314159  # return 1st band freq. - 0.314159

rooteps = ridder(rootfun, 1, 12)
print("root (value of epsilon) is at: {}".format(rooteps))

rootval = rootfun(rooteps)
print("root function at {} = {}".format(rooteps, rootval))
Ejemplo n.º 38
0
print_heading('5x5 point defect, targeted solver')

ms.num_bands = 1  # only need to compute a single band, now!
ms.target_freq = (0.2812 + 0.4174) / 2
ms.tolerance = 1e-8
ms.run_tm()

# Tuning the Point-defect Mode

print_heading('Tuning the 5x5 point defect')

old_geometry = ms.geometry  # save the 5x5 grid with a missing rod


def rootfun(eps):
    # add the cylinder of epsilon = eps to the old geometry:
    ms.geometry = old_geometry + [
        mp.Cylinder(0.2, material=mp.Medium(epsilon=eps))
    ]
    ms.run_tm()  # solve for the mode (using the targeted solver)
    print("epsilon = {} gives freq. =  {}".format(eps, ms.get_freqs()[0]))
    return ms.get_freqs()[0] - 0.314159  # return 1st band freq. - 0.314159


rooteps = ridder(rootfun, 1, 12)
print("root (value of epsilon) is at: {}".format(rooteps))

rootval = rootfun(rooteps)
print("root function at {} = {}".format(rooteps, rootval))
Ejemplo n.º 39
0
def main():
    pi = np.pi
    N = 20
    a1 = pi / 8.
    a2 = pi / 4.
    p1 = 1. / 3.
    p2 = 5. / 12.
    x = getChebNodes(N)
    ax1 = fA(x, p1, 0., a1)
    ax2 = fA(x, p2, a2, a1)
    theta1 = getTheta(ax1)
    theta2 = getTheta(ax2)
    phi1 = phi(theta1)
    phi2 = phi(theta2)
    fp1 = cheb.chebfit(x, phi1, N)
    fp2 = cheb.chebfit(x, phi2, N)
#	print fp1
#	print fp2
    print "Disagreement at pi/8 is %.15f" % (cheb.chebval(1, fp1) - cheb.chebval(1, fp2))
    phim1 = cheb.chebval(1, fp2)
    phim2 = cheb.chebval(-1, fp2)
#	print phim1;
#	print phim2;

    K = 4
    M = 3 * pow(2, K)
    M = 60
    K = 5
    alphas = np.array([i / float(M) for i in range(2 * K, M + 3)])
    Atrue1 = np.linspace(0, pi / 8., 200)
    Atrue2 = np.linspace(pi / 8., pi / 4., 200)
    phis1 = cheb.chebval(fX(Atrue1, p1, 0, a1), fp1)
    phis2 = cheb.chebval(fX(Atrue2, p2, a2, a1), fp2)
    #alphas = [1./3.]
#	print cheb.chebval(fX(0,p1,0,a1),fp1)
#	print cheb.chebval(fX(pi/8,p1,0,a1),fp1)-phim1
    r = np.zeros((len(alphas), 2))
    err = np.zeros((len(alphas), 2))
    for k in range(len(alphas)):
        p = alphas[k]
        sx1 = fA(x, p, 0, phim1)
        sx2 = fA(x, p, phim2, phim1)
        A1 = np.zeros(len(sx1))
        A2 = np.zeros(len(sx1))
    #	print "p = %f" %p
    #	print sx1
    #	print sx2
        for i in range(1, len(sx1) - 1):
            A1[i] = optimize.ridder(
                lambda x: -cheb.chebval(fX(x, p1, 0, a1), fp1) + sx1[i], 0, pi / 8. + .1)
        A1[-1] = pi / 8.
        A2 = [optimize.ridder(lambda x: cheb.chebval(
            fX(x, p2, a2, a1), fp2) - sxi, pi / 8., pi / 4.) for sxi in sx2]
    #	print A1
    #	print A2
        fa1 = cheb.chebfit(x, A1, N)
        fa2 = cheb.chebfit(x, A2, N)
    #	print fa1
    #	print fa2
        r[k, 0] = abs(fa1[-1])
        r[k, 1] = abs(fa2[-1])
        err[k, 0] = np.linalg.norm(
            Atrue1 - cheb.chebval(fX(phis1, p, 0, phim1), fa1))
        err[k, 1] = np.linalg.norm(
            Atrue2 - cheb.chebval(fX(phis2, p, phim2, phim1), fa2))
    print "alpha      r1      r2     err1      err2"
    for j in range(len(r)):
        print " %f   %e   %e   %e   %e" % (alphas[j], r[j, 0], r[j, 1], err[j, 0], err[j, 1])
    plt.rc('text', usetex=True)
    plt.rc('font', family='serif')

    plt.subplots_adjust(hspace=0.4)
    plt.subplot(211)
    plt.semilogy(alphas, r)
    plt.legend([r"$\phi^{-1}_1$", r"$\phi^{-1}_2$"])
    xlab = ['1/6', '1/4', '1/3', '2/5', '1/2', '3/5', '2/3', '3/4', '5/6', '1']
    ticks = [1. / 6., 1. / 4., 1. / 3., 2. / 5., 1. /
             2., 3. / 5., 2. / 3., 3. / 4., 5. / 6., 1.]
    plt.xticks(ticks, xlab)
    plt.grid(True)
    plt.title(r'$\phi^{-1}(x) \approx \sum_k a_k T_k(cx^{\alpha}-1)$')
    # plt.ylabel(r'a_N')
    plt.ylabel('coefficient decay')
    plt.xlabel(r'$\alpha$')
    plt.subplot(212)
    plt.xlabel(r'$\alpha$')
    plt.ylabel('Error')
    # plt.ylabel(r'$\phi^{-1}_i(x)-\tilde{\phi}_i^{-1}(x)$')
    plt.semilogy(alphas, err)
    plt.xticks(ticks, xlab)
    plt.grid(True)
    plt.title('Error')
    plt.legend([r"$\phi^{-1}_1$", r"$\phi^{-1}_2$"])
    # plt.show()
    p3 = 1.
    p4 = 3. / 5
    sx1 = fA(x, p3, 0, phim1)
    sx2 = fA(x, p4, phim2, phim1)
    A1 = np.zeros(len(sx1))
    A2 = np.zeros(len(sx1))
#	print sx1
#	print sx2
    for i in range(1, len(sx1) - 1):
        A1[i] = optimize.ridder(
            lambda x: -cheb.chebval(fX(x, p1, 0, a1), fp1) + sx1[i], 0, pi / 8. + .1)
    A1[-1] = pi / 8.
    A2 = [optimize.ridder(lambda x: cheb.chebval(
        fX(x, p2, a2, a1), fp2) - sxi, pi / 8., pi / 4.) for sxi in sx2]
#	print A1
#	print A2
    fa1 = cheb.chebfit(x, A1, N)
    fa2 = cheb.chebfit(x, A2, N)
#	print fa1
#	print fa2

    print "Power for phi1 is %f" % p1
    print "Power for phi2 is %f" % p2
    print "Power for phi1^(-1) is %f" % p3
    print "Power for phi2^(-1) is %f" % p4
    fnames = ["phiofA1.txt", "phiofA2.txt", "Aofphi1.txt", "Aofphi2.txt"]
    coeffs = np.zeros((N + 1, 4))
    coeffs[:, 0] = fp1
    coeffs[:, 1] = fp2
    coeffs[:, 2] = fa1
    coeffs[:, 3] = fa2
    for i in range(4):
        f = open(fnames[i], "w")
        for j in range(len(fa1)):
            f.write("%.16f, " % (coeffs[j, i]))
        f.close()
    for i in range(N + 1):
        print "%.16f,  " % x[i]
Ejemplo n.º 40
0
         funcionTestFourier(freqTest) / np.max(lineas),
         color='blue',
         label='interpolación Cuadrática')
plt.plot(freq, np.zeros_like(freq), color='black')
plt.legend(prop={'size': 13})
plt.savefig("fft" + element + " " + lineS, dpi=dpi, bbox_inches='tight')

A = trapz(y=linea, x=lambLinea)
beta = 2 * A / linea[lambLinea == 0] / np.pi
c = 299792458
vsiniMax = c * beta * 1e-3

#x = np.array([0.0345,0.096,freq[3]+3/4*(freq[4]-freq[3])])
x = np.array([recta(2), recta(4), recta(6)])  #se hace manualmente.
x = np.array([
    ridder(funcionTestFourier, freq[0], freq[2]),
    ridder(funcionTestFourier, freq[2], freq[3]),
    ridder(funcionTestFourier, freq[3], freq[5])
])  #se hace manualmente.
funcionTestFourier = interp1d(freq, lineas)

yAlta = np.array([3.832, 7.016, 10.174])
y = np.array([4.147, 7.303, 10.437])
from scipy.stats import linregress
from scipy.optimize import curve_fit

m, b, r, p, sigma = linregress(x, y)

plt.figure()
plt.scatter(x, y)
plt.plot(x, x * m + b)
Ejemplo n.º 41
0
                                             full_output=True,
                                             xtol=1e-12,
                                            )

root_brenth, result_brenth = optimize.brenth(numeric_foc, 
                                             a=eps, 
                                             b=1e3 - eps, 
                                             args=model_params,
                                             full_output=True,
                                             xtol=1e-12,
                                            )

root_ridder, result_ridder = optimize.ridder(numeric_foc, 
                                             a=eps, 
                                             b=1e3 - eps, 
                                             args=model_params,
                                             full_output=True,
                                             xtol=1e-12,
                                            )

root_bisect, result_bisect = optimize.bisect(numeric_foc, 
                                             a=eps, 
                                             b=1e3 - eps, 
                                             args=model_params,
                                             full_output=True,
                                             xtol=1e-12,
                                            )

# newton is more efficient, but convergence not guaranteed!
root_newton = optimize.newton(numeric_foc, 
                              x0=5e2,