Exemplo n.º 1
0
    def toWl(self, V0, maxiter=500, tol=1e-15):
        """Convert V0 number to wavelength.

        An iterative method is used, since the index can be wavelength
        dependant.

        """
        if V0 == 0:
            return float("inf")
        if isinf(V0):
            return 0

        def f(x):
            return constants.tpi / V0 * b * self.NA(x)

        b = self.innerRadius(-1)

        wl = f(1.55e-6)
        if abs(wl - f(wl)) > tol:
            for w in (1.55e-6, 5e-6, 10e-6):
                try:
                    wl = fixed_point(f, w, xtol=tol, maxiter=maxiter)
                except RuntimeError:
                    # FIXME: What should we do if it does not converge?
                    self.logger.info(
                        "toWl: did not converged from {}µm "
                        "for V0 = {} (wl={})".format(w*1e6, V0, wl))
                if wl > 0:
                    break

        if wl == 0:
            self.logger.error("toWl: did not converged for "
                              "V0 = {} (wl={})".format(V0, wl))

        return Wavelength(wl)
Exemplo n.º 2
0
    def encode(self, x):
        """
        Given an input array `x` it returns its associated encoding `y(x)`.
        Please cf. the paper for more details.

        Note that NO learning takes place.
        """
        n = self._outputSize
        y = np.zeros(n)
        Q = self._Q
        W = self._W
        t = self._t
        lam = self._lambda

        try:

            y_star = np.random.sample(n)
            y_star = fixed_point(
                lambda p: expit(lam * (np.dot(Q, x) + np.dot(W, p) - t)),
                y_star,
                maxiter=2000,
                method='del2')

        except RuntimeError:
            pass

        winner = np.where(y_star > 0.5)[0]
        y[winner] = 1.

        return y
Exemplo n.º 3
0
def GCI( df ):
#supported by ASME (name of variables based on [1])
   df.sort_values('dx',  inplace=True) #ascending=False,

   r21=df['dx'].values[1]/df['dx'].values[0]
   r32=df['dx'].values[2]/df['dx'].values[1]

   extrapolated_21=np.zeros(len(df.columns)-3)
   dfGCI= pd.DataFrame({'Simulation':["behaviour","extrapolated_value", "p", "GCI"]}  ,columns=df.columns)

   for icol, col in enumerate(df.columns):
     if ( df[col].name != 'Simulation' and df[col].name != 'dx' and df[col].name != 'dt' ):
        epsilon21 = df[col].values[1]-df[col].values[0]
        epsilon32 = df[col].values[2]-df[col].values[1]
        R= epsilon21/epsilon32 #R: discriminating ratio
        s=np.sign(epsilon32/epsilon21)
        if (0<R<1):
           dfGCI[col].values[0]= "Monotonic convergence"
        elif (R<0 and abs(R)<1):
           dfGCI[col].values[0]= "Oscillatory convergence"
        elif (R>1):
           dfGCI[col].values[0]= "Monotonic divergence"
        else:
           dfGCI[col].values[0]= "Oscillatory divergence"
        if (0<R<1): #the method proposed in [1] is only suited for monotonic convergence
           def func(p):
               return 1/np.log(r21)*abs( np.log(abs(epsilon32/epsilon21))+np.log((r21**p-s)/(r32**p-s)))
           p=optimize.fixed_point(func,1/np.log(r21)*abs( np.log(abs(epsilon32/epsilon21))))
           extrapolated_21=(r21**p*df[col].values[0]-df[col].values[1])/(r21**p-1.0)
           GCI_21=1.25*abs(epsilon21/df[col].values[0])/(r21**p-1.0)
           dfGCI[col].values[1]= extrapolated_21
           dfGCI[col].values[2]= p
           dfGCI[col].values[3]= GCI_21
   dfConvergence=df.append(dfGCI, ignore_index=True);
   return dfConvergence
Exemplo n.º 4
0
def H_tracking_evolution_equation(current_time, gamma, fermihubbard,
                                  observables, J_target):

    D = fermihubbard.operator_dict['hop_left_op'].expt_value(gamma[:-1])

    phi = fixed_point(H_tracking_implicit_phi_function,
                      observables.phi[-1],
                      args=(gamma, J_target(current_time), fermihubbard,
                            observables))
    # phi = 0

    psi_dot = -expiphi(phi) * fermihubbard.perimeter_params.t \
              * fermihubbard.operator_dict['hop_left_op'].dot(gamma[:-1])
    psi_dot -= expiphiconj(phi) * fermihubbard.perimeter_params.t \
               * fermihubbard.operator_dict['hop_right_op'].dot(gamma[:-1])
    psi_dot += fermihubbard.operator_dict['H_onsite'].dot(gamma[:-1])

    y_dot = -(-fermihubbard.perimeter_params.t * (expiphi(phi) * D
                                                  + expiphiconj(phi) * D.conj())
              + fermihubbard.operator_dict['H_onsite'].expt_value(gamma[:-1]))\
            * (J_target.derivative())(current_time)/(J_target(current_time)**2)

    gamma_dot = np.append(psi_dot, y_dot)

    return gamma_dot
Exemplo n.º 5
0
def improved_H_tracking(current_time, gamma, phi_init, init_cond,
                        perimeter_params, fermihubbard, J_dot_target):
    """H tracking equation from the Ehrenfest theorem for the Hamiltonian H"""
    # Separate our extended vector
    y_t = gamma[-1]
    psi_t = gamma[:-1]
    phi_0 = init_cond[0]
    # Fixed point iteration on phi
    J_target = J_dot_target.antiderivative()

    phi_fpi = fixed_point(phi_implicit_H,
                          phi_init,
                          args=(current_time, gamma, init_cond,
                                perimeter_params, fermihubbard, J_target))

    # Calculate psi dot

    psi_dot = -1j * fermihubbard.operator_dict['H'].dot(psi_t, time=phi_fpi)

    # Calculate y dot

    y_dot = - fermihubbard.operator_dict['H'].expt_value(psi_t, time=phi_fpi) \
            * J_dot_target(current_time)/((J_target(current_time))**2)

    # recombine for gamma dot

    gamma_dot = np.append(psi_dot, y_dot)

    return gamma_dot
Exemplo n.º 6
0
    def encode(self, x):
        """
        Given an input array `x` it returns its associated encoding `y(x)`.
        Please cf. the paper for more details.

        Note that NO learning takes place.
        """
        n = self._outputSize
        y = np.zeros(n)
        Q = self._Q
        W = self._W
        t = self._t
        lam = self._lambda


        try:
            
            y_star = np.random.sample(n)
            y_star = fixed_point(lambda p: expit(lam * ( np.dot(Q,x) + np.dot(W,p) - t)), 
                                 y_star, maxiter=2000, method='del2')

        except RuntimeError:
            pass


        winner = np.where(y_star > 0.5)[0]
        y[ winner ] = 1.

        return y
Exemplo n.º 7
0
    def find_stationary_var(amat=None, bmat=None, cmat=None):
        """Find fixed point of H = CC' + AHA' + BHB' given A, B, C.

        Parameters
        ----------
        amat, bmat, cmat : (nstocks, nstocks) arrays
            Parameter matrices

        Returns
        -------
        (nstocks, nstocks) array
            Unconditional variance matrix

        """
        nstocks = amat.shape[0]
        kwargs = {'amat': amat, 'bmat': bmat, 'ccmat': cmat.dot(cmat.T)}
        fun = partial(ParamGeneric.fixed_point, **kwargs)
        try:
            with np.errstate(divide='ignore', invalid='ignore'):
                hvar = np.eye(nstocks)
                sol = sco.fixed_point(fun, hvar[np.tril_indices(nstocks)])
                hvar[np.tril_indices(nstocks)] = sol
                hvar[np.triu_indices(nstocks, 1)] \
                    = hvar.T[np.triu_indices(nstocks, 1)]
                return hvar
        except RuntimeError:
            # warnings.warn('Could not find stationary varaince!')
            return None
Exemplo n.º 8
0
def calculate_spar_distance(psi_baseline, Au_baseline, Au_goal, Al_goal,
                            deltaz, c_goal):
    """Calculate spar distance (dimensional)"""
    def f(psi_lower_goal):
        y_lower_goal = CST(psi_lower_goal * c_goal, c_goal,
                           [deltaz / 2., deltaz / 2.], Au_goal, Al_goal)
        y_lower_goal = y_lower_goal['l']
        return psi_upper_goal + (s[0] / s[1]) * (y_lower_goal -
                                                 y_upper_goal) / c_goal

    # Calculate cruise chord
    c_baseline = calculate_c_baseline(c_goal, Au_baseline, Au_goal, deltaz)

    # Calculate upper psi at goal airfoil
    psi_upper_goal = calculate_psi_goal(psi_baseline, Au_baseline, Au_goal,
                                        deltaz, c_baseline, c_goal)
    y_upper_goal = CST(psi_upper_goal * c_goal, c_goal,
                       [deltaz / 2., deltaz / 2.], Au_goal, Al_goal)
    y_upper_goal = y_upper_goal['u']

    # Spar direction
    s = calculate_spar_direction(psi_baseline, Au_baseline, Au_goal, deltaz,
                                 c_goal)

    # Calculate lower psi and xi at goal airfoil
    # Because the iterative method can lead to warningdivision by zero after
    # converging, we ignore the warning
    np.seterr(divide='ignore', invalid='ignore')
    psi_lower_goal = optimize.fixed_point(f, [psi_upper_goal])
    x_lower_goal = psi_lower_goal * c_goal
    y_lower_goal = CST(x_lower_goal, c_goal, [deltaz / 2., deltaz / 2.],
                       Au_goal, Al_goal)
    y_lower_goal = y_lower_goal['l']

    return (y_upper_goal - y_lower_goal[0]) / s[1]
Exemplo n.º 9
0
    def find_stationary_var(amat=None, bmat=None, cmat=None):
        """Find fixed point of H = CC' + AHA' + BHB' given A, B, C.

        Parameters
        ----------
        amat, bmat, cmat : (nstocks, nstocks) arrays
            Parameter matrices

        Returns
        -------
        (nstocks, nstocks) array
            Unconditional variance matrix

        """
        nstocks = amat.shape[0]
        kwargs = {'amat': amat, 'bmat': bmat, 'ccmat': cmat.dot(cmat.T)}
        fun = partial(ParamGeneric.fixed_point, **kwargs)
        try:
            with np.errstate(divide='ignore', invalid='ignore'):
                hvar = np.eye(nstocks)
                sol = sco.fixed_point(fun, hvar[np.tril_indices(nstocks)])
                hvar[np.tril_indices(nstocks)] = sol
                hvar[np.triu_indices(nstocks, 1)] \
                    = hvar.T[np.triu_indices(nstocks, 1)]
                return hvar
        except RuntimeError:
            # warnings.warn('Could not find stationary varaince!')
            return None
Exemplo n.º 10
0
def get_ev(x):

    bgfr, nsyn_bg, nsyn_00, nsyn_01, nsyn_10, nsyn_11, delay = x
    f0_ss_internal, f1_ss_internal = sopt.fixed_point(steady_state_function,
                                                      np.array([f0_ss, f1_ss]),
                                                      args=x)
    A = L + (nsyn_bg * bgfr +
             nsyn_01 * f0_ss_internal) * Se + nsyn_11 * f1_ss_internal * Si
    A[0, :] = 1
    b = np.zeros(A.shape[0])
    b[0] = 1
    p_star_internal = npla.solve(A, b)
    A0 = leak_matrix + (
        nsyn_bg * bgfr +
        nsyn_01 * f0_ss_internal) * synaptic_matrix_bg + nsyn_11 * (
            nsyn_bg * bgfr + nsyn_01 * f0_ss_internal) * np.dot(
                p_star_internal, threshold_vector_bg) * synaptic_matrix_recc
    A1 = (nsyn_bg * bgfr + nsyn_01 * f0_ss_internal) * nsyn_11 * np.outer(
        synaptic_matrix_recc.dot(p_star_internal), threshold_vector_bg)
    n = A0.shape[0]
    N = 6
    D = -cheb(N - 1) * 2 / delay
    tmp1 = np.kron(D[:N - 1, :], np.eye(n))
    tmp2 = np.hstack((A1, np.zeros((n, (N - 2) * n)), A0))
    tmp3 = spsp.csr_matrix(np.vstack((tmp1, tmp2)))
    t0 = time.time()
    w = spsp.linalg.eigs(tmp3,
                         5,
                         return_eigenvectors=False,
                         which='LR',
                         ncv=150)
    w_nonzero = [wi for wi in w if np.abs(wi) > 1e-8]
    w_crit = sorted(w_nonzero, key=lambda x: np.real(x))[-1]
    print delay, time.time() - t0, w_crit
    return w_crit
    def do_one_step_fixed_point(self, t, X0):

        rho0 = vector_hatmap(X0, self.gamma)
        grad = self.gradient_hamiltonian(rho0)

        callback = None
        if self.diagnostics:
            callback = self.diagnostics_logger

        def optimization_function(rho1):
            s = grad + self.gradient_hamiltonian(rho1)
            res  = np.empty((self.N, 3, 3))
            for n in range(0, self.N):               
                #g = linalg.expm(-self.h/2*s[n, :, :])

                g = cayley(-self.h/4*s[n, :, :])

                res[n, :, :] = Ad(g, rho0[n, :, :])
            return res


        #d = Diagnostics()


        rho1 = fixed_point(optimization_function, rho0)
        

        #self.diagnostics_logger.store()

        return vector_invhat(rho1, self.gamma)
