コード例 #1
0
 def solve(self):
   try:
       x_fp = anderson(self.rootOperator, self.x_0, maxiter = self.numberOfIterations, verbose=0, callback=self.iterationCounter, x_rtol=self.convergenceCriterion )
   except Exception as inst:
       print type(inst) #Typically interrupt or non-convergence
       return
   print "scipy Anderson converged after" , self.iterationStep, "steps"
   #As a side effect, we calculate other intersting physical quantities based on the found fixpoint solution
   self.derivePhysicalQuantitiesFromFixpoint(x_fp)
   #Reset iteration counter in case solve is called various times (and class is not re-instantiated)
   self.iterationStep = 0
コード例 #2
0
ファイル: solver.py プロジェクト: BasileGrassi/dynare-python
def solver(fobj, x0, lb=None, ub=None, options={}, method="lmmcp", jac="default", verbose=False):

    in_shape = x0.shape

    ffobj = lambda x: fobj(x.reshape(in_shape)).flatten()

    if not isinstance(jac, str):
        pp = np.prod(in_shape)

        def Dffobj(t):
            tt = t.reshape(in_shape)
            dval = jac(tt)
            return dval.reshape((pp, pp))

    elif jac == "precise":
        from numdifftools import Jacobian

        Dffobj = Jacobian(ffobj)
    else:
        Dffobj = MyJacobian(ffobj)

    if method == "fsolve":
        import scipy.optimize as optimize

        factor = options.get("factor")
        factor = factor if factor else 1
        [sol, infodict, ier, msg] = optimize.fsolve(
            ffobj, x0.flatten(), fprime=Dffobj, factor=factor, full_output=True, xtol=1e-10, epsfcn=1e-9
        )
        if ier != 1:
            print msg
    elif method == "anderson":
        import scipy.optimize as optimize

        sol = optimize.anderson(ffobj, x0.flatten())
    elif method == "newton_krylov":
        import scipy.optimize as optimize

        sol = optimize.newton_krylov(ffobj, x0.flatten())
    elif method == "lmmcp":
        from dolo.numeric.extern.lmmcp import lmmcp, Big

        if lb == None:
            lb = -Big * np.ones(len(x0.flatten()))
        else:
            lb = lb.flatten()
        if ub == None:
            ub = Big * np.ones(len(x0.flatten()))
        else:
            ub = ub.flatten()

        sol = lmmcp(ffobj, Dffobj, x0.flatten(), lb, ub, verbose=verbose, options=options)

    return sol.reshape(in_shape)
コード例 #3
0
 def solve(self):
     try:
         x_fp = anderson(self.rootOperator,
                         self.x_0,
                         maxiter=self.numberOfIterations,
                         verbose=0,
                         callback=self.iterationCounter,
                         x_rtol=self.convergenceCriterion)
     except Exception as inst:
         print type(inst)  #Typically interrupt or non-convergence
         return
     print "scipy Anderson converged after", self.iterationStep, "steps"
     #As a side effect, we calculate other intersting physical quantities based on the found fixpoint solution
     self.derivePhysicalQuantitiesFromFixpoint(x_fp)
     #Reset iteration counter in case solve is called various times (and class is not re-instantiated)
     self.iterationStep = 0
コード例 #4
0
def rhoBar(D, rhoL=0.4, rhoR=0.6, x=None, sigma=None, E=0, verbose=False):
    """
    Calculate the steady state profile for a 1D system.
    D, sigma - Diffusion and mobility coefficients (must supply functions even if they are constant)
    rhoL, rhoR - boundary conditions.
    E - bulk field
    """
    if x is None:
        x = np.linspace(0, 1)
    rho0 = rhoL * (1 - x) + rhoR * x + 0.02
    rho0[0] = rhoL
    rho0[-1] = rhoR
    dx = np.gradient(x)
    residual = lambda rho: steadyStateEquation(rho, rhoL, rhoR, D, sigma, E, dx
                                               )
    try:
        rhoBulk = opti.newton_krylov(residual,
                                     rho0[1:-1],
                                     method="gmres",
                                     x_rtol=1e-9,
                                     verbose=verbose)
    except opti.nonlin.NoConvergence:
        try:
            rhoBulk = opti.newton_krylov(residual,
                                         rho0[1:-1],
                                         method="lgmres",
                                         x_rtol=1e-9,
                                         verbose=verbose)
        except opti.nonlin.NoConvergence:
            try:
                rhoBulk = opti.anderson(residual,
                                        rho0[1:-1],
                                        x_rtol=1e-9,
                                        verbose=verbose)
            except opti.nonlin.NoConvergence:
                rhoBulk = opti.newton_krylov(residual,
                                             rho0[1:-1],
                                             method="gmres",
                                             x_rtol=1e-9,
                                             iter=15000,
                                             verbose=verbose)

    rho = rhoBulk
    rho = np.insert(rho, 0, rhoL)
    rho = np.append(rho, rhoR)
    return rho
