当前位置: 首页>>代码示例>>Python>>正文


Python optimize.brentq方法代码示例

本文整理汇总了Python中scipy.optimize.brentq方法的典型用法代码示例。如果您正苦于以下问题:Python optimize.brentq方法的具体用法?Python optimize.brentq怎么用?Python optimize.brentq使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在scipy.optimize的用法示例。


在下文中一共展示了optimize.brentq方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: p_o2_calc

# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import brentq [as 别名]
def p_o2_calc(delta, dh_1, dh_2, temp, act):
    """
    Calculates the oxygen partial pressure p_O2 of a perovskite solid solution with two redox-active species
    :param delta:   non-stoichiometry delta
    :param dh_1:    reaction enthalpy of perovskite 1
    :param dh_2:    reaction enthalpy of perovskite 2
    :param temp:    temperature in K
    :return:        p_O2 as absolute value
    """

    def fun_p_o2(p_o2):
        return delta_mix(temp, p_o2, dh_1, dh_2, act) - delta

    try:
        sol_p_o2_l = brentq(fun_p_o2, a=-100, b=100)
    except ValueError:
        sol_p_o2_l = brentq(fun_p_o2, a=-300, b=300)

    return pd.np.exp(sol_p_o2_l) 
开发者ID:materialsproject,项目名称:MPContribs,代码行数:21,代码来源:views.py

示例2: validate_on_lfw

# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import brentq [as 别名]
def validate_on_lfw(model, lfw_160_path):
    # Read the file containing the pairs used for testing
    pairs = lfw.read_pairs('validation-LFW-pairs.txt')
    # Get the paths for the corresponding images
    paths, actual_issame = lfw.get_paths(lfw_160_path, pairs)
    num_pairs = len(actual_issame)

    all_embeddings = np.zeros((num_pairs * 2, 512), dtype='float32')
    for k in tqdm.trange(num_pairs):
        img1 = cv2.imread(paths[k * 2], cv2.IMREAD_COLOR)[:, :, ::-1]
        img2 = cv2.imread(paths[k * 2 + 1], cv2.IMREAD_COLOR)[:, :, ::-1]
        batch = np.stack([img1, img2], axis=0)
        embeddings = model.eval_embeddings(batch)
        all_embeddings[k * 2: k * 2 + 2, :] = embeddings

    tpr, fpr, accuracy, val, val_std, far = lfw.evaluate(
        all_embeddings, actual_issame, distance_metric=1, subtract_mean=True)

    print('Accuracy: %2.5f+-%2.5f' % (np.mean(accuracy), np.std(accuracy)))
    print('Validation rate: %2.5f+-%2.5f @ FAR=%2.5f' % (val, val_std, far))

    auc = metrics.auc(fpr, tpr)
    print('Area Under Curve (AUC): %1.3f' % auc)
    eer = brentq(lambda x: 1. - x - interpolate.interp1d(fpr, tpr)(x), 0., 1.)
    print('Equal Error Rate (EER): %1.3f' % eer) 
开发者ID:ppwwyyxx,项目名称:Adversarial-Face-Attack,代码行数:27,代码来源:face_attack.py

示例3: _ppf_single

# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import brentq [as 别名]
def _ppf_single(self, q, *args):
        left = right = None
        if self.a > -np.inf:
            left = self.a
        if self.b < np.inf:
            right = self.b

        factor = 10.
        if not left:  # i.e. self.a = -inf
            left = -1.*factor
            while self._ppf_to_solve(left, q, *args) > 0.:
                right = left
                left *= factor
            # left is now such that cdf(left) < q
        if not right:  # i.e. self.b = inf
            right = factor
            while self._ppf_to_solve(right, q, *args) < 0.:
                left = right
                right *= factor
            # right is now such that cdf(right) > q

        return optimize.brentq(self._ppf_to_solve,
                               left, right, args=(q,)+args, xtol=self.xtol)

    # moment from definition 
开发者ID:ryfeus,项目名称:lambda-packs,代码行数:27,代码来源:_distn_infrastructure.py

示例4: _solve_effect_size

# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import brentq [as 别名]
def _solve_effect_size(self, effect_size=None, nobs=None, alpha=None,
                           power=None, k_groups=2):
        '''experimental, test failure in solve_power for effect_size
        '''
        def func(x):
            effect_size = x
            return self._power_identity(effect_size=effect_size,
                                          nobs=nobs,
                                          alpha=alpha,
                                          k_groups=k_groups,
                                          power=power)

        val, r = optimize.brentq(func, 1e-8, 1-1e-8, full_output=True)
        if not r.converged:
            print(r)
        return val 
开发者ID:birforce,项目名称:vnpy_crypto,代码行数:18,代码来源:power.py

示例5: solve_equilibrium

# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import brentq [as 别名]
def solve_equilibrium(c0, stoich, K, activity_product=None):
    """
    Solve equilibrium concentrations by using scipy.optimize.brentq

    Parameters
    ----------
    c0: array_like
        Initial guess of equilibrium concentrations
    stoich: tuple
        per specie stoichiometry coefficient (law of mass action)
    K: float
        equilibrium constant
    activity_product: callable
        see ``equilibrium_residual``
    delta_frac: float
        to avoid division by zero the span of searched values for
        the reactions coordinate (rc) is shrunk by 2*delta_frac*span(rc)
    """
    stoich = np.array(stoich)
    c0 = np.array(c0)
    rc = _solve_equilibrium_coord(c0, stoich, K, activity_product)
    return c0 + rc*stoich 
开发者ID:bjodah,项目名称:chempy,代码行数:24,代码来源:_equilibrium.py

示例6: rootfind

# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import brentq [as 别名]
def rootfind(a, b, args, funciso_here):
    solutioniso = 0
    try:
        solutioniso = brentq(
            funciso_here, 0.01, 0.49, args=args
        )  # works for most cases
    except ValueError:  # starting values a,b for cases where 0.01/0.49 are not sign changing
        try:
            solutioniso = brentq(funciso_here, a, b, args=args)
        except ValueError:
            solutioniso = None  # if no solution can be found
    return solutioniso 
开发者ID:materialsproject,项目名称:MPContribs,代码行数:14,代码来源:views.py

示例7: compute_eer

# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import brentq [as 别名]
def compute_eer(y_true, y_pred):
    fpr, tpr, _ = roc_curve(y_true, y_pred, pos_label=1)
    eer = brentq(lambda x : 1. - x - interp1d(fpr, tpr)(x), 0., 1)
    
    return 100. * eer 
开发者ID:jefflai108,项目名称:Attentive-Filtering-Network,代码行数:7,代码来源:v1_metrics.py

示例8: roc

# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import brentq [as 别名]
def roc(labels, scores, saveto=None):
    """Compute ROC curve and ROC area for each class"""
    fpr = dict()
    tpr = dict()
    roc_auc = dict()

    labels = labels.cpu()
    scores = scores.cpu()

    # True/False Positive Rates.
    fpr, tpr, _ = roc_curve(labels, scores)
    roc_auc = auc(fpr, tpr)

    # Equal Error Rate
    eer = brentq(lambda x: 1. - x - interp1d(fpr, tpr)(x), 0., 1.)

    if saveto:
        plt.figure()
        lw = 2
        plt.plot(fpr, tpr, color='darkorange', lw=lw, label='(AUC = %0.2f, EER = %0.2f)' % (roc_auc, eer))
        plt.plot([eer], [1-eer], marker='o', markersize=5, color="navy")
        plt.plot([0, 1], [1, 0], color='navy', lw=1, linestyle=':')
        plt.xlim([0.0, 1.0])
        plt.ylim([0.0, 1.05])
        plt.xlabel('False Positive Rate')
        plt.ylabel('True Positive Rate')
        plt.title('Receiver operating characteristic')
        plt.legend(loc="lower right")
        plt.savefig(os.path.join(saveto, "ROC.pdf"))
        plt.close()

    return roc_auc 
开发者ID:samet-akcay,项目名称:ganomaly,代码行数:34,代码来源:evaluate.py

示例9: Jn_zeros

# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import brentq [as 别名]
def Jn_zeros(n, k):
    zerosj = np.zeros((n, k), dtype='float32')
    zerosj[0] = np.arange(1, k + 1) * np.pi
    points = np.arange(1, k + n) * np.pi
    racines = np.zeros(k + n - 1, dtype='float32')
    for i in range(1, n):
        for j in range(k + n - 1 - i):
            foo = brentq(Jn, points[j], points[j + 1], (i, ))
            racines[j] = foo
        points = racines
        zerosj[i][:k] = racines[:k]

    return zerosj 
开发者ID:rusty1s,项目名称:pytorch_geometric,代码行数:15,代码来源:dimenet_utils.py

示例10: isentrope

# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import brentq [as 别名]
def isentrope(rock, pressures, entropy, T_guess):
    def _deltaS(T, S, P, rock):
        rock.set_state(P, T)
        return rock.S - S

    sol = T_guess
    temperatures = np.empty_like(pressures)
    for i, P in enumerate(pressures):
        sol = brentq(_deltaS, rock.bounds[1][0], rock.bounds[1][1], args=(entropy, P, rock))
        temperatures[i] = sol

    return temperatures

# Define function to find an isentrope given a
# 2D entropy interpolation function 
开发者ID:geodynamics,项目名称:burnman,代码行数:17,代码来源:example_geodynamic_adiabat.py

示例11: volume

# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import brentq [as 别名]
def volume(self, pressure, temperature, params):
        """
        Returns molar volume. :math:`[m^3]`
        """
        T_0 = params['T_0']
        Debye_0 = params['Debye_0']
        V_0 = params['V_0']
        n = params['n']

        a1_ii = 6. * params['grueneisen_0']  # EQ 47
        a2_iikk = -12. * params['grueneisen_0'] + 36. * pow(
            params['grueneisen_0'], 2.) - 18. * params['q_0'] * params['grueneisen_0']  # EQ 47

        b_iikk = 9. * params['K_0']  # EQ 28
        b_iikkmm = 27. * params['K_0'] * (params['Kprime_0'] - 4.)  # EQ 29z

        # we need to have a sign change in [a,b] to find a zero. Let us start with a
        # conservative guess:
        args = (pressure, temperature, V_0, T_0,
                Debye_0, n, a1_ii, a2_iikk, b_iikk, b_iikkmm)
        try:
            sol = bracket(_delta_pressure, params[
                          'V_0'], 1.e-2 * params['V_0'], args)
        except ValueError:
            raise Exception(
                'Cannot find a volume, perhaps you are outside of the range of validity for the equation of state?')
        return opt.brentq(_delta_pressure, sol[0], sol[1], args=args) 
开发者ID:geodynamics,项目名称:burnman,代码行数:29,代码来源:slb.py

示例12: volume

# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import brentq [as 别名]
def volume(self, pressure, temperature, params):
        _delta_pressure = lambda x, pressure, temperature, params: pressure - self.pressure(temperature, x, params)
        
        # we need to have a sign change in [a,b] to find a zero. Let us start with a
        # conservative guess:
        args = (pressure, temperature, params)
        try:
            sol = bracket(_delta_pressure, params['V_0'],
                          1.e-2 * params['V_0'], args)
        except ValueError:
            raise Exception(
                'Cannot find a volume, perhaps you are outside of the range of validity for the equation of state?')
        return opt.brentq(_delta_pressure, sol[0], sol[1], args=args) 
开发者ID:geodynamics,项目名称:burnman,代码行数:15,代码来源:dks_liquid.py

示例13: volume_fourth_order

# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import brentq [as 别名]
def volume_fourth_order(pressure, params):
    func = lambda x: birch_murnaghan_fourth(
        params['V_0'] / x, params) - pressure
    try:
        sol = bracket(func, params['V_0'], 1.e-2 * params['V_0'])
    except:
        raise ValueError(
            'Cannot find a volume, perhaps you are outside of the range of validity for the equation of state?')
    return opt.brentq(func, sol[0], sol[1]) 
开发者ID:geodynamics,项目名称:burnman,代码行数:11,代码来源:birch_murnaghan_4th.py

示例14: volume

# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import brentq [as 别名]
def volume(self, pressure, temperature, params):
        """
        Returns molar volume. :math:`[m^3]`
        """

        _volume = lambda V, P, T, params: ( P -
                                            self.pressure(T, V, params) )
        
        return brentq(_volume, params['V_0']*0.1, params['V_0']*2., args=(pressure, temperature, params)) 
开发者ID:geodynamics,项目名称:burnman,代码行数:11,代码来源:aa.py

示例15: pressure

# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import brentq [as 别名]
def pressure( self, temperature, volume, params):
        """
        Returns the pressure of the mineral at a given temperature and volume [Pa]
        """
        
        '''
        Ts = self._isentropic_temperature(volume, params)
        
        
        dE = self._isochoric_energy_change(Ts, temperature, volume, params)
        E1 = self._isentropic_energy_change(volume, params) - params['E_0']
        E2 = E1 + dE

        # Integrate at constant volume (V \int dP = \int gr dE)
        dP = (params['grueneisen_0']*(E2 - E1) +
              (0.5*params['grueneisen_prime'] *
               np.power(params['V_0']/volume, params['grueneisen_n']) *
               (E2*E2 - E1*E1))) / volume # eq. 23

        P = self._isentropic_pressure(volume, params) + dP
        '''

        dV = volume*1.e-4
        S = self.entropy(0., temperature, volume, params)

        delta_S = lambda T, S, V: S - self.entropy(0., T, V, params)
        
        T0 = brentq(delta_S, temperature*0.97, temperature*1.03, args=(S, volume - 0.5*dV))
        T1 = brentq(delta_S, temperature*0.97, temperature*1.03, args=(S, volume + 0.5*dV))

        E0 = self.molar_internal_energy(0., T0, volume - 0.5*dV, params)
        E1 = self.molar_internal_energy(0., T1, volume + 0.5*dV, params)

        P = -(E1 - E0)/dV # |S
        
        return P 
开发者ID:geodynamics,项目名称:burnman,代码行数:38,代码来源:aa.py


注:本文中的scipy.optimize.brentq方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。