Exemplo n.º 12
0
    def toWl(self, V0, maxiter=500, tol=1e-15):
        """Convert V0 number to wavelength.

        An iterative method is used, since the index can be wavelength
        dependant.

        """
        if V0 == 0:
            return float("inf")
        if isinf(V0):
            return 0

        def f(x):
            return constants.tpi / V0 * b * self.NA(x)

        b = self.innerRadius(-1)

        wl = f(1.55e-6)
        if abs(wl - f(wl)) > tol:
            for w in (1.55e-6, 5e-6, 10e-6):
                try:
                    wl = fixed_point(f, w, xtol=tol, maxiter=maxiter)
                except RuntimeError:
                    # FIXME: What should we do if it does not converge?
                    self.logger.info("toWl: did not converged from {}µm "
                                     "for V0 = {} (wl={})".format(
                                         w * 1e6, V0, wl))
                if wl > 0:
                    break

        if wl == 0:
            self.logger.error("toWl: did not converged for "
                              "V0 = {} (wl={})".format(V0, wl))

        return Wavelength(wl)
Exemplo n.º 13
0
def Hmax_evolution(current_time, gamma, observables, perimeter_params,
                   J_target, fermihubbard, delta):
    # First check if we are below the current tolerance
    if observables.current[-1] < observables.add_var['jtol'] or J_target(
            current_time) < observables.add_var['jtol']:
        # if we are below the tolerance, we will check the method used in the last step
        if observables.add_var['last_method'][-1] == 'H':
            # if we used H tracking the last step, we will assign the initial conditions for R tracking
            observables.init_cond = np.array([observables.phi[-2], 0])
            observables.y = 0
            # print('switch to R')
        else:
            # if we used R tracking the last step, we will do nothing special
            None

        observables.add_var['last_method'].append('R')

        # evolve our gamma using R tracking
        f_params = dict(phi_init=observables.phi[-1],
                        init_cond=observables.init_cond,
                        perimeter_params=perimeter_params,
                        fermihubbard=fermihubbard,
                        J_dot_target=J_target.derivative())
        gamma_delta_t = RK4(current_time, gamma, delta, improved_R_tracking,
                            **f_params)
        phi_delta_t = observables.init_cond[0] \
                      + np.angle(fermihubbard.operator_dict['hop_left_op'].expt_value(gamma_delta_t[:-1])) \
                      - gamma_delta_t[-1]
        return [phi_delta_t, gamma_delta_t]
    else:
        # if we are above the tolerance, we will check the method used in the last step
        if observables.add_var['last_method'][-1] == 'R':
            # if we used R tracking last step, we will assign the initial conditions for H tracking
            bound_cond = (perimeter_params.a / J_target(current_time)) \
                         * fermihubbard.operator_dict['H'].expt_value(gamma[:-1], time=observables.phi[-1])
            observables.init_cond = np.array([observables.phi[-3], bound_cond])
            gamma[-1] = 0
            # print('switch to H')
        else:
            # if we used R tracking the last step, we will do nothing special
            None

        observables.add_var['last_method'].append('H')

        #evolve our gamma using H tracking

        f_params = dict(phi_init=observables.phi[-4],
                        init_cond=observables.init_cond,
                        perimeter_params=perimeter_params,
                        fermihubbard=fermihubbard,
                        J_dot_target=J_target.derivative())
        gamma_delta_t = RK4(current_time, gamma, delta, improved_H_tracking,
                            **f_params)
        phi_delta_t = fixed_point(
            phi_implicit_H,
            observables.phi[-1],
            args=(current_time + delta, gamma_delta_t, observables.init_cond,
                  perimeter_params, fermihubbard, J_target))
        return [phi_delta_t, gamma_delta_t]
def friction(Re,epsilon,diam):
	from scipy.optimize import fixed_point			
	def friction_funct(friction, Re, epsilon, diam):

		LHS = - 2.*np.log10(epsilon/(3.7*diam)+ 2.51/(Re*np.sqrt(friction)))
		return 1/LHS**2

	return fixed_point(friction_funct, 0.2, args=(Re,epsilon,diam))
def original_tracking_implicit_four_step(current_time, psi, psi_nm1, psi_nm2,
                                         psi_nm3, fhm, J_target, l, bn, tp):
    psi_np1 = fixed_point(implicit_four_step,
                          psi,
                          args=(current_time, psi, psi_nm1, psi_nm2, psi_nm3,
                                tp, fhm, J_target, l, bn))
    psi_n = psi
    return [psi_np1, psi_n, psi_nm1, psi_nm2]
Exemplo n.º 16
0
def AndreevEnergy(hfe,mu):
	""" returns the ABS frequency in the Hartree-Fock approximation """
	eqn = lambda x: sp.sqrt(hfe**2+(DFg(x)-U*mu)**2)/(1.0+SFg(x))
	## change the initial condition init_val if convercence problems raise
	wzero = sp.real_if_close(fixed_point(eqn,ABSinit_val*Delta))
	if sp.fabs(sp.imag(wzero)) > 1e-12:
		print("# - Warning: AndreevEnergy: Non-zero Im w(ABS) = {0: .5e}".format(sp.imag(wzero)))
	return sp.float64(sp.real(wzero))	## caution: fixed_point returns numpy.ndarray
def next_p(p_0, D_0, Pi, e, p_bar):
    #find the next iterate p
    Lambda = sparse.diags(D_0)

    #p_1 = f(p_0) solve fixed point
    p_1 = optimize.fixed_point(FF, p_0, args=(p_0, Pi, Lambda, e, p_bar))
    D_1 = next_default_ind(p_1, Pi, p_bar, e)
    return p_1, D_1
Exemplo n.º 18
0
def solve(J, n1, delta, beta, gamma):
    X = np.array([[1., -J], [-J, 1.]])
    n = np.vstack([n1, 1 - n1])
    m0 = np.array([[5., -5.], [-5., 5.]])
    r0 = np.array([[.5, .5], [.5, .5]])
    p0 = np.hstack([m0, r0])
    p = fixed_point(sce, p0, args=(X, n, delta, beta, gamma))
    m, r = np.hsplit(p, 2)
    return m, r
Exemplo n.º 19
0
 def f(x, ii):
     if ii in [0,1]:
         return  sopt.fixed_point(steady_state_function, np.array([f0_ss, f1_ss]), args=x)[ii]
     elif ii == 2:
         return np.real(get_ev(x))
     elif ii == 3:
         return np.imag(get_ev(x))
     else: 
         raise Exception 
def original_tracking_implicit_bd_six_step(current_time, psi, psi_nm1, psi_nm2,
                                           psi_nm3, psi_nm4, psi_nm5, fhm,
                                           J_target, l, bn, tp):
    psi_np1 = fixed_point(backwards_diff_six_step,
                          psi,
                          args=(current_time, psi, psi_nm1, psi_nm2, psi_nm3,
                                psi_nm4, psi_nm5, tp, fhm, J_target, l, bn))
    psi_n = psi
    return [psi_np1, psi_n, psi_nm1, psi_nm2, psi_nm3, psi_nm4]
Exemplo n.º 21
0
def BFP_(UFP, kUB, kBU, P, Aspine, Cooperativity):
    """Returns the fixed point of the bound receptor pool.

    Parameters
    ----------
    UFP : float
        Fixed point of the mobile receptor pool.
    kUB : float
        Rate at which AMPARs bind to PSD slots.
    kBU : float
        Rate at which AMPARs unbind from PSD slots.
    P : float
        Number of binding site/slots at the PSD.
    Aspine : float
        Spine surface area.
    Cooperativity : 0, 1
        Specifies whether cooperative recepotr binding is accounted for (=1) or not (=0).
        
    Returns
    -------
    float
        Fixed point of the bound receptor pool.
    """
    def dB_FP(B, U, kUB, kBU, P, Aspine, Cooperativity):
        """Function of the number of bound receptors B plus its derivative dB/dt (func(B)=dB/dt+B). Used to numerically find the fixed point using scipy.optimize.fixed_point from the svipy library.

        Parameters
        ----------
        B : float
            Number of bound receptors.
        U : float
            Number of mobile recepotrs.
        kUB : float
            Rate at which AMPARs bind to PSD slots.
        kBU : float
            Rate at which AMPARs unbind from PSD slots.
        P : float
            Number of binding site/slots at the PSD.
        Aspine : float
            Spine surface area.
        Cooperativity : 0, 1
            Specifies whether cooperative recepotr binding is accounted for (=1) or not (=0).
            
        Returns
        -------
        float
            dB/dt+B.
        """
        return kUB_(B, kUB, Cooperativity, P) * (P - B) * U / Aspine - kBU_(
            B, kBU, Cooperativity, P) * B + B

    return optimize.fixed_point(dB_FP,
                                P,
                                args=(UFP, kUB, kBU, P, Aspine, Cooperativity),
                                xtol=1e-10,
                                maxiter=10000,
                                method='iteration')
def original_tracking_implicit_two_step(current_time, psi, psi_nm1, fhm,
                                        J_target, l, bn, tp):
    # print(psi.shape)
    psi_np1 = fixed_point(implicit_two_step,
                          psi,
                          args=(current_time, psi, psi_nm1, tp, fhm, J_target,
                                l, bn))
    psi_n = psi
    return [psi_np1, psi_n]
Exemplo n.º 23
0
    def Solve_prob_of_entry_SymmetricREE(self, theta_input, X_m_input,
                                         N_m_input):
        '''Solve for the fixed point of function self._expected_prob_To_result_prob(theta, X_m, N_m, ...) 

        Input:
        -- theta_input: 5 element array or list, parameters of interest
        -- X_m: scalar or vector, market level profit shifterr
        -- N_m: scalar or vector, number of firms in the market  

        Output:
        --prob: equilibrium probability of entering A or B
                size: for one market, (2, ) array; for multiple markets, (2, NumOfMarkets) array '''

        # 1. Solve for the fixed point for P_A and P_B
        # (1) scalar
        if isinstance(X_m_input, int) or isinstance(X_m_input, float):
            # initial value
            x0 = np.array([.5, .5])
            # solve
            fixed_point = opt.fixed_point(
                lambda x: self._expected_prob_To_result_prob(
                    theta_input, X_m_input, N_m_input, x[0], x[1])[1:].flatten(
                    ),
                x0,
                maxiter=2000)

        # (2) vector
        else:
            # initial value: 2-by-NumberOfMarkets
            x0 = np.ones((2, len(X_m_input))) * 0.5
            # solve
            fixed_point = opt.fixed_point(
                lambda x: self._expected_prob_To_result_prob(
                    theta_input, X_m_input, N_m_input, x[0, :], x[1, :])[1:, :
                                                                         ],
                x0,
                maxiter=2000)

        # P_0 = 1-P_A - P_B
        prob_0 = 1 - np.sum(fixed_point, axis=0)
        prob = np.append([prob_0], fixed_point, axis=0)

        return prob
Exemplo n.º 24
0
def lcl(pressure, temperature, dewpt, max_iters=50, eps=1e-5):
    r"""Calculate the lifted condensation level (LCL) using from the starting point.

    The starting state for the parcel is defined by `temperature`, `dewpt`,
    and `pressure`.

    Parameters
    ----------
    pressure : `pint.Quantity`
        The starting atmospheric pressure
    temperature : `pint.Quantity`
        The starting temperature
    dewpt : `pint.Quantity`
        The starting dew point

    Returns
    -------
    `(pint.Quantity, pint.Quantity)`
        The LCL pressure and temperature

    Other Parameters
    ----------------
    max_iters : int, optional
        The maximum number of iterations to use in calculation, defaults to 50.
    eps : float, optional
        The desired relative error in the calculated value, defaults to 1e-5.

    See Also
    --------
    parcel_profile

    Notes
    -----
    This function is implemented using an iterative approach to solve for the
    LCL. The basic algorithm is:

    1. Find the dew point from the LCL pressure and starting mixing ratio
    2. Find the LCL pressure from the starting temperature and dewpoint
    3. Iterate until convergence

    The function is guaranteed to finish by virtue of the `max_iters` counter.

    """
    def _lcl_iter(p, p0, w, t):
        td = dewpoint(vapor_pressure(units.Quantity(p, pressure.units), w))
        return (p0 * (td / t)**(1. / kappa)).m

    w = mixing_ratio(saturation_vapor_pressure(dewpt), pressure)
    fp = so.fixed_point(_lcl_iter,
                        pressure.m,
                        args=(pressure.m, w, temperature),
                        xtol=eps,
                        maxiter=max_iters)
    lcl_p = units.Quantity(fp, pressure.units)
    return lcl_p, dewpoint(vapor_pressure(lcl_p, w))
Exemplo n.º 25
0
def _contraction_Blumenthal1986(r,M_DMO,Mbar,fbar):
    # solve for the contracted radius 'rf' containing the same DM mass
    # as enclosed for r 
    func_M_bar= interp1d(r,Mbar,bounds_error=False,
                         fill_value=(Mbar[0],Mbar[-1]) )
    func_r_contract= lambda rf: r*(M_DMO/(1.-fbar))/(M_DMO+func_M_bar(rf)) 
    rf= fixed_point(func_r_contract,r)
    # now find how much the enclosed mass increased at r
    func_M_DM= interp1d(rf,M_DMO,bounds_error=False,
                        fill_value=(M_DMO[0],M_DMO[-1]))
    return func_M_DM(r)/r**2.