コード例 #5
0
 def __solver__(self, p):
     
     p.xk = p.x0.copy()
     p.fk = asfarray(max(abs(p.f(p.x0)))).flatten()
     
     p.iterfcn()
     if p.istop:
         p.xf, p.ff = p.xk, p.fk
         return 
     
     try: xf = anderson(p.f, p.x0, iter = p.maxIter)
     except: 
         p.istop = -1000
         return
     p.xk = p.xf = asfarray(xf)
     p.fk = p.ff = asfarray(max(abs(p.f(xf)))).flatten()
     p.istop = 1000
     p.iterfcn()
コード例 #6
0
    def __solver__(self, p):

        p.xk = p.x0.copy()
        p.fk = asfarray(max(abs(p.f(p.x0)))).flatten()

        p.iterfcn()
        if p.istop:
            p.xf, p.ff = p.xk, p.fk
            return

        try:
            xf = anderson(p.f, p.x0, iter=p.maxIter)
        except:
            p.istop = -1000
            return
        p.xk = p.xf = asfarray(xf)
        p.fk = p.ff = asfarray(max(abs(p.f(xf)))).flatten()
        p.istop = 1000
        p.iterfcn()
コード例 #7
0
ファイル: engine.py プロジェクト: sfurini/chick
 def find_equilibrium(self, initial_state=None):
     """
     Parameters
     ----------
     initial_state: dict
     """
     initial_state = self.get_independent_state_array(initial_state)
     print('initial_state: ', initial_state)
     try:
         # root = newton_krylov(self.get_independent_rates, initial_state, method='lgmres', verbose=1)
         root = anderson(self.get_independent_rates,
                         initial_state,
                         verbose=1)
     except NoConvergence as e:
         root = e.args[0]
     inds, species = self.get_independent_species()
     root_dict = {}
     for i, ind in enumerate(inds):
         root_dict[species[i]] = int(round(root[i]))
     return root_dict
コード例 #8
0
 def minimize(self, u_init):
     u0 = u_init
     u0[0] = (1 / (self.segment.EI[0, 0] + self.segment.EI[1, 0] + self.segment.EI[2, 0])) * \
             (self.segment.EI[0, 0] * self.segment.U_x[0, 0] +
              self.segment.EI[1, 0] * self.segment.U_x[1, 0] * np.cos(- self.alpha_0[1, 0]) +
              self.segment.EI[1, 0] *
              self.segment.U_y[1, 0] * np.sin(- self.alpha_0[1, 0]) +
              self.segment.EI[2, 0] * self.segment.U_x[2, 0] * np.cos(- self.alpha_0[2, 0]) +
              self.segment.EI[2, 0] *
              self.segment.U_y[2, 0] * np.sin(- self.alpha_0[2, 0]))
     u0[1] = (1 / (self.segment.EI[0, 0] + self.segment.EI[1, 0] + self.segment.EI[2, 0])) * \
             (self.segment.EI[0, 0] * self.segment.U_y[0, 0] +
              -self.segment.EI[1, 0] * self.segment.U_x[1, 0] * np.sin(- self.alpha_0[1, 0]) +
              self.segment.EI[1, 0] *
              self.segment.U_y[1, 0] * np.cos(- self.alpha_0[1, 0]) +
              -self.segment.EI[2, 0] * self.segment.U_x[2, 0] * np.sin(- self.alpha_0[2, 0]) +
              self.segment.EI[2, 0] *
              self.segment.U_y[2, 0] * np.cos(-self.alpha_0[2, 0]))
     res = optimize.anderson(self.ode_solver, u0, f_tol=1e-3)
     # another option for scalar cost function is  is res = optimize.minimize(self.ode_solver, u0,
     # method='Powell', options={'gtol': 1e-3, 'maxiter': 1000})
     return res
コード例 #9
0
 def search(self,Ksqrnum,sigmanum,gnum,n):
     '''
     Search for the first n roots.
     '''
     guess = GUESS_W
     self.tempKsqrnum = Ksqrnum
     self.tempsigmanum = sigmanum
     self.tempgnum = gnum
     if n ==1:
         orde = 1
         while(orde!=0):
             oneOnGuess = 1./guess
             print 'Root guess: %s'%(1./oneOnGuess)
             root = (1./scipy.absolute(anderson(self.aid_f, oneOnGuess,verbose=True,f_tol=6e-5)))
             info = self.zero_point_info(Ksqrnum,sigmanum,gnum,root)
             orde = info[0]
             print 'Root and order: %s , %s'%(root,orde)
             guess = root*(orde + 1)
     else:
         pass
     
     
     return [root]
コード例 #10
0
ファイル: densitydensity.py プロジェクト: gharib85/pygra
def generic_densitydensity(h0,
                           mf=None,
                           mix=0.1,
                           v=None,
                           nk=8,
                           solver="plain",
                           maxerror=1e-5,
                           filling=None,
                           callback_mf=None,
                           callback_dm=None,
                           load_mf=True,
                           compute_cross=True,
                           compute_dd=True,
                           verbose=1,
                           compute_anomalous=True,
                           compute_normal=True,
                           info=False,
                           callback_h=None,
                           **kwargs):
    """Perform the SCF mean field"""
    if verbose > 1: info = True
    #    if not h0.check_mode("spinless"): raise # sanity check
    mf = obj2mf(mf)
    h1 = h0.copy()  # initial Hamiltonian
    h1.turn_dense()
    h1.nk = nk  # store the number of kpoints
    if mf is None:
        try:
            if load_mf: mf = inout.load(mf_file)  # load the file
            else: raise
        except:
            mf = dict()
            for d in v:
                mf[d] = np.exp(1j * np.random.random(h1.intra.shape))
            mf[(0, 0, 0)] = mf[(0, 0, 0)] + mf[(0, 0, 0)].T.conjugate()
    else:
        pass  # initial guess
    ii = 0
    os.system("rm -f STOP")  # remove stop file
    hop0 = hamiltonian2dict(h1)  # create dictionary

    def f(mf, h=h1):
        """Function to minimize"""
        #      print("Iteration #",ii) # Iteration
        mf0 = deepcopy(mf)  # copy
        h = h1.copy()
        hop = update_hamiltonian(hop0,
                                 mf)  # add the mean field to the Hamiltonian
        set_hoppings(h, hop)  # set the new hoppings in the Hamiltonian
        if callback_h is not None:
            h = callback_h(h)  # callback for the Hamiltonian
        t0 = time.perf_counter()  # time
        dm = get_dm(h, v, nk=nk)  # get the density matrix
        if callback_dm is not None:
            dm = callback_dm(dm)  # callback for the density matrix
        t1 = time.perf_counter()  # time
        # return the mean field
        mf = get_mf(v,
                    dm,
                    compute_cross=compute_cross,
                    compute_dd=compute_dd,
                    has_eh=h0.has_eh,
                    compute_anomalous=compute_anomalous,
                    compute_normal=compute_normal)
        if callback_mf is not None:
            mf = callback_mf(mf)  # callback for the mean field
        t2 = time.perf_counter()  # time
        if info: print("Time in density matrix = ", t1 - t0)  # Difference
        if info: print("Time in the normal term = ", t2 - t1)  # Difference
        scf = SCF()  # create object
        scf.hamiltonian = h  # store
        #      h.check() # check the Hamiltonian
        scf.hamiltonian0 = h0  # store
        scf.mf = mf  # store mean field
        if os.path.exists("STOP"): scf.mf = mf0  # use the guess
        scf.dm = dm  # store density matrix
        scf.v = v  # store interaction
        scf.tol = maxerror  # maximum error
        return scf

    if solver == "plain":
        do_scf = True
        while do_scf:
            scf = f(mf)  # new vector
            mfnew = scf.mf  # new vector
            t0 = time.clock()  # time
            diff = diff_mf(mfnew, mf)  # mix mean field
            mf = mix_mf(mfnew, mf, mix=mix)  # mix mean field
            t1 = time.clock()  # time
            if info: print("Time in mixing", t1 - t0)
            if verbose > 0: print("ERROR in the SCF cycle", diff)
            #print("Mixing",dmix)
            if info: print()
            if diff < maxerror:
                scf = f(mfnew)  # last iteration, with the unmixed mean field
                inout.save(scf.mf, mf_file)  # save the mean field
                #   scf.hamiltonian.check(tol=100*maxerror) # perform some sanity checks
                return scf
    else:  # use different solvers
        scf = f(mf)  # perform one iteration
        fmf2a = get_mf2array(scf)  # convert MF to array
        fa2mf = get_array2mf(scf)  # convert array to MF

        def fsol(x):  # define the function to solve
            mf1 = fa2mf(x)  # convert to a MF
            scf1 = f(mf1)  # compute function
            xn = fmf2a(scf1.mf)  # new vector
            diff = x - xn  # difference vector
            print("ERROR", np.max(np.abs(diff)))
            print()
            return x - xn  # return vector

        x0 = fmf2a(scf.mf)  # initial guess
        # these methods do seem too efficient, but lets have them anyway
        if solver == "krylov":
            from scipy.optimize import newton_krylov
            x = newton_krylov(fsol, x0, rdiff=1e-3)  # use the solver
        elif solver == "anderson":
            from scipy.optimize import anderson
            x = anderson(fsol, x0)  # use the solver
        elif solver == "broyden1":
            from scipy.optimize import broyden1
            x = broyden1(fsol, x0, f_tol=maxerror * 100)  # use the solver
        elif solver == "linear":
            from scipy.optimize import linearmixing
            x = linearmixing(fsol, x0, f_tol=maxerror * 100)  # use the solver
        else:
            raise  # unrecognised solver
        mf = fa2mf(x)  # transform to MF
        scf = f(mf)  # compute the SCF with the solution
        scf.error = maxerror  # store the error
        inout.save(scf.mf, mf_file)  # save the mean field
        return scf  # return the mean field