Exemplo n.º 26
0
 def f(x, ii):
     if ii in [0, 1]:
         return sopt.fixed_point(steady_state_function,
                                 np.array([f0_ss, f1_ss]),
                                 args=x)[ii]
     elif ii == 2:
         return np.real(get_ev(x))
     elif ii == 3:
         return np.imag(get_ev(x))
     else:
         raise Exception
Exemplo n.º 27
0
def plot_f(la, c_i, c) : 
    
    y = 10**-10
    x = np.linspace(0.4, 1.1, 100)
    f = [1 + 1j]
    for xx in x : 
        func = lambda t : 1/(-(xx + 1j*y) + c*np.sum(c_i*la/(1+la*t)))
        t = fixed_point(func,x0 = f[-1])
        f.append(1/np.pi*np.imag(t))
    f = np.array(f[1:])
    integral_f = np.sum(f[:-1]*(x[1:] - x[:-1]))*1.5
    plt.figure(0)
    plt.plot(x, f/integral_f, color = 'green')
    plt.legend()
def friction_factor(V, d, rho, ni, k):
    #velocity
    #diameter
    #density
    #viscosity
    #roughness

    Re = V * d * rho / ni

    def colebrook(x):
        LHS = -2 * np.log10((2.51 / (Re * np.sqrt(x))) + (k / (3.71 * d)))
        return (1.0 / LHS)**2

    return fixed_point(colebrook, 0.2)
Exemplo n.º 29
0
def get_loyer(scenario):
    yr = scenario.year    
    simu = ScenarioSimulation()
    simu.set_config(scenario= scenario, nmen = 1, year = yr, country = 'france')
    simu.set_param()


    def func(loyer):
        simu.scenario.menage[0].update({'loyer': loyer})                 
        data, data_default = simu.compute()
        revdisp = data['revdisp'].vals
        logt = data['logt'].vals 
        return float(((revdisp - logt)/3 + logt )/12) 
    
    return fixed_point(func, 0)
Exemplo n.º 30
0
def _contraction_Gnedin2004(r,M_DMO,M_bar,Rvir,fbar):
    # solve for the contracted radius 'rf' containing the same DM mass
    # as enclosed for r 
    func_M_bar= interp1d(r,M_bar,bounds_error=False,
                         fill_value=(M_bar[0],M_bar[-1]))
    func_M_DMO= interp1d(r,M_DMO,bounds_error=False,
                         fill_value=(M_DMO[0],M_DMO[-1]))
    A, w= 0.85, 0.8
    func_r_mean= lambda ri: A*Rvir*(ri/Rvir)**w
    M_DMO_rmean= func_M_DMO(func_r_mean(r))
    func_r_contract= lambda rf: r*(M_DMO_rmean/(1.-fbar))\
        /(M_DMO_rmean+func_M_bar(func_r_mean(rf)))
    rf= fixed_point(func_r_contract,r)
    # now find how much the enclosed mass increased at r
    func_M_DM = interp1d(rf,M_DMO,bounds_error=False,
                         fill_value=(M_DMO[0],M_DMO[-1]))
    return func_M_DM(r)/r**2.
Exemplo n.º 31
0
def SolveHF():
	""" Hartree-Fock equations solver """
	ed = eps-U/2.0            ## local energy level shifted to symmetry point
	ErrMsg = 0                ## error message indicator
	## filling the arrays #################################
	dX   = 1e-4         ## band energy sampling
	Xmin = -100.0       ## lower cutoff for band energy
	X_A = sp.arange(Xmin,-Delta,dX)
	## initial conditions #################################
	## change these if no convergence is achieved #########
	n_siam = lambda x: 0.5 - sp.arctan((ed+U*x)/(GammaR+GammaL))/sp.pi	
	n = fixed_point(n_siam,0.5)
	mu = 0.2
	hfe = ed+U*n
	wzero = AndreevEnergy(hfe,mu)
	n_old = 1e5
	mu_old = 1e5
	wzero_old = 1e5
	k = 0
	while any([sp.fabs(wzero-wzero_old) > ConvHF,\
	           sp.fabs(mu-mu_old)       > ConvHF,\
                sp.fabs(n-n_old)         > ConvHF]):
		[n_old,mu_old,wzero_old] = [n,mu,wzero]
		hfe = ed+U*n
		[D1,D2,D3] = MSumsHF(hfe,mu,wzero,X_A)
		mu = -D3/(1.0-U*D1)
		n = 0.5 if eps == 0.0 else (D2+ed*D1)/(1.0-U*D1)
		hfe = ed+U*n
		wzero = AndreevEnergy(hfe,mu)
		if k > HF_max_iter: 
			print('# - Error: SolveHF: No convergence after {0: 5d} iterations, exit.'.format(k))
			n = mu = wzero = -1.0
			ErrMsg = 1
			break
		if sp.fabs(sp.imag(n))  > 1e-12:
			print('# - Warning: SolveHF: neglecting non-zero Im n  = {0: .5e}'.format(sp.imag(n)))
		n = sp.real(n)
		if sp.fabs(sp.imag(mu)) > 1e-12:
			print('# - Warning: SolveHF: neglecting non-zero Im mu = {0: .5e}'.format(sp.imag(mu)))
		mu = sp.real(mu)
		k += 1
	if chat: print('# - Converged after {0: 3d} iterations,  n = {1: .6f},  mu = {2: .6f}'\
	.format(k,float(n),float(mu)))
	return sp.array([n,mu,wzero,ErrMsg])
def original_tracking_radau_IIa_5th(current_time, psi, fhm, J_target, l, bn,
                                    tp, k1_0, k2_0, k3_0):
    alpha = [(2 / 5) - np.sqrt(6) / 10, (2 / 5) + np.sqrt(6) / 10, 1]
    beta = [[(11 / 45) - 7 * np.sqrt(6) / 360,
             (37 / 225) - 169 * np.sqrt(6) / 1800,
             -(2 / 225) + np.sqrt(6) / 75],
            [(37 / 225) + 169 * np.sqrt(6) / 1800,
             (11 / 45) + 7 * np.sqrt(6) / 360, -(2 / 225) - np.sqrt(6) / 75],
            [(4 / 9) - np.sqrt(6) / 36, (4 / 9) + np.sqrt(6) / 36, (1 / 9)]]

    k1, k2, k3 = fixed_point(tracking_radau_IIa_5th,
                             np.array([k1_0, k2_0, k3_0]),
                             args=(current_time, psi, fhm, J_target, l, bn, tp,
                                   alpha, beta))

    return [
        psi + ((4 / 9) - np.sqrt(6) / 36) * k1 +
        ((4 / 9) + np.sqrt(6) / 36) * k2 + (1 / 9) * k3, k1, k2, k3
    ]
Exemplo n.º 33
0
def calculate_c_baseline(c_L, Au_C, Au_L, deltaz):
    """Equations in the New_CST.pdf. Calculates the upper chord in order for
       the cruise and landing airfoils ot have the same length."""
    def integrand(psi, Au, delta_xi):
        return np.sqrt(1 + dxi_u(psi, Au, delta_xi)**2)

    def f(c_C):
        """Function dependent of c_C and that outputs c_C."""
        y_C, err = quad(integrand, 0, 1, args=(Au_C, deltaz / c_C))
        y_L, err = quad(integrand, 0, 1, args=(Au_L, deltaz / c_L))
        return c_L * y_L / y_C

    c_C = optimize.fixed_point(f, [c_L])
    #In case the calculated chord is really close to the original, but the
    #algorithm was not able to make them equal
    if abs(c_L - c_C) < 1e-7:
        return c_L
    #The output is an array so it needs the extra [0]
    return c_C[0]
Exemplo n.º 34
0
def _gauss6(f, t, y, h):
    """ One step Gauss6 for the autonomous system y'=f(y).

    This is implemented as an Runge-Kutta method.
    See Hairer, Lubich, Wanner, Geometric Numerical Integration, page 30.

    Input
        f   the right-hand side
        t   the initial time
        y   can either be a number for the initial value or a function whose
            value at t serves as the inital value and can be used for
            extrapolating initial guesses for the nonliear solver
        h   step size
    Output
        yn  the solution function on [t, t + h]
    """
    # Step 0: initialize
    (a, b, c) = _WEIGHTS  # get coefficients
    # Step 1: generate initial guess for stage values
    if hasattr(y, '__call__'):
        # y is a function => rename it to l and take y0=y(t)
        l = y
        y0 = y(t)
    else:
        # y is a single number => use the linear interpolant for initial guess
        l = BarycentricInterpolator([t, t + h], [y, y + h * f(y)])
        y0 = y
    # compute initial guess for stage values
    z = array([l(t + ci * h) - y0 for ci in c])

    # Step 2: solve for stage values
    # the nonlinear system associate with the stage values
    def eq(w):
        return h * a.dot(array([f(y0 + wi) for wi in w]))

    # solve using fixed point interation
    z = fixed_point(eq, z, xtol=DOLFIN_SQRT_EPS, maxiter=500000)

    # Step 3: construct the solution as the interpolant
    pts = array([t + ci * h for ci in c])
    return BarycentricInterpolator(pts, y0 + z)
Exemplo n.º 35
0
    def _kernel_do(self, g1, g2, lmda):

        # Frist, compute kernels between all pairs of nodes using the method borrowed
        # from FCSP. It is faster than directly computing all edge kernels
        # when $d_1d_2>2$, where $d_1$ and $d_2$ are vertex degrees of the
        # graphs compared, which is the most case we went though. For very
        # sparse graphs, this would be slow.
        vk_dict = self._compute_vertex_kernels(g1, g2)

        # Compute the weight matrix of the direct product graph.
        w_times, w_dim = self._compute_weight_matrix(g1, g2, vk_dict)
        # use uniform distribution if there is no prior knowledge.
        p_times_uni = 1 / w_dim
        p_times = np.full((w_dim, 1), p_times_uni)
        x = optimize.fixed_point(self._func_fp,
                                 p_times,
                                 args=(p_times, lmda, w_times),
                                 xtol=1e-06,
                                 maxiter=1000)
        # use uniform distribution if there is no prior knowledge.
        q_times = np.full((1, w_dim), p_times_uni)
        return np.dot(q_times, x)
Exemplo n.º 36
0
def plot_convergence():
    """Compare convergence of Newton's method, Broyden's method, and function iteration."""

    def f(x):
        fval = np.exp(x) - 1
        # Log x values in list x_values.
        x_values.append(x)
        return fval

    def get_log_error(x):
        return np.log10(np.abs(x)).flatten()

    # Newton's Method.
    x_values = []
    _ = newton(f, 2)
    error_newton = get_log_error(x_values)

    # Broyden's Method.
    x_values = []
    _ = broyden1(f, 2)
    error_broyden = get_log_error(x_values)

    # Function iteration.
    x_values = []
    _ = fixed_point(f, 2, xtol=1e-4)
    error_funcit = get_log_error(x_values)

    # Plot results.
    plt.figure(figsize=(10, 5))
    plt.plot(error_newton, label="Newton's Method")
    plt.plot(error_broyden, label="Broyden's Method")
    plt.plot(error_funcit, label="Function Iteration")
    plt.title(r"Convergence rates for $f(x)= exp(x)-1$ with $x_0=2$")
    plt.xlabel("Iteration")
    plt.ylabel("Log10 Error")
    plt.xlim(0, 50)
    plt.ylim(-6, 2)
    plt.legend()
Exemplo n.º 37
0
def iterate_capped_fp(fs, B_0, C_0, last_ell):
    '''performs one fixed point update with caps'''
    ellbar = [fs.c[i] if C_0[i] == 1 else 0 for i in range(fs.m)]
    Psi, psi = map_nnz_dim(np.ones(fs.m) - np.array(C_0))
    Psi_T = sparse.csr_matrix(Psi.T)
    Psi = sparse.csr_matrix(Psi)
    tgamma = Psi * fs.gamma * Psi_T
    tB = Psi * sparse.diags(B_0) * Psi_T
    tX = Psi * fs.X * Psi_T
    tv = Psi * (fs.s + fs.X * ellbar - fs.d)
    last_tell = Psi * last_ell

    def fun(tell, tB, tX, tgamma, tv):
        return tgamma * tB * (tX * tell + tv)

    tell = optimize.fixed_point(fun,
                                last_tell,
                                args=(tB, tX, tgamma, tv),
                                maxiter=2000)

    check = tX * tell + tv
    B_1 = [
        1 if B_0[i] == 1 else 1 if check[psi[i]] >= 0 else 0
        for i in range(fs.m)
    ]
    check = tgamma * check - Psi * fs.c
    C_1 = [
        1 if C_0[i] == 1 else 1 if check[psi[i]] >= 0 else 0
        for i in range(fs.m)
    ]
    '''
    if C_1 == C_0: #ell is overestimate of some values if C_1 != C[0]
        ell = Psi_T*tell + ellbar
    else:
        ell = last_ell
    '''
    ell = Psi_T * tell + ellbar
    return ell, B_1, C_1
    def _calc_scores_and_labels(self, x):
        # Assign equal weights to features
        feature_weights = np.full([1, x.shape[1]], 1/np.sqrt(x.shape[1]))
        labels = None
        for it in range(self.max_iterations):
            # Find clusters in the feature space, normalised by weights
            weighted_samples = feature_weights * x
            labels = KMeans().fit_predict(weighted_samples)

            # Compute objective vector of the method
            objective = Lasso._calc_objective_vector(x, labels)

            # Find parameter of threshold that optimizes L1-norm
            root = fixed_point(
                lambda delta: self._function_to_optimize(objective, delta),
                0
            )
            # Compute new feature weights
            new_weights = Lasso._calc_new_feature_weights(objective, root)
            if np.linalg.norm(new_weights - feature_weights) < self.eps:
                break
            feature_weights = new_weights
        return feature_weights[0], labels
Exemplo n.º 39
0
def _fp_labled_do(g1, g2, ds_attrs, node_kernels, node_label, edge_kernels,
                  edge_label, lmda):
    # Frist, compute kernels between all pairs of nodes, method borrowed
    # from FCSP. It is faster than directly computing all edge kernels
    # when $d_1d_2>2$, where $d_1$ and $d_2$ are vertex degrees of the
    # graphs compared, which is the most case we went though. For very
    # sparse graphs, this would be slow.
    vk_dict = computeVK(g1, g2, ds_attrs, node_kernels, node_label)

    # Compute weight matrix of the direct product graph.
    w_times, w_dim = computeW(g1, g2, vk_dict, ds_attrs, edge_kernels,
                              edge_label)
    # use uniform distribution if there is no prior knowledge.
    p_times_uni = 1 / w_dim
    p_times = np.full((w_dim, 1), p_times_uni)
    x = fixed_point(func_fp,
                    p_times,
                    args=(p_times, lmda, w_times),
                    xtol=1e-06,
                    maxiter=1000)
    # use uniform distribution if there is no prior knowledge.
    q_times = np.full((1, w_dim), p_times_uni)
    return np.dot(q_times, x)
Exemplo n.º 40
0
def get_ev(x):
    
    bgfr, nsyn_bg, nsyn_00, nsyn_01, nsyn_10, nsyn_11, delay = x
    f0_ss_internal, f1_ss_internal = sopt.fixed_point(steady_state_function, np.array([f0_ss, f1_ss]), args=x)
    A = L + (nsyn_bg*bgfr+nsyn_01*f0_ss_internal)*Se + nsyn_11*f1_ss_internal*Si     
    A[0,:] = 1       
    b = np.zeros(A.shape[0])
    b[0]=1
    p_star_internal = npla.solve(A,b)
    A0 = leak_matrix + (nsyn_bg*bgfr+nsyn_01*f0_ss_internal)*synaptic_matrix_bg + nsyn_11*(nsyn_bg*bgfr+nsyn_01*f0_ss_internal)*np.dot(p_star_internal,threshold_vector_bg)*synaptic_matrix_recc
    A1 = (nsyn_bg*bgfr+nsyn_01*f0_ss_internal)*nsyn_11*np.outer(synaptic_matrix_recc.dot(p_star_internal), threshold_vector_bg)
    n = A0.shape[0]
    N=6
    D=-cheb(N-1)*2/delay
    tmp1 = np.kron(D[:N-1,:], np.eye(n))
    tmp2 = np.hstack((A1,np.zeros((n,(N-2)*n)), A0))
    tmp3 = spsp.csr_matrix(np.vstack((tmp1, tmp2)))
    t0 = time.time()
    w = spsp.linalg.eigs(tmp3, 5, return_eigenvectors=False, which='LR', ncv=150)
    w_nonzero = [wi for wi in w if np.abs(wi) > 1e-8]
    w_crit = sorted(w_nonzero, key=lambda x:np.real(x))[-1]
    print delay, time.time() - t0, w_crit
    return w_crit
Exemplo n.º 41
0
def likelihood(theta):

    sigma = theta[0]
    alpha = theta[1]
    lamda = theta[2]

    global counts
    counts = counts+1
    print counts, "times likelihood"
    print "sigma = ",sigma, "alpha = ", alpha, "lamda = ", lamda

    #outline
    #2.compute V1
    #3.shooting method
    #4.derive likelihood
    
    #"=== 2 ==="
    #derive value and search cost of no insurance
    
    def value_noins(x):
        s = (alpha*lamda*(w-x))**(1/(1-lamda))
        v = (-s + alpha*(s**lamda) * (w-x)) / r
        return 0.9 * x + 0.1 * v

    print w, w-10
    v0 = fixed_point(value_noins, w-10)
    s0 = (alpha*lamda*(w-v0))**(1/(1-lamda))

    #"=== 3 ==="

    #shooting method

    #container of value and search cost during getting insurance
    value_ins = zeros(dts)
    scosts = zeros(dts)

    #substitute the value when t = T
    value_ins[dts-1] = v0
    scosts[dts-1] = s0

    #deribe previous value from current value and dt
    def value_prev(x,v_next):
        s = (alpha*lamda*(w-x))**(1/(1-lamda))
        v = ((b**(1-sigma))/(1-sigma) - s + alpha*(s**lamda) * (w-x) + (v_next - x) / dt) / r
        return 0.9 * x + 0.1 * v

    for i in range(dts-1):
        value_ins[dts-2-i] = fixed_point(value_prev, value_ins[dts-1-i] + 5 * dt, args=([value_ins[dts-1-i]]))
        scosts[dts-2-i] = (alpha*lamda*(w-value_ins[dts-2-i]))**(1/(1-lamda))
    #"=== 4 ==="

    #obtain likelihood when parameter and value of duration is given
    #by derive cumulative distribution function of search cost

    #compute hazard ratio (getting job rate)
    jrate = zeros(maxdts)
    for i in xrange(dts):
        jrate[i] = alpha * (scosts[i]**lamda)
    jrate[dts:maxdts] = alpha * (s0 ** lamda)
    
    #generate cumulative function
    cdf = zeros(maxdts-1)
    for i in xrange(maxdts-1):
        cdf[i] = 1 - exp(0 - (dt/2) * (sum(jrate[0:i]) + sum(jrate[0:i+1])))

    #deribe cumulative likelihood
    llh = 0
    for i in xrange(len(durs)):
        llh = llh + log(cdf[loc[i]])
    print "-likelihood = ", -llh
    print "========================="
    return -llh
Exemplo n.º 42
0
ofr = well_flow(t, 100, 0.28, 1/2)
history_data = [
    100,
    77,
    61,
    49.5,
    41,
    34.5,
]

params, _ = curve_fit(well_flow, t, history_data, p0=[100, 0.5, 1/3])
print(params)

plot.plot(t, well_flow(t, *params))
plot.plot(t, history_data, "ro")
plot.ylim(0, 100)

plot.show()

objfunc = lambda x: well_flow(x, 100, 0.28, 0.5) - 5
sol = root(objfunc, 10)
print(sol.x)


sol = fixed_point(well_flow, [5], (100, 0.28, 0.5))
print(sol)


y, _ = quad(well_flow, 0, 24.8, (100, 0.28, 1/2))
print(y*365)
Exemplo n.º 43
0
def functional_iteration(f, x0, tol=10**-16):
    """ Thin wrapper of optimize.fixed_point
    """
    return optimize.fixed_point(f, x0)
Exemplo n.º 44
0
def anderson(x,dist='norm'):
    """Anderson and Darling test for normal, exponential, or Gumbel
    (Extreme Value Type I) distribution.

    Given samples x, return A2, the Anderson-Darling statistic,
    the significance levels in percentages, and the corresponding
    critical values.

    Critical values provided are for the following significance levels
    norm/expon:   15%, 10%, 5%, 2.5%, 1%
    Gumbel:       25%, 10%, 5%, 2.5%, 1%
    logistic:     25%, 10%, 5%, 2.5%, 1%, 0.5%

    If A2 is larger than these critical values then for that significance
    level, the hypothesis that the data come from a normal (exponential)
    can be rejected.
    """
    if not dist in ['norm','expon','gumbel','extreme1','logistic']:
        raise ValueError, "Invalid distribution."
    y = sort(x)
    xbar = stats.mean(x)
    N = len(y)
    if dist == 'norm':
        s = stats.std(x)
        w = (y-xbar)/s
        z = distributions.norm.cdf(w)
        sig = array([15,10,5,2.5,1])
        critical = around(_Avals_norm / (1.0 + 4.0/N - 25.0/N/N),3)
    elif dist == 'expon':
        w = y / xbar
        z = distributions.expon.cdf(w)
        sig = array([15,10,5,2.5,1])
        critical = around(_Avals_expon / (1.0 + 0.6/N),3)
    elif dist == 'logistic':
        def rootfunc(ab,xj,N):
            a,b = ab
            tmp = (xj-a)/b
            tmp2 = exp(tmp)
            val = [sum(1.0/(1+tmp2),axis=0)-0.5*N,
                   sum(tmp*(1.0-tmp2)/(1+tmp2),axis=0)+N]
            return array(val)
        sol0=array([xbar,stats.std(x)])
        sol = optimize.fsolve(rootfunc,sol0,args=(x,N),xtol=1e-5)
        w = (y-sol[0])/sol[1]
        z = distributions.logistic.cdf(w)
        sig = array([25,10,5,2.5,1,0.5])
        critical = around(_Avals_logistic / (1.0+0.25/N),3)
    else:
        def fixedsolve(th,xj,N):
            val = stats.sum(xj)*1.0/N
            tmp = exp(-xj/th)
            term = sum(xj*tmp,axis=0)
            term /= sum(tmp,axis=0)
            return val - term
        s = optimize.fixed_point(fixedsolve, 1.0, args=(x,N),xtol=1e-5)
        xbar = -s*log(sum(exp(-x/s),axis=0)*1.0/N)
        w = (y-xbar)/s
        z = distributions.gumbel_l.cdf(w)
        sig = array([25,10,5,2.5,1])
        critical = around(_Avals_gumbel / (1.0 + 0.2/sqrt(N)),3)
    i = arange(1,N+1)
    S = sum((2*i-1.0)/N*(log(z)+log(1-z[::-1])),axis=0)
    A2 = -N-S
    return A2, critical, sig
Exemplo n.º 45
0
      
    b = np.zeros(A.shape[0])
    b[0]=1
       
    # Solve for steady state:
    try:
        p_star = npla.solve(A,b)
    except npla.linalg.LinAlgError:
          
        p_star = spsp.linalg.spsolve(A,b)
          
     
    # Steady state firing rate
    return np.dot(p_star, (bgfr*nsyn_bg+nsyn_recc*ss_fr_guess)*threshold_vector)
    
ss_fr = sopt.fixed_point(f, 12)
A = leak_matrix + (nsyn_bg*bgfr+nsyn_recc*ss_fr)*synaptic_matrix
A[0,:] = 1
b = np.zeros(A.shape[0])
b[0]=1
p_star = spsp.linalg.spsolve(A,b)
 
 
# alpha = np.dot(p_star, threshold_vector)
#  
# # print 1-nsyn_recc*alpha
# # 
# # sys.exit()
# f0 = synaptic_matrix.dot(p_star)
# f1 = threshold_vector/((1-nsyn_recc*alpha)**2)  
# M = np.outer(f0,f1)
Exemplo n.º 46
0
    b = np.zeros(A.shape[0])
    b[0]=1
    f0_new = np.dot(npla.solve(A,b), (bgfr*nsyn_bg+nsyn_00*f0)*te)
    
    # Population 1:
    A = L + (nsyn_bg*bgfr+nsyn_01*f0)*Se + nsyn_11*f1*Si     
    A[0,:] = 1       
    b = np.zeros(A.shape[0])
    b[0]=1
    f1_new = np.dot(npla.solve(A,b), (bgfr*nsyn_bg+nsyn_01*f0)*te)
    
    return np.array([f0_new, f1_new])


# Compute steady state:
f0_ss, f1_ss = sopt.fixed_point(steady_state_function, np.array([14,9]), args=(bgfr, nsyn_bg, nsyn_00, nsyn_01, nsyn_10, nsyn_11, delay))

# Compute initial guesses for eigenvector and eigenvalue:
# # Components:
b1 = ExternalPopulation(bgfr, record=True)
i1 = InternalPopulation(tau_m=.05, v_min=0, v_max=1, dv=dv, update_method = 'gmres')
b1_i1 = Connection(b1, i1, nsyn_bg, weights=we, delays=0.0)
i1_i1 = Connection(i1, i1, 0, weights=wi, delays=0.0)
 
def cheb(N):
    x = np.cos(np.pi*np.arange(N+1)/N)
    c = np.array([2] + [1]*(N-1) + [2])*np.array([(-1)**ii for ii in range(N+1)])
    X = npm.repmat(x,1,N+1).reshape(N+1,N+1).T
    dX = X-X.T
    D = (np.outer(c,1./c))/(dX+(np.eye(N+1)))#      % off-diagonal entries
    return D - np.diag(np.sum(D, axis=1))#, x#;                 % diagonal entries