コード例 #11
0
ファイル: car.py プロジェクト: Ghasak/traffic-intersection
    def state_dot(self, init_dyn_state, t, delta_f, delta_r, T_af, T_ar, T_bf,
                  T_br):
        # state = [v_x, v_y, r, psi, w_f, w_r, X, Y]

        state = init_dyn_state
        v_x = state[0]
        v_y = state[1]
        r = state[2]
        psi = state[3]
        w_f = state[4]
        w_r = state[5]
        X = state[6]
        Y = state[7]
        m = self.m
        L_r = self.L_r
        L_f = self.L_f
        h = self.h
        R_w = self.R_w
        I_w = self.I_w
        I_z = self.I_z
        g = params.g

        alpha_f = arctan2(v_y + L_f * r, v_x) - delta_f  # equation 11
        alpha_r = arctan2(v_y - L_r * r, v_x) - delta_r  # equation 12
        V_tf = sqrt((v_y + L_f * r)**2 + v_x**2)  # equation 13
        V_tr = sqrt((v_y - L_r * r)**2 + v_x**2)  # equation 14
        v_wxf = V_tf * cos(alpha_f)  # equation 15
        v_wxr = V_tr * cos(alpha_r)  # equation 16
        S_af = self.get_longitudinal_slip(v_wxf, w_f)  # equation 17
        S_ar = self.get_longitudinal_slip(v_wxr, w_r)  # equation 18

        def algebra(var):
            vdot_x, F_xf, F_xr, F_yf, F_yr = var
            rhs = -F_xf * cos(delta_f) - F_yf * sin(delta_f) - F_xr * cos(
                delta_r) - F_yr * sin(delta_r)
            eq1 = vdot_x - rhs / m + v_y * r  # equation 1
            # substitutions
            a_x = vdot_x  # instantaneous longitudinal acceleration
            F_zf = (m * g * L_r - m * a_x * h) / (L_f + L_r)  # equation 9
            F_zr = (m * g * L_f - m * a_x * h) / (L_f + L_r)  # equation 10
            F_xf_guess, F_yf_guess = self.get_traction(F_xf, F_zf, S_af,
                                                       alpha_f)
            F_xr_guess, F_yr_guess = self.get_traction(F_xr, F_zr, S_ar,
                                                       alpha_r)
            eq19 = F_xf - F_xf_guess  # equation 19
            eq20 = F_yf - F_yf_guess  # equation 20
            eq21 = F_xr - F_xr_guess  # equation 21
            eq22 = F_yf - F_yf_guess  # equation 22
            return eq1, eq19, eq20, eq21, eq22

        # resolve interdependency with nonlinear solver
        init_guess = [0, 0, 0, 0, 0]
        vdot_x, F_xf, F_xr, F_yf, F_yr = anderson(algebra, init_guess)
        rhs = F_yf * cos(delta_f) - F_xf * sin(delta_f) + F_yr * cos(
            delta_r) - F_xr * sin(delta_r)
        vdot_y = rhs / m - v_x * r  # equation 2
        rhs = L_f * (F_yf * cos(delta_f) - F_xf * sin(delta_f)) - L_r * (
            F_yr * cos(delta_r) - F_xr * sin(delta_r))
        r_dot = rhs / I_z  # equation 3
        rhs = F_xf * R_w - T_bf + T_af
        wdot_f = rhs / I_w  # equation 4
        rhs = F_xr * R_w - T_br + T_ar
        wdot_r = rhs / I_w  # equation 5
        psi_dot = r  # equation 6
        v_X = v_x * cos(psi) - v_y * sin(psi)  # equation 7
        v_Y = v_x * sin(psi) + v_y * cos(psi)  # equation 8

        dstate_dt = [vdot_x, vdot_y, r_dot, psi_dot, wdot_f, wdot_r, v_X, v_Y]
        return dstate_dt