Exemplo n.º 47
0
def anderson(x,dist='norm'):
    """
    Anderson-Darling test for data coming from a particular distribution

    The Anderson-Darling test is a modification of the Kolmogorov-
    Smirnov test kstest_ for the null hypothesis that a sample is
    drawn from a population that follows a particular distribution.
    For the Anderson-Darling test, the critical values depend on
    which distribution is being tested against.  This function works
    for normal, exponential, logistic, or Gumbel (Extreme Value
    Type I) distributions.

    Parameters
    ----------
    x : array_like
        array of sample data
    dist : {'norm','expon','logistic','gumbel','extreme1'}, optional
        the type of distribution to test against.  The default is 'norm'
        and 'extreme1' is a synonym for 'gumbel'

    Returns
    -------
    A2 : float
        The Anderson-Darling test statistic
    critical : list
        The critical values for this distribution
    sig : list
        The significance levels for the corresponding critical values
        in percents.  The function returns critical values for a
        differing set of significance levels depending on the
        distribution that is being tested against.

    Notes
    -----
    Critical values provided are for the following significance levels:

    normal/exponenential
        15%, 10%, 5%, 2.5%, 1%
    logistic
        25%, 10%, 5%, 2.5%, 1%, 0.5%
    Gumbel
        25%, 10%, 5%, 2.5%, 1%

    If A2 is larger than these critical values then for the corresponding
    significance level, the null hypothesis that the data come from the
    chosen distribution can be rejected.

    References
    ----------
    .. [1] http://www.itl.nist.gov/div898/handbook/prc/section2/prc213.htm
    .. [2] Stephens, M. A. (1974). EDF Statistics for Goodness of Fit and
           Some Comparisons, Journal of the American Statistical Association,
           Vol. 69, pp. 730-737.
    .. [3] Stephens, M. A. (1976). Asymptotic Results for Goodness-of-Fit
           Statistics with Unknown Parameters, Annals of Statistics, Vol. 4,
           pp. 357-369.
    .. [4] Stephens, M. A. (1977). Goodness of Fit for the Extreme Value
           Distribution, Biometrika, Vol. 64, pp. 583-588.
    .. [5] Stephens, M. A. (1977). Goodness of Fit with Special Reference
           to Tests for Exponentiality , Technical Report No. 262,
           Department of Statistics, Stanford University, Stanford, CA.
    .. [6] Stephens, M. A. (1979). Tests of Fit for the Logistic Distribution
           Based on the Empirical Distribution Function, Biometrika, Vol. 66,
           pp. 591-595.

    """
    if not dist in ['norm','expon','gumbel','extreme1','logistic']:
        raise ValueError, "Invalid distribution."
    y = sort(x)
    xbar = np.mean(x, axis=0)
    N = len(y)
    if dist == 'norm':
        s = np.std(x, ddof=1, axis=0)
        w = (y-xbar)/s
        z = distributions.norm.cdf(w)
        sig = array([15,10,5,2.5,1])
        critical = around(_Avals_norm / (1.0 + 4.0/N - 25.0/N/N),3)
    elif dist == 'expon':
        w = y / xbar
        z = distributions.expon.cdf(w)
        sig = array([15,10,5,2.5,1])
        critical = around(_Avals_expon / (1.0 + 0.6/N),3)
    elif dist == 'logistic':
        def rootfunc(ab,xj,N):
            a,b = ab
            tmp = (xj-a)/b
            tmp2 = exp(tmp)
            val = [sum(1.0/(1+tmp2),axis=0)-0.5*N,
                   sum(tmp*(1.0-tmp2)/(1+tmp2),axis=0)+N]
            return array(val)
        sol0=array([xbar,np.std(x, ddof=1, axis=0)])
        sol = optimize.fsolve(rootfunc,sol0,args=(x,N),xtol=1e-5)
        w = (y-sol[0])/sol[1]
        z = distributions.logistic.cdf(w)
        sig = array([25,10,5,2.5,1,0.5])
        critical = around(_Avals_logistic / (1.0+0.25/N),3)
    else:
        def fixedsolve(th,xj,N):
            val = stats.sum(xj)*1.0/N
            tmp = exp(-xj/th)
            term = sum(xj*tmp,axis=0)
            term /= sum(tmp,axis=0)
            return val - term
        s = optimize.fixed_point(fixedsolve, 1.0, args=(x,N),xtol=1e-5)
        xbar = -s*log(sum(exp(-x/s),axis=0)*1.0/N)
        w = (y-xbar)/s
        z = distributions.gumbel_l.cdf(w)
        sig = array([25,10,5,2.5,1])
        critical = around(_Avals_gumbel / (1.0 + 0.2/sqrt(N)),3)
    i = arange(1,N+1)
    S = sum((2*i-1.0)/N*(log(z)+log(1-z[::-1])),axis=0)
    A2 = -N-S
    return A2, critical, sig
Exemplo n.º 48
0
def flap_multiobjective(airfoil, chord, J, sma, linear, sigma_o, W, r_w, V,
         altitude, alpha, T_0, T_final, MVF_init, n, R, all_outputs = False,
         import_matlab = True, eng = None, aero_loads = True, 
         cycling = 'False', n_cycles = 0):
    """
    solve actuation problem for flap driven by an antagonistic mechanism
    using SMA and linear actuators
    :param J: dictionary with coordinates of Joint
    :param sigma_o: pre-stress, if not defined, it calculates the biggest
                    one respecting the constraints (max is H_max)
    :param T_0: initial temperature
    :param T_final: final temperature
    :param MVF_init: initial martensitic volume fraction
    :param n: number of steps in simulation"""
    
    from scipy.interpolate import interp1d
    import pickle
    import os.path
 
    if import_matlab and eng == None:
        import matlab.engine
        #Start Matlab engine
        eng = matlab.engine.start_matlab()
        #Go to directory where matlab file is
        if import_matlab:
            eng.cd(' ..')
            eng.cd('SMA_temperature_strain_driven')
        else:
            eng.cd('SMA_temperature_strain_driven')
            
    def constitutive_model(T, MVF_init, i, n, eps, eps_t_0, sigma_0 = 0,
            eps_0 = 0, plot = 'True'):
        """Run SMA model
        
        - all inputs are scalars"""
        k = i+1
        if k == n:
            data = eng.OneD_SMA_Model(k, eps, T, MVF_init, 
                                      eps_t_0, sigma_0, eps_0, n, plot,
                                      nargout=6) 
        else:
            data = eng.OneD_SMA_Model(k, eps, T, MVF_init,
                                      eps_t_0, sigma_0, eps_0, n, 'False',
                                      nargout=6)
        return data

    def equilibrium(eps_s, s, l, T, MVF_init, sigma_0,
                   i, n, r_w, W, x = None, y = None, alpha = 0.,
                   q = 1., chord = 1., x_hinge = 0.25, aero_loads = aero_loads,
                   return_abs = False):
        """Calculates the moment equilibrium. Function used for the 
        secant method.
        """
        #calculate new theta for eps_s and update all the parameter
        #of the actuator class
        s.eps = eps_s
#        print s.eps, s.eps_0, s.r_1, s.r_2, s.r_1_0, s.r_2_0, s.max_eps, s.min_eps
#        print s.min_theta, s.max_theta
#        try:
#        print eps_s
        s.calculate_theta(theta_0 = s.theta)
#        except:
#            s.theta = max(s.max_theta, l.max_theta)
#            s.update()
#            l.theta = max_theta
#            l.update()
#            plot_flap(x, y, J['x'], -s.theta)
#            raise Exception("Inverse solution for theta did not converge")
        s.update()
        
        l.theta = s.theta
        l.update()
        #SMA (Constitutive equation: coupling via sigma)
        data = constitutive_model(T, MVF_init, i, n, eps_s,
                                  eps_t_0, sigma_0, s.eps_0, plot = 'False')
        
        s.sigma = data[0][i][0]
        s.calculate_force(source = 'sigma')
        tau_s = s.calculate_torque()
        
        #Linear (Geometric equation: coupling via theta)
        l.calculate_force()
        tau_l = l.calculate_torque()
        
        #weight (Geometric equation: coupling via theta)
        tau_w = - r_w*W*math.cos(l.theta)

        #aerodynamic (Panel method: coupling via theta)
        if aero_loads:
            # The deflection considered for the flap is positivite in
            # the clockwise, contrary to the dynamic system. Hence we need
            # to multiply it by -1.
#            print alpha, x_hinge, l.theta
            if abs(l.theta) > math.pi/2.:
                tau_a = - np.sign(l.theta)*4
            else:
                Cm = Cm_function(l.theta)
                tau_a = Cm*q*chord**2
#            Cm = calculate_flap_moment(x, y, alpha, x_hinge, - l.theta,
#                                       unit_deflection = 'rad')
        else:
            tau_a = 0.
            
#        print 'tau', tau_s, tau_l, tau_w, tau_a, tau_s + tau_l + tau_w + tau_a
        f = open('data', 'a')
        f.write('\t Inner loop 1\t'+ str(T[i]) + '\t' + str( eps_s) + '\t' + \
                str( tau_s + tau_l + tau_w + tau_a) + '\t' + str( tau_s) + '\t' + str(tau_l) + '\t' + str(tau_w) + '\t' + str(tau_a) + '\t' + \
                str(l.theta)  + '\n')
        f.write('\t ' + str(i) + '\t' + str(n) +'\n')
        f.write('\t ' + str(l.F) + '\t' + str(s.F) + '\n')
        f.close()
        if return_abs:
            return abs(tau_s + tau_l + tau_w + tau_a)
        else:
            return tau_s + tau_l + tau_w + tau_a

    def eps_s_fixed_point(eps_s, s, l, T, MVF_init, sigma_0,
                   i, n, r_w, W, x = None, y = None, alpha = 0.,
                   q = 1., chord = 1., x_hinge = 0.25, aero_loads = aero_loads,
                   return_abs = False):
        """Calculates the SMA strain. Function used for the 
        fixed position iteration method. Restriction d epsilon_s / dt < 1.
        """
        #calculate new theta for eps_s and update all the parameter
        #of the actuator class
        s.eps = eps_s
#        print 'eps_s: ', eps_s
        s.calculate_theta(theta_0 = s.theta)
        s.update()
        
        l.theta = s.theta
        l.update()
        #SMA (Constitutive equation: coupling via sigma)
        data = constitutive_model(T, MVF_init, i, n, eps_s,
                                  eps_t_0, sigma_0, s.eps_0, plot = 'False')
        
        s.sigma = data[0][i][0]
        s.calculate_force(source = 'sigma')
        tau_s = s.calculate_torque()
        
        #Linear (Geometric equation: coupling via theta)
        l.calculate_force()
        tau_l = l.calculate_torque()
        
        #weight (Geometric equation: coupling via theta)
        tau_w = - r_w*W*math.cos(l.theta)

        #aerodynamic (Panel method: coupling via theta)
        if aero_loads:
            # The deflection considered for the flap is positivite in
            # the clockwise, contrary to the dynamic system. Hence we need
            # to multiply it by -1.
            if abs(l.theta) > math.pi/2.:
                tau_a = - np.sign(l.theta)*4
            else:
                Cm = Cm_function(l.theta)
                tau_a = Cm*q*chord**2
        else:
            tau_a = 0.
        
        B = tau_s/s.sigma
        eps_t = data[3][i][0] 
        E = data[5][i][0] 
        eps_s = eps_t - (tau_l + tau_w + tau_a)/(B*E)
        
#        print 'tau', tau_s, tau_l, tau_w, tau_a, tau_s + tau_l + tau_w + tau_a
        f = open('data', 'a')
        f.write('\t Inner loop 2\t'+ str(T[i]) + '\t' + str( eps_s) + '\t' + \
                str( tau_s + tau_l + tau_w + tau_a) + '\t' + str( tau_s) + '\t' + str(tau_l) + '\t' + str(tau_w) + '\t' + str(tau_a) + '\t' + \
                str(l.theta)  + '\n')
        f.close()        
        return eps_s
            
    def deformation_theta(theta = -math.pi/2., plot = False):
        """Return lists of deformation os SMA actuator per theta"""
        
        theta_list = np.linspace(-theta, theta)
        eps_s_list = []
        eps_l_list = []
        
        for theta in theta_list:
            s.theta = theta
            l.theta = theta
            
            s.update()
            l.update()
            
            l.calculate_force()
            
            eps_s_list.append(s.eps)
            eps_l_list.append(l.eps)
        if plot:
            import matplotlib.pyplot as plt
            plt.figure()
            plt.plot(np.degrees(theta_list), eps_s_list, 'r', np.degrees(theta_list), eps_l_list, 'b')  
            plt.xlabel('$\\theta (degrees)$')
            plt.ylabel('$\epsilon$')
    
        return eps_s_list, theta_list

    def plot_flap(x, y, x_J, y_J = None, theta = 0):
        """
        Plot flap with actuators. theta is clockwise positive.
        @Author: Endryws (modified by Pedro Leal)
        
        Created on Fri Mar 18 14:26:54 2016
        """
        import matplotlib.pyplot as plt
        plt.figure()
        x_dict, y_dict = af.separate_upper_lower(x, y)
        
        # Below I create the dictionarys used to pass to the function find_hinge
        upper = {'x': x_dict['upper'], 'y': y_dict['upper']} # x and y upper points
        lower = {'x': x_dict['lower'], 'y': y_dict['lower']} # x and y lower points
        hinge = af.find_hinge(x_J, upper, lower) 
        
        #=======================================================================
        # With the Joint (hinge) point, i can use the find flap function to
        # found the points of the flap in the airfoil.
        #=======================================================================
        
        data = {'x': x, 'y': y}
        static_data, flap_data = af.find_flap(data, hinge)
        R = hinge['y_upper']
        theta_list = np.linspace(3*math.pi/2, math.pi/2, 50)
        x_circle_list = hinge['x'] + R*np.cos(theta_list)
        y_circle_list = hinge['y'] + R*np.sin(theta_list)

        n_upper = len(flap_data['x'])/2
        
        # Ploting the flap in the original position
        plt.plot(flap_data['x'][:n_upper],flap_data['y'][:n_upper],'k--')
        plt.plot(flap_data['x'][n_upper:],flap_data['y'][n_upper:],'k--')         
        # Rotate and plot
        upper = {'x': np.concatenate((flap_data['x'][:n_upper], x_circle_list)),
                 'y': np.concatenate((flap_data['y'][:n_upper], y_circle_list))}
        lower = {'x':(flap_data['x'][n_upper:]),
                 'y':(flap_data['y'][n_upper:])}
                
        rotated_upper, rotated_lower = af.rotate(upper, lower, hinge, theta, 
                                                 unit_theta = 'rad')
        plt.plot(static_data['x'], static_data['y'],'k')
        
        plt.plot(rotated_upper['x'], rotated_upper['y'],'k')
        plt.plot(rotated_lower['x'], rotated_lower['y'],'k')
        plt.axes().set_aspect('equal')
        
        s.plot_actuator()
        l.plot_actuator()
        
        if y_J != None:
            for i in range(y_J):
                plt.scatter(x_J , y_J[i])
        plt.grid()
        plt.locator_params(axis = 'y', nbins=6)
        plt.xlabel('${}_{I}x + x_J$')
        plt.ylabel('${}_{I}y$')
        border = 0.05
        plt.xlim(-border, 1+border)
        plt.savefig( str(np.floor(100*abs(theta))) + "_configuration.png")
        plt.close()