コード例 #12
0
ファイル: solver.py プロジェクト: lnsongxf/dynare-python
def solver(fobj,
           x0,
           lb=None,
           ub=None,
           options={},
           method='lmmcp',
           jac='default',
           verbose=False):

    in_shape = x0.shape

    ffobj = lambda x: fobj(x.reshape(in_shape)).flatten()

    if not isinstance(jac, str):
        pp = np.prod(in_shape)

        def Dffobj(t):
            tt = t.reshape(in_shape)
            dval = jac(tt)
            return dval.reshape((pp, pp))

    elif jac == 'precise':
        from numdifftools import Jacobian
        Dffobj = Jacobian(ffobj)
    else:
        Dffobj = MyJacobian(ffobj)

    if method == 'fsolve':
        import scipy.optimize as optimize
        factor = options.get('factor')
        factor = factor if factor else 1
        [sol, infodict, ier, msg] = optimize.fsolve(ffobj,
                                                    x0.flatten(),
                                                    fprime=Dffobj,
                                                    factor=factor,
                                                    full_output=True,
                                                    xtol=1e-10,
                                                    epsfcn=1e-9)
        if ier != 1:
            print msg
    elif method == 'anderson':
        import scipy.optimize as optimize
        sol = optimize.anderson(ffobj, x0.flatten())
    elif method == 'newton_krylov':
        import scipy.optimize as optimize
        sol = optimize.newton_krylov(ffobj, x0.flatten())
    elif method == 'lmmcp':
        from dolo.numeric.extern.lmmcp import lmmcp, Big
        if lb == None:
            lb = -Big * np.ones(len(x0.flatten()))
        else:
            lb = lb.flatten()
        if ub == None:
            ub = Big * np.ones(len(x0.flatten()))
        else:
            ub = ub.flatten()

        sol = lmmcp(ffobj,
                    Dffobj,
                    x0.flatten(),
                    lb,
                    ub,
                    verbose=verbose,
                    options=options)

    return sol.reshape(in_shape)
コード例 #13
0
def findrpoA(x0, Tapproximate):
    def rpot(x):
        return rpo(x, Tapproximate)

    rpos = anderson(rpot, x0)
    return rpos
コード例 #14
0
def solve_nlae(x0, model_parameters):
    # x_sol, info, flag, err_msg = opt.fsolve(kotte_nlae, x0, model_parameters, xtol=1e-3, full_output=1)
    options = {'ftol': 1e-8, 'disp': 1, 'maxiter': 5000}
    wrapped_fun = lambda y: kotte_nlae(y, model_parameters)
    sol = opt.anderson(wrapped_fun, x0, maxiter=100000, f_tol=1e-8)
    return sol