#==============================================================================
# Material and flow properties
#==============================================================================
    #SMA properties
    E_M = 8.8888e+10
    E_A = 3.7427e+10
    sigma_crit = 0
    H_max = 0.0550
    H_min = 0.0387
    k = 4.6849e-09
    
    Air_props= air_properties(altitude, unit='feet')
    rho = Air_props['Density']
    q = 0.5*rho*V**2

    #Spring properties(Squared or closed)
    C = 10. #Spring index
    Nt = 17. #Total number of springs
    safety_factor = 5.
    A = 2211e6*10**(0.435) #Mpa.mm**0.125
    
#===========================================================================
# Generate Temperature arrays
#===========================================================================
    if n_cycles == 0:
        T = np.linspace(T_0, T_final, n)
    else:
        T = np.append(np.linspace(T_0, T_final, n),
                      np.linspace(T_final, T_0, n))
        for i in range(n_cycles-1):
            T = np.append(T,T)
    T = list(T)
#===========================================================================
# Generate airfoil (NACA0012)
#===========================================================================
    xf.call(airfoil, output='Coordinates')
    filename = xf.file_name(airfoil, output='Coordinates')
    Data = xf.output_reader(filename, output='Coordinates',
                            header = ['x','y'])
    #The coordinates from Xfoil are normalized, hence we have to multiply
    #by the chord
    x = []
    y = []
    for i in range(len(Data['x'])):
        x.append( Data['x'][i]*chord )
        y.append( Data['y'][i]*chord )
    
    filename = airfoil + '_' + str(int(100*J['x'])) + '_' + \
               str(int(100*chord)) + '.p'
    
    #Generate aerodynamic moment data. If already exists, load it
    if os.path.isfile(filename):
        with open(filename, "rb") as f:
            Cm_list = pickle.load( f )
            theta_list = pickle.load( f )
    else:
        theta_list = np.linspace(-math.pi/2., math.pi/2., 100)
        Cm_list = []
        for theta in theta_list:
            Cm = calculate_flap_moment(x, y, alpha, J['x'], - theta,
                                       unit_deflection = 'rad')
            Cm_list.append(Cm)
        with open(filename, "wb") as f:
            pickle.dump( Cm_list, f )
            pickle.dump( theta_list, f )
        
    Cm_function = interp1d(theta_list, Cm_list)
#===========================================================================
# SMA actuator  
#===========================================================================
    #Initial transformation strain
    eps_t_0 = H_min + (H_max - H_min)*(1. - math.exp(-k*(abs(sigma_o) - \
                                                     sigma_crit)))
    #Define initial strain
    eps_0 = eps_t_0 + sigma_o/E_M
    #Sma actuator (s)
    s = actuator(sma, J, eps_0 = eps_0, material = 'SMA', design = 'B',
                 R = R)

    #Check if crossing joint. If True do nothing
    if s.check_crossing_joint(tol = 0.0009):
        print '1'
        if all_outputs:
            return [s.eps_0], [0], [s.theta], [sigma_o], [1.], [T[0]], [eps_t_0], [s.theta], [0], [0], [s.length_r]
        else:
            return s.theta, 9999.
    else:
        #Input initial stress   
        s.sigma = sigma_o
        s.calculate_force(source = 'sigma')
        s.eps_t_0 = eps_t_0
    
        if alpha != 0.:
            raise Exception('The initial equilibirum equation only ' + \
                            'makes sense for alpha equal to zero!!')
        s.update()
        #Calculate initial torques
        s.calculate_torque()   
        
        tau_w = - r_w*W 

        if aero_loads:
            # The deflection considered for the flap is positivite in
            # the clockwise, contrary to the dynamic system. Hence we need
            # to multiply it by -1.
            Cm = Cm_function(s.theta)
            tau_a = Cm*q*chord**2
        else:
            tau_a = 0.

#===========================================================================
# Linear actuator
#===========================================================================
        #Linear actuator (l)
        l = actuator(linear, J, material = 'linear', design = 'B', R=R)
        l.theta = s.theta

        #Check if crossing joint. If True do nothing
        if l.check_crossing_joint(tol = 0.001):
            if all_outputs:
                return [s.eps_0], [0], [s.theta], [sigma_o], [1.], [T[0]], [eps_t_0], [s.theta], [0], [0], [s.length_r]
            else:
                return s.theta, 9999.
        else:        
            #l.k = - (s.torque + tau_w + tau_a)/(l.eps*(l.y_p*l.r_1 - l.x_p*l.r_2))

            l.F =  (s.torque + tau_w + tau_a)/l.R
#            print 'force: ', l.F, s.torque, s.torque + tau_w + tau_a
            #Spring components
            if l.F < 0:
                l.d = (safety_factor*(2*C+1)*abs(1.5*l.F)/(0.1125*A*math.pi))**(1./1.855)
            else:
                l.d = (safety_factor*(C*(4*C+2)/(4*C-3))*abs(1.5*l.F)/(0.05625*A*math.pi))**(1./1.855)

            l.D = C*l.d
            
            if l.d < 0.000838:
                G = 82.7e9
                E = 203.4e9
            elif l.d < 0.0016:
                G = 81.7e9
                E = 200.0e9
            elif l.d < 0.00318:
                G = 81.0e9
                E = 196.6e9
            else:
                G = 80.0e9
                E = 193.0e9

            if l.F < 0:
                Na = Nt - 2 #Active number of springs
            else:
                Nt = (E*G*l.d*l.length_r_0 + (1.-2.*C)*E*G*l.d**2 - \
                     8.*l.F*G*C**3)/(E*G*l.d**2 + 8.*E*l.F*C**3)
                Na = Nt + G/E #Equivalent active number of springs
#                print "Ns", Nt, Na
            l.N = Nt    
            l.k = l.d**4*G/(8*l.D**3*Na)
            
            if l.F < 0.:
                l.zero_stress_length = -l.F/l.k + l.length_r_0
                l.solid = (Nt + 1)*l.d
            else:
                l.zero_stress_length = (2*C - 1 + Nt)*l.d
                l.solid = l.zero_stress_length
      
            l.update()
            l.eps_0 = l.eps
            l.calculate_force(source = 'strain')
            l.calculate_torque()
#            print "torque: ", l.torque
            l.calculate_theta()
#            print s.torque, s.eps_0, s.eps, l.eps, l.torque, s.torque + tau_w + \
#                    tau_a + l.torque
            t = 0.12
            
            y_J = af.Naca00XX(chord, t, [J['x']], return_dict = 'y')
            
            l.find_limits(y_J, theta_0 = 0)
    
#            print 's: limits', s.max_theta, s.min_theta
#            print s.max_theta_A, s.max_theta_B
#            print 'l: limits', l.max_theta, l.min_theta
#            print l.max_theta_A, l.max_theta_B
#            plot_flap(x, y, J['x'], theta= 0.)
            if l.pulley_position == "down":
                max_theta = min(l.max_theta, math.pi/2)
            elif l.pulley_position == "up":
                max_theta = max(l.max_theta, -math.pi/2)
        ##==============================================================================
        # Matlab simulation
        ##==============================================================================         
            eps_s = eps_0
            eps_s_list = [eps_s]
            eps_l_list = [l.eps]
            theta_list = [s.theta]
            F_l_list =[l.calculate_force()]
            L_s_list = [s.length_r]
            #Because of the constraint of the maximum deflection, it is possible that
            #the number of steps is smaller than n
            n_real = 1
            
#            plot_flap(x, y, J['x'], theta= -s.theta)
            
            #Create new data file and erase everything inside
            f = open('data', 'w')
            f.close()
            
            if n_cycles == 0:
                iterations = n
            else:
                iterations = 2*n*n_cycles
            #original number of steps without any restrictions
            n_o = n

            eps_s_prev = [eps_0, eps_0]
            for i in range(1, iterations):
                #because n_real can be different of n, it is posssible that
                #i is greater than the actual number of iterations. Need
                #to break
                if i == iterations:
                    break
                
                #Linear prediction 
                delta_eps = eps_s_prev[1] - eps_s_prev[0]
                #Correction with fixed point iteration
                try:
                    eps_s = fixed_point(eps_s_fixed_point, eps_s + delta_eps, args=((s, l, T, 
                                           MVF_init, sigma_o, i, n, r_w, W, x, y, alpha, 
                                           q, chord, J['x'], True)), xtol = 1e-8)
                except:
#                    eps_s = fixed_point(eps_s_fixed_point, eps_s, args=((s, l, T, 
#                           MVF_init, sigma_o, i, n, r_w, W, x, y, alpha, 
#                           q, chord, J['x'], True)), xtol = 1e-8)
                    eps_s_start = eps_s + delta_eps
                    for j in range(10):
                        try:
                            eps_s = fixed_point(eps_s_fixed_point, eps_s_start, args=((s, l, T, 
                                                   MVF_init, sigma_o, i, n, r_w, W, x, y, alpha, 
                                                   q, chord, J['x'], True)), xtol = 1e-8)
                            break
                        except:
                            eps_s_start  = eps_s_start*float(j)/10.
                eps_s_prev[0] = eps_s_prev[1]
                eps_s_prev[1] = eps_s

                s.eps = eps_s
                s.calculate_theta(theta_0 = s.theta)
                s.update()
                
                f = open('data', 'a')
                f.write('Outer loop \t'+ str(i)  + '\t'+ str(eps_s) + '\t'+ str(s.theta)+ '\n')
                f.close()
#                print 'new theta: ', s.theta
                #stop if actuator crosses joints, exceds maximum theta and theta is positively increasing
#                print l.r_1,  l.r_2
#                print s.check_crossing_joint(tol = 0.001), l.check_crossing_joint(tol = 0.001), s.theta, l.length_r, l.solid
                if s.check_crossing_joint(tol = 0.001) or l.check_crossing_joint(tol = 0.001) or l.length_r <= l.solid:
                    if n_cycles == 0:
                        iterations = n_real
                        T = T[:n_real]
                        break
                    else:
                        n = n_real #+ 10
                        iterations = 2*n_real*n_cycles
                        T_cycle = T[:n_real]  + T[:n_real][::-1] #+ 10*[T[n_real-1]]
                        T = T_cycle
                        for k in range(n_cycles-1):
                            T += T_cycle
                        #Correction with fixed point iteration
                            eps_s = fixed_point(eps_s_fixed_point, eps_s_prev[1], args=((s, l, T, 
                                                   MVF_init, sigma_o, i, n, r_w, W, x, y, alpha, 
                                                   q, chord, J['x'], True)), xtol = 1e-8)
                        eps_s_prev[0] = eps_s_prev[1]
                        eps_s_prev[1] = eps_s
                        
                        s.eps = eps_s
                        s.calculate_theta(theta_0 = s.theta)
                        s.update()
                        
                else:
                    if n != n_real:
                        n_real +=1
                    if n_o == n_real:
                        n = n_real #+ 10
                        if n_cycles == 0:
                            iterations = n_real
                        else:
                            iterations = 2*n_real*n_cycles
                            T_cycle = T[:n_real]  + T[:n_real][::-1] #+ 10*[T[n_real-1]]
                            T = T_cycle
                            for k in range(n_cycles-1):
                                T += T_cycle
                l.theta = s.theta
                l.update()
                
                eps_s_list.append(eps_s)
                eps_l_list.append(l.eps)
                theta_list.append(s.theta)
                F_l_list.append(l.calculate_force())
                L_s_list.append(s.length_r)
    
#            print 'final theta: ', s.theta
            if all_outputs:
#                print "Nt: %.4f , Na: %.4f, d: %.5f, D: %.4f, L: %.4f, solid length: %.4f, final_L: %.4f" % (Nt, Na, l.d , l.D, l.zero_stress_length, l.solid, l.length_r)
#                s.theta = theta_list[-1]
#                l.theta = s.theta
#                s.update()
#                l.update()
#                plot_flap(x, y, J['x'], theta= -s.theta)
#                
#                s.theta = 0.
#                l.theta = s.theta
#                s.update()
#                l.update()
#                plot_flap(x, y, J['x'], theta= -s.theta)

                if n_real == 1:
                    return [s.eps_0], [l.eps], [s.theta], [sigma_o], [1.], [T[0]], [eps_t_0], [s.theta], [0], [0], [s.length_r]
                else:
                    #Extra run with prescribed deformation (which has already been calculated)
                    # to get all the properties]
                    #TODO: include back n_real
                    for i in range(1, iterations):
                        data = constitutive_model(T, MVF_init, i, iterations, 
                                                  eps_s_list[i], eps_t_0,
                                                  sigma_0 = sigma_o,
                                                  eps_0 = eps_0, 
                                                  plot = 'False')
                    delta_xi = 1. - data[1][-1][0]
                    
                    sigma_list = []
                    for i in range(len(data[0])):
                        sigma_list.append(data[0][i][0])
                    MVF_list = []
                    for i in range(len(data[1])):
                        MVF_list.append(data[1][i][0])    
                    eps_t_list = []
                    for i in range(len(data[3])):
                        eps_t_list.append(data[3][i][0])
                    return eps_s_list, eps_l_list, theta_list, sigma_list, MVF_list, T, eps_t_list, theta_list, F_l_list, l.k, L_s_list
            else:
#                print theta_list
                return theta_list[-1], l.k
Exemplo n.º 49
0
def compute_optimal_pension(e, ea, rev_smic_chef, rev_smic_part, temps_garde, uc_parameters=None, criterium=None, disabled=None):
    """
    Return optimal pension according to different criteria
    
    Parameters
    ----------
    e : number of kids 
    ea : number of teenagers
    rev_smic_chef : revenue of the non custodian parent (in SMIC)
    rev_smic_part : revenue of the custodian parent (in SMIC)
    temps_garde : type of custody
    uc_parameters : parameters to compute the household consumption units
    criterium : the normative criteria used to compute the optimal pension
    disabled : the disabled presattions of the socio-fiscal model
    
    Returns
    -------
    optimal_pension : the optimal pension  
    """
    EPS = 1e-3
    
    from scipy.optimize import fixed_point, fsolve
    from scripts.unaf import get_unaf
    dep_decent_unaf = get_unaf(e, ea)
    dep_decent_unaf2 = get_unaf(e, ea, a=1)

    # Define a useful function
    def func_optimal_pension(pension):
         
        if disabled is None:
            dis =  ["asf"]
        elif "asf" not in disabled:
            dis = disabled + ['asf']
            
        df = get_results_df(e, ea, rev_smic_chef, rev_smic_part, temps_garde, uc_parameters=uc_parameters, pension=pension, disabled=dis)
        print df.to_string()
        df = df.set_index([u"ménage"])
        private_cost_after = ( df.get_value(u"chef", u"prise en charge privée de l'enfant") +
                             df.get_value(u"part", u"prise en charge privée de l'enfant") )
        revdisp_chef = df.get_value(u"chef", u"revdisp")
        revdisp_part = df.get_value(u"part", u"revdisp")
        
        total_cost_after_chef = df.get_value(u"chef", u"dépense totale pour enfants")
        total_cost_after_part = df.get_value(u"part", u"dépense totale pour enfants")
        total_cost_before = df.get_value(u"couple", u"dépense totale pour enfants")
        public_cost_after_chef = df.get_value(u"chef", u"prise en charge publique de l'enfant")
        public_cost_after_part = df.get_value(u"part", u"prise en charge publique de l'enfant")

        nivvie_chef_after = df.get_value(u"chef", u"nivvie")
        nivvie_part_after = df.get_value(u"part", u"nivvie")
        nivvie_chef_before = df.get_value(u"chef", u"nivvie")/df.get_value(u"chef", u"nivvie_loss")
        nivvie_part_before = df.get_value(u"part", u"nivvie")/df.get_value(u"part", u"nivvie_loss")
        
#        opt_pension = private_cost_after*(revdisp_chef + pension)/(revdisp_chef+revdisp_part) - total_cost_after_chef + public_cost_after_chef

        private_cost_after_chef = df.get_value(u"chef", u"prise en charge privée de l'enfant")        
        private_cost_after_part = df.get_value(u"part", u"prise en charge privée de l'enfant")
        private_cost_before = df.get_value(u"couple", u"prise en charge privée de l'enfant")
        

        if criterium == "revdisp":
            opt_pension = private_cost_after*revdisp_chef/(revdisp_chef+revdisp_part)-private_cost_after_chef
        elif criterium == "nivvie":
            opt_pension = private_cost_after*nivvie_chef_after/(nivvie_chef_after+nivvie_part_after)-private_cost_after_chef
        elif criterium == "revdisp_pyc":
            opt_pension = private_cost_after*(revdisp_chef+pension)/(revdisp_chef+revdisp_part)-private_cost_after_chef    
        elif criterium == "jacquot":
            alpha = uc_parameters['alpha']
            beta  = uc_parameters['beta']
            gamma = uc_parameters['gamma']
            A = (.3*e + .5*ea)/(1 + .3*e + .5*ea)
            B = (alpha*gamma*(.3*e + .5*ea))/(1 + alpha*gamma*(.3*e + .5*ea))
            C = 1 + .3*e + .5*ea
            D = 1 + alpha*gamma*(.3*e + .5*ea)
            opt_pension = ((A-B)*revdisp_chef*revdisp_part)/((revdisp_chef/C) + (revdisp_part/D))
        elif criterium == "share_private_cost_before_chef":
            opt_pension = - private_cost_after_chef  + private_cost_before*nivvie_chef_before/(nivvie_chef_before+nivvie_part_before)
        
        elif criterium == "share_private_cost_before_part":
            opt_pension = private_cost_after_part  - private_cost_before*nivvie_part_before/(nivvie_chef_before+nivvie_part_before)
        
        elif criterium == "share_private_cost_before_chef_nivvie_after":
            opt_pension = - private_cost_after_chef  + private_cost_before*nivvie_chef_after/(nivvie_chef_after+nivvie_part_after)
        
        elif criterium == "share_private_cost_before_chef_nivvie_after_coef":
            opt_pension = - private_cost_after_chef  + 1.4*private_cost_before*nivvie_chef_after/(nivvie_chef_after+nivvie_part_after)
        
        elif criterium == "share_private_cost_before_part_nivvie_after":
            opt_pension = private_cost_after_part  - private_cost_before*nivvie_part_after/(nivvie_chef_after+nivvie_part_after)
        
        elif criterium == "same_total_cost":
            return total_cost_after_chef+total_cost_after_part-total_cost_before
        
        elif criterium == "unaf":
            return total_cost_after_part - dep_decent_unaf
        
        elif criterium == "unaf2":
            return revdisp_part - dep_decent_unaf2
        return opt_pension 
    
    if criterium == "same_total_cost" or criterium in ["unaf", "unaf2"]:
        res = fsolve(func_optimal_pension, 10000, xtol = EPS)
        print res
        optimal_pension = res[0]
    else:
        try :
            optimal_pension = fixed_point(func_optimal_pension, 0, xtol = EPS, maxiter = 10)
        except RuntimeError:
            optimal_pension = 10000
    
    return optimal_pension
Exemplo n.º 50
0
def flap(airfoil, chord, J, sma, linear, spring, W, r_w, V,
         altitude, alpha, T_0, T_final, MVF_init, n, all_outputs = False,
         import_matlab = True, eng = None, aero_loads = True, 
         cycling = 'False', n_cycles = 0):
    """
    solve actuation problem for flap driven by an antagonistic mechanism
    using SMA and linear actuators
    :param J: dictionary with coordinates of Joint
    :param sigma_o: pre-stress, if not defined, it calculates the biggest
                    one respecting the constraints (max is H_max)
    :param T_0: initial temperature
    :param T_final: final temperature
    :param MVF_init: initial martensitic volume fraction
    :param n: number of steps in simulation"""
    
    from scipy.interpolate import interp1d
    import pickle
    import os.path
 
    if import_matlab and eng == None:
        import matlab.engine
        #Start Matlab engine
        eng = matlab.engine.start_matlab()
        #Go to directory where matlab file is
        if import_matlab:
            eng.cd(' ..')
            eng.cd('SMA_temperature_strain_driven')
        else:
            eng.cd('SMA_temperature_strain_driven')
            
    def constitutive_model(T, MVF_init, i, n, eps, eps_t_0, sigma_0 = 0,
            eps_0 = 0, plot = 'True'):
        """Run SMA model
        
        - all inputs are scalars"""
        k = i+1
        if k == n:
            data = eng.OneD_SMA_Model(k, eps, T, MVF_init, 
                                      eps_t_0, sigma_0, eps_0, n, plot,
                                      nargout=6) 
        else:
            data = eng.OneD_SMA_Model(k, eps, T, MVF_init,
                                      eps_t_0, sigma_0, eps_0, n, 'False',
                                      nargout=6)
        return data

    def equilibrium(eps_s, s, l, T, MVF_init, sigma_0,
                   i, n, r_w, W, x = None, y = None, alpha = 0.,
                   q = 1., chord = 1., x_hinge = 0.25, aero_loads = aero_loads,
                   return_abs = False):
        """Calculates the moment equilibrium. Function used for the 
        secant method.
        """
        #calculate new theta for eps_s and update all the parameter
        #of the actuator class
        s.eps = eps_s
#        print s.eps, s.eps_0, s.r_1, s.r_2, s.r_1_0, s.r_2_0, s.max_eps, s.min_eps
#        print s.min_theta, s.max_theta
#        try:
#        print eps_s
        s.calculate_theta(theta_0 = s.theta)
#        except:
#            s.theta = max(s.max_theta, l.max_theta)
#            s.update()
#            l.theta = max_theta
#            l.update()
#            plot_flap(x, y, J['x'], -s.theta)
#            raise Exception("Inverse solution for theta did not converge")
        s.update()
        
        l.theta = s.theta
        l.update()
        #SMA (Constitutive equation: coupling via sigma)
        data = constitutive_model(T, MVF_init, i, n, eps_s,
                                  eps_t_0, sigma_0, s.eps_0, plot = 'False')
        
        s.sigma = data[0][i][0]
        s.calculate_force(source = 'sigma')
        tau_s = s.calculate_torque()
        
        #Linear (Geometric equation: coupling via theta)
        l.calculate_force()
        tau_l = l.calculate_torque()
        
        #weight (Geometric equation: coupling via theta)
        tau_w = - r_w*W*math.cos(l.theta)

        #aerodynamic (Panel method: coupling via theta)
        tau_a = 0.
            
#        print 'tau', tau_s, tau_l, tau_w, tau_a, tau_s + tau_l + tau_w + tau_a
        f = open('data', 'a')
        f.write('\t Inner loop \t'+ str(T[i]) + '\t' + str( eps_s) + '\t' + \
                str( tau_s + tau_l + tau_w + tau_a) + '\t' + str( tau_s) + '\t' + str(tau_l) + '\t' + str(tau_w) + '\t' + str(tau_a) + '\t' + \
                str(l.theta)  + '\n')
        f.write('\t ' + str(i) + '\t' + str(n) +'\n')
        f.write('\t ' + str(l.F) + '\t' + str(s.F) + '\n')
        f.close()
        if return_abs:
            return abs(tau_s + tau_l + tau_w + tau_a)
        else:
            return tau_s + tau_l + tau_w + tau_a

    def eps_s_fixed_point(eps_s, s, l, T, MVF_init, sigma_0,
                   i, n, r_w, W, x = None, y = None, alpha = 0.,
                   q = 1., chord = 1., x_hinge = 0.25, aero_loads = aero_loads,
                   return_abs = False):
        """Calculates the SMA strain. Function used for the 
        fixed position iteration method. Restriction d epsilon_s / dt < 1.
        """
        #calculate new theta for eps_s and update all the parameter
        #of the actuator class
        s.eps = eps_s
#        print 'eps_s: ', eps_s
        s.calculate_theta(theta_0 = s.theta)
        s.update()
        
        l.theta = s.theta
        l.update()

        #SMA (Constitutive equation: coupling via sigma)
        data = constitutive_model(T, MVF_init, i, n, eps_s,
                                  eps_t_0, sigma_0, s.eps_0, plot = 'False')
        
        s.sigma = data[0][i][0]
        s.calculate_force(source = 'sigma')
        tau_s = s.calculate_torque()
        
        #Linear (Geometric equation: coupling via theta)
        l.calculate_force()
        tau_l = l.calculate_torque()
        
        #weight (Geometric equation: coupling via theta)
        tau_w = - r_w*W*math.cos(l.theta)

        #aerodynamic (Panel method: coupling via theta)
        tau_a = 0.
        
        B = tau_s/s.sigma
        eps_t = data[3][i][0] 
        E = data[5][i][0] 
        

        eps_s = eps_t - (tau_l + tau_w + tau_a)/(B*E)
        
#        print 'tau', tau_s, tau_l, tau_w, tau_a, tau_s + tau_l + tau_w + tau_a
        f = open('data', 'a')
        f.write('\t Inner loop 2\t'+ str(T[i]) + '\t' + str( eps_s) + '\t' + \
                str( tau_s + tau_l + tau_w + tau_a) + '\t' + str( tau_s) + '\t' + str(tau_l) + '\t' + str(tau_w) + '\t' + str(tau_a) + '\t' + \
                str(l.theta)  + '\n')
        f.close()        
        return eps_s
            
    def deformation_theta(theta = -math.pi/2., plot = False):
        """Return lists of deformation os SMA actuator per theta"""
        
        theta_list = np.linspace(-theta, theta)
        eps_s_list = []
        eps_l_list = []
        
        for theta in theta_list:
            s.theta = theta
            l.theta = theta
            
            s.update()
            l.update()
            
            l.calculate_force()
            
            eps_s_list.append(s.eps)
            eps_l_list.append(l.eps)
        if plot:
            import matplotlib.pyplot as plt
            plt.figure()
            plt.plot(np.degrees(theta_list), eps_s_list, 'r', np.degrees(theta_list), eps_l_list, 'b')  
            plt.xlabel('$\\theta (degrees)$')
            plt.ylabel('$\epsilon$')
    
        return eps_s_list, theta_list
   
    def plot_flap(x, y, x_J, y_J = None, theta = 0):
        """
        Plot flap with actuators. theta is clockwise positive.
        @Author: Endryws (modified by Pedro Leal)
        
        Created on Fri Mar 18 14:26:54 2016
        """
        import matplotlib.pyplot as plt
        plt.figure()
        x_dict, y_dict = af.separate_upper_lower(x, y)
        
        # Below I create the dictionarys used to pass to the function find_hinge
        upper = {'x': x_dict['upper'], 'y': y_dict['upper']} # x and y upper points
        lower = {'x': x_dict['lower'], 'y': y_dict['lower']} # x and y lower points
        hinge = af.find_hinge(x_J, upper, lower) 
        
        #=======================================================================
        # With the Joint (hinge) point, i can use the find flap function to
        # found the points of the flap in the airfoil.
        #=======================================================================
        
        data = {'x': x, 'y': y}
        static_data, flap_data = af.find_flap(data, hinge)
        R = hinge['y_upper']
        theta_list = np.linspace(3*math.pi/2, math.pi/2, 50)
        x_circle_list = hinge['x'] + R*np.cos(theta_list)
        y_circle_list = hinge['y'] + R*np.sin(theta_list)

        n_upper = len(flap_data['x'])/2
        
        # Ploting the flap in the original position
        plt.plot(flap_data['x'][:n_upper],flap_data['y'][:n_upper],'k--')
        plt.plot(flap_data['x'][n_upper:],flap_data['y'][n_upper:],'k--')         
        # Rotate and plot
        upper = {'x': np.concatenate((flap_data['x'][:n_upper], x_circle_list)),
                 'y': np.concatenate((flap_data['y'][:n_upper], y_circle_list))}
        lower = {'x':(flap_data['x'][n_upper:]),
                 'y':(flap_data['y'][n_upper:])}
                
        rotated_upper, rotated_lower = af.rotate(upper, lower, hinge, theta, 
                                                 unit_theta = 'rad')
        plt.plot(static_data['x'], static_data['y'],'k')
        
        plt.plot(rotated_upper['x'], rotated_upper['y'],'k')
        plt.plot(rotated_lower['x'], rotated_lower['y'],'k')
        plt.axes().set_aspect('equal')
        
        l.plot_actuator()
        s.plot_actuator()
        
        
        if y_J != None:
            for i in range(y_J):
                plt.scatter(x_J , y_J[i])
        plt.grid()
        plt.locator_params(axis = 'y', nbins=6)
        plt.xlabel('${}_{I}x + x_J$')
        plt.ylabel('${}_{I}y$')
        border = 0.05
        plt.xlim(-border, 1+border)
        plt.savefig( str(np.floor(100*abs(theta))) + "_configuration.png")
        plt.close()

#==============================================================================
# Material and flow properties
#==============================================================================
    #SMA properties
    E_M = 8.8888e+10
    E_A = 3.7427e+10
    sigma_crit = 0
    H_max = 0.0550
    H_min = 0.0387
    k = 4.6849e-09
    
    Air_props= air_properties(altitude, unit='feet')
    rho = Air_props['Density']
    q = 0.5*rho*V**2
    
#===========================================================================
# Generate Temperature arrays
#===========================================================================
    if n_cycles == 0:
        T = np.linspace(T_0, T_final, n)
    else:
        T = np.append(np.linspace(T_0, T_final, n),
                      np.linspace(T_final, T_0, n))
        for i in range(n_cycles-1):
            T = np.append(T,T)
    T = list(T)
#===========================================================================
# Generate airfoil (NACA0012)
#===========================================================================
    xf.call(airfoil, output='Coordinates')
    filename = xf.file_name(airfoil, output='Coordinates')
    Data = xf.output_reader(filename, output='Coordinates',
                            header = ['x','y'])
    #The coordinates from Xfoil are normalized, hence we have to multiply
    #by the chord
    x = []
    y = []
    for i in range(len(Data['x'])):
        x.append( Data['x'][i]*chord )
        y.append( Data['y'][i]*chord )
    
    filename = airfoil + '_' + str(int(100*J['x'])) + '_' + \
               str(int(100*chord)) + '.p'
    
    #Generate aerodynamic moment data. If already exists, load it
#    if os.path.isfile(filename):
#        with open(filename, "rb") as f:
#            Cm_list = pickle.load( f )
#            theta_list = pickle.load( f )
#    else:
#        theta_list = np.linspace(-math.pi/2., math.pi/2., 100)
#        Cm_list = []
#        for theta in theta_list:
#            Cm = calculate_flap_moment(x, y, alpha, J['x'], - theta,
#                                       unit_deflection = 'rad')
#            Cm_list.append(Cm)
#        with open(filename, "wb") as f:
#            pickle.dump( Cm_list, f )
#            pickle.dump( theta_list, f )
#        
#    Cm_function = interp1d(theta_list, Cm_list)

#===========================================================================
# Linear actuator
#===========================================================================
    #Linear actuator (l)
    l = actuator(linear, J, material = 'linear')
    l.k = spring['k']
    #Check if crossing joint. If True do nothing
    if l.check_crossing_joint(tol = 0.005):
        print "problem with linear"
        plot_flap(x, y, J['x'], theta= 0)
        if all_outputs:
            return 0., 0, 0., 200.
        else:
            return 0, 9999.
    else:        

        l.zero_stress_length = spring['L_0']
        l.solid = l.zero_stress_length
  
        l.update()
        l.eps_0 = l.eps
        l.calculate_force(source = 'strain')
        l.calculate_torque()
        l.calculate_theta()
#===========================================================================
# SMA actuator  
#===========================================================================
        tau_w = - r_w*W 
        
        #Sma actuator (s)
        s = actuator(sma, J, material = 'SMA')
        
        #Initial force
        s.F = - s.length_r_0*(l.torque + tau_w)/(s.y_p*s.r_1 - s.x_p*s.r_2)
        
        #Initial stress
        s.sigma = s.F/s.area
        sigma_o = s.sigma
        
        #Initial transformation strain
        eps_t_0 = H_min + (H_max - H_min)*(1. - math.exp(-k*(abs(s.sigma) - \
                                                         sigma_crit)))
        s.eps_t_0 = eps_t_0
        
        #Define initial strain
        eps_0 = s.eps_t_0 + s.sigma/E_M
        s.eps_0 = eps_0
        s.zero_stress_length = s.length_r_0/(1. + s.eps_0)
        s.update()
        
        #Calculate initial torques
        s.calculate_torque()  
        print s.eps, s.F, l.F, s.torque, l.torque, tau_w, s.sigma, sigma_o
        #Check if crossing joint. If True do nothing
        if s.check_crossing_joint(tol = 0.005):
            print "problem with SMA"
            plot_flap(x, y, J['x'], theta= 0)
            if all_outputs:
                return 0., s.theta, 0., 200.
            else:
                return s.theta, 9999.
        else:
    
            t = 0.12
            
            y_J = af.Naca00XX(chord, t, [J['x']], return_dict = 'y')
            
            s.find_limits(y_J, theta_0 = 0)
            l.find_limits(y_J, theta_0 = 0)
    
#            print 's: limits', s.max_theta, s.min_theta
#            print s.max_theta_A, s.max_theta_B
#            print 'l: limits', l.max_theta, l.min_theta
#            print l.max_theta_A, l.max_theta_B
#            plot_flap(x, y, J['x'], theta= 0.)            
            max_theta = max(s.max_theta, l.max_theta)
        ##==============================================================================
        # Matlab simulation
        ##==============================================================================         
            eps_s = eps_0
            eps_s_list = [eps_s]
            eps_l_list = [l.eps]
            theta_list = [s.theta]
            F_l_list =[l.calculate_force()]
            L_s_list = [s.length_r]
            #Because of the constraint of the maximum deflection, it is possible that
            #the number of steps is smaller than n
            n_real = 1
            
#            plot_flap(x, y, J['x'], theta= -s.theta)
            
            #Create new data file and erase everything inside
            f = open('data', 'w')
            f.close()
            
            if n_cycles == 0:
                iterations = n
            else:
                iterations = 2*n*n_cycles
            #original number of steps without any restrictions
            n_o = n
            print s.eps, s.F, l.F, s.torque, l.torque, tau_w
            eps_s_prev = [eps_0, eps_0]
            for i in range(1, iterations):
                #because n_real can be different of n, it is posssible that
                #i is greater than the actual number of iterations. Need
                #to break
                if i == iterations:
                    break
                
                #Linear prediction 
                delta_eps = eps_s_prev[1] - eps_s_prev[0]
                #Correction with fixed point iteration
                try:
                    eps_s = fixed_point(eps_s_fixed_point, eps_s + delta_eps, args=((s, l, T, 
                                           MVF_init, sigma_o, i, n, r_w, W, x, y, alpha, 
                                           q, chord, J['x'], True)), xtol = 1e-8)
                except:
#                    eps_s = fixed_point(eps_s_fixed_point, eps_s, args=((s, l, T, 
#                           MVF_init, sigma_o, i, n, r_w, W, x, y, alpha, 
#                           q, chord, J['x'], True)), xtol = 1e-8)
                    eps_s_start = eps_s + delta_eps
                    for j in range(10):
                        try:
                            eps_s = fixed_point(eps_s_fixed_point, eps_s_start, args=((s, l, T, 
                                                   MVF_init, sigma_o, i, n, r_w, W, x, y, alpha, 
                                                   q, chord, J['x'], True)), xtol = 1e-8)
                            break
                        except:
                            eps_s_start  = eps_s_start*float(j)/10.
                eps_s_prev[0] = eps_s_prev[1]
                eps_s_prev[1] = eps_s

                s.eps = eps_s
                s.calculate_theta(theta_0 = s.theta)
                s.update()
                
                f = open('data', 'a')
                f.write('Outer loop \t'+ str(i)  + '\t'+ str(eps_s) + '\t'+ str(s.theta)+ '\n')
                f.close()
#                print 'new theta: ', s.theta
                #stop if actuator crosses joints, exceds maximum theta and theta is positively increasing
                if s.theta <= max_theta or s.check_crossing_joint(tol = 0.001) or l.check_crossing_joint(tol = 0.001) or s.theta > 0.01 or l.length_r <= l.solid:
                    if n_cycles == 0:
                        iterations = n_real
                        T = T[:n_real]
                        break
                    else:
                        n = n_real #+ 10
                        iterations = 2*n_real*n_cycles
                        T_cycle = T[:n_real]  + T[:n_real][::-1] #+ 10*[T[n_real-1]]
                        T = T_cycle
                        for k in range(n_cycles-1):
                            T += T_cycle
                        #Correction with fixed point iteration
                            eps_s = fixed_point(eps_s_fixed_point, eps_s_prev[1], args=((s, l, T, 
                                                   MVF_init, sigma_o, i, n, r_w, W, x, y, alpha, 
                                                   q, chord, J['x'], True)), xtol = 1e-8)
                        eps_s_prev[0] = eps_s_prev[1]
                        eps_s_prev[1] = eps_s
                        
                        s.eps = eps_s
                        s.calculate_theta(theta_0 = s.theta)
                        s.update()
                        
                else:
                    if n != n_real:
                        n_real +=1
                    if n_o == n_real:
                        n = n_real #+ 10
                        if n_cycles == 0:
                            iterations = n_real
                        else:
                            iterations = 2*n_real*n_cycles
                            T_cycle = T[:n_real]  + T[:n_real][::-1] #+ 10*[T[n_real-1]]
                            T = T_cycle
                            for k in range(n_cycles-1):
                                T += T_cycle
                l.theta = s.theta
                l.update()
                
                eps_s_list.append(eps_s)
                eps_l_list.append(l.eps)
                theta_list.append(s.theta)
                F_l_list.append(l.calculate_force())
                L_s_list.append(s.length_r)
    
#            print 'final theta: ', s.theta
            if all_outputs:
                s.theta = theta_list[-1]
                l.theta = s.theta
                s.update()
                l.update()
                plot_flap(x, y, J['x'], theta= -s.theta)
                
                s.theta = 0.
                l.theta = s.theta
                s.update()
                l.update()
                plot_flap(x, y, J['x'], theta= -s.theta)
                
                if n_real == 1:
                    return 0., s.theta, 0., 200.
                else:
                    #Extra run with prescribed deformation (which has already been calculated)
                    # to get all the properties]
                    #TODO: include back n_real
                    for i in range(1, iterations):
                        data = constitutive_model(T, MVF_init, i, iterations, 
                                                  eps_s_list[i], eps_t_0,
                                                  sigma_0 = sigma_o,
                                                  eps_0 = eps_0, 
                                                  plot = 'False')
                    delta_xi = 1. - data[1][-1][0]
                    
                    sigma_list = []
                    for i in range(len(data[0])):
                        sigma_list.append(data[0][i][0])
                    MVF_list = []
                    for i in range(len(data[1])):
                        MVF_list.append(data[1][i][0])    
                    eps_t_list = []
                    for i in range(len(data[3])):
                        eps_t_list.append(data[3][i][0])
                    return eps_s_list, eps_l_list, theta_list, sigma_list, MVF_list, T, eps_t_list, theta_list, F_l_list, l.k, L_s_list
            else:
#                print theta_list
                return theta_list[-1], l.k
Exemplo n.º 51
0
def PofRho(T, rho):
	return fixed_point(lambda P: 1e3*rho*R*T/mu(T,P), 1e3*rho*R*T)