Ejemplo n.º 1
0
def A_rule (mdot,A,M,Pt,Tt):
    import numpy as np
    import sympy as sy
    
    gam=1.4
    R=287
    delta=(gam-1)/2.
# mdot=A*(Pt/Tt**0.5)*(gam/R)**0.5*M*(1+delta*M**2)**(-1*(gam+1)/(2*(gam-1))


    if mdot!=0 and M==0 and A!=0:
        Mach = sy.Symbol('Mach', positive=True, real=True)
        eq=mdot-A*Mach*Pt*sy.sqrt(gam/R/Tt)*(1+delta*Mach**2)**((gam+1)/(-2*(gam-1)))
        M=sy.nsolve(eq,Mach,0.2)
        return M
    elif mdot==0 and M!=0 and A!=0:
        mdot=A*Pt*M*sy.sqrt(gam/R/Tt)*(1+delta*M**2)**((gam+1)/(-2*(gam-1)))
        return mdot
    elif mdot!=0 and M!=0 and A==0:
        Area=sy.Symbol ('Area', positive = True, real = True)
        eq=mdot-Area*M*Pt*sy.sqrt(gam/R/Tt)*(1+delta*M**2)**((gam+1)/(-2*(gam-1)))
        A=sy.nsolve (eq,Area,1)
        return A
    else:
        return print("Wrong Values")
    
        
                                                                                     
                                                                                     
	def run_finally(cls, cxn, parameters_dict, all_data, det):    
		print "switching the 866 back to ON"
		cxn.pulser.switch_manual('866DP', True)

		ident = int(cxn.scriptscanner.get_running()[-1][0])
		print " sequence ident" , ident

		all_data = np.array(all_data)
		try:
			all_data = all_data.sum(1)
		except ValueError:
			return

		p = parameters_dict
		duration = p.DriftTrackerRabi.line_2_pi_time
		freq = np.pi/duration

		ind1 = np.where(det == -1)
		ind2 = np.where(det == 1)

		det1 = det[ind1][0] * 2.39122444/p.DriftTrackerRabi.line_1_pi_time
		det2 = det[ind2][0] * 2.39122444/p.DriftTrackerRabi.line_1_pi_time

		p1 = all_data[ind1][0]
		p2 = all_data[ind2][0]

		print "at ",det1, " the pop is", p1
		print "at ",det2, " the pop is", p2

		from sympy import sin, symbols, nsolve
		x = symbol('x')

		relative_det_1 = nsolve(freq**2 / (freq**2 + (x + det1)**2) * (sin((freq**2 + (x - det1)**2)**0.5 * duration / 2))**2 - p1, 0)
		relative_det_2 = nsolve(freq**2 / (freq**2 + (x + det2)**2) * (sin((freq**2 + (x - det2)**2)**0.5 * duration / 2))**2 - p2, 0)

		detuning_2 = U((relative_det_1 + relative_det_2)/2, 'kHz')

		print "detuning 2", (relative_det_1 + relative_det_2)/2

		line_1 = p.DriftTracker.line_selection_1
		line_2 = p.DriftTracker.line_selection_2

		carr_1 = detuning_1_global+p.Carriers[carrier_translation[line_1]]
		carr_2 = detuning_2+p.Carriers[carrier_translation[line_2]]

		submission = [(line_1, carr_1), (line_2, carr_2)]
		print  "3243", submission

		print carr_1
		print carr_2

		if p.DriftTrackerRabi.submit:
			cxn.sd_tracker.set_measurements(submission)
			import labrad
			global_sd_cxn = labrad.connect(cl.global_address , password = cl.global_password, tls_mode='off')
			print cl.client_name , "is sub lines to global SD"
			print submission 
			global_sd_cxn.sd_tracker_global.set_measurements(submission, cl.client_name) 
			global_sd_cxn.disconnect()
Ejemplo n.º 3
0
def concave_triangle(area):
    theta, n = symbols('theta n')
    A = (1-cos(theta)) * (1-sin(theta)) / 2 + \
        (2-cos(theta)) * sin(theta) / 2 - \
        theta / 2
    theta_ = nsolve(A - area, theta, 0.1)
    # print(theta_)
    n = nsolve((1 - sin(theta_)) - (1 - cos(theta_)) * n, n, 15)
    return n
Ejemplo n.º 4
0
def error_bound(n):
    e = Symbol('e')
    y = Symbol('y')
    growth_function_bound = generate_growth_function_bound(50)
    a = original_vc_bound(n, 0.05, growth_function_bound)
    b = nsolve(Eq(rademacher_penalty_bound(n, 0.05, growth_function_bound), y), 1)
    c = nsolve(Eq(parrondo_van_den_broek_right(e, n, 0.05, growth_function_bound), e), 1)
    d = nsolve(Eq(devroye(e, n, 0.05, growth_function_bound), e), 1)
    return a, b, c, d
Ejemplo n.º 5
0
def error_bound(n):
    e = Symbol('e')
    y = Symbol('y')
    growth_function_bound = generate_growth_function_bound(50)
    a = original_vc_bound(n, 0.05, growth_function_bound)
    b = nsolve(Eq(rademacher_penalty_bound(n, 0.05, growth_function_bound), y),
               1)
    c = nsolve(
        Eq(parrondo_van_den_broek_right(e, n, 0.05, growth_function_bound), e),
        1)
    d = nsolve(Eq(devroye(e, n, 0.05, growth_function_bound), e), 1)
    return a, b, c, d
Ejemplo n.º 6
0
def get_perm_lims(mesh):
    med_perm_by_primal_1 = []
    meshset_by_L2 = mesh.mb.get_child_meshsets(mesh.L2_meshset)
    for m2 in meshset_by_L2:
        meshset_by_L1 = mesh.mb.get_child_meshsets(m2)
        for m1 in meshset_by_L1:
            elem_by_L1 = mesh.mb.get_entities_by_handle(m1)
            perm1 = mesh.mb.tag_get_data(
                mesh.tags['PERM'], elem_by_L1).reshape([len(elem_by_L1), 9])
            med1_x = sum(perm1[:, 0]) / len(perm1[:, 0])
            med_perm_by_primal_1.append(med1_x)
    med_perm_by_primal_1 = np.sort(med_perm_by_primal_1)
    s = 1.0  #Parâmetro da secante
    lg = np.log(med_perm_by_primal_1)
    ordem = 11
    print("fit")
    fit = np.polyfit(range(len(lg)), lg, ordem)
    x = sympy.Symbol('x', real=True, positive=True)
    func = 0
    for i in range(ordem + 1):
        func += fit[i] * x**(ordem - i)
    print("deriv")
    derivada = sympy.diff(func, x)
    inc_secante = (lg[-1] - lg[0]) / len(lg)
    print("solve")
    equa = sympy.Eq(derivada, 2 * inc_secante)
    #real_roots=sympy.solve(equa)
    ind_inferior = int(sympy.nsolve(equa, 0.1 * len(lg), verify=False))
    if ind_inferior < 0:
        ind_inferior = 0
    ind_superior = int(sympy.nsolve(equa, 0.9 * len(lg), verify=False))
    if ind_superior > len(lg) - 1:
        ind_superior = len(lg) - 1

    new_inc_secante = (lg[ind_superior] - lg[ind_inferior]) / (ind_superior -
                                                               ind_inferior)
    eq2 = sympy.Eq(derivada, new_inc_secante)
    new_ind_inferior = int(sympy.nsolve(eq2, ind_inferior, verify=False))
    if new_ind_inferior < ind_inferior:
        new_ind_inferior = ind_inferior
    new_ind_superior = int(sympy.nsolve(eq2, ind_superior, verify=False))
    if new_ind_superior > ind_superior:
        new_ind_superior = ind_superior

    ind_inferior = new_ind_inferior
    ind_superior = new_ind_superior

    val_barreira = med_perm_by_primal_1[ind_inferior]
    val_canal = med_perm_by_primal_1[ind_superior]

    return val_barreira, val_canal
Ejemplo n.º 7
0
    def __init__(self, c=None, length=1, dim=3):

        eta, L = sp.symbols('eta, length')
        eta = sp.nsolve(c**2 * eta**2 - 2 * (1 - sp.cos(eta)), eta, -5)

        W = c * L

        X, Z = ligaro(W, eta)

        # center at -cL/2,
        R = L / eta
        A = -0.5 * W
        cx = A
        cy = W * sp.sin(eta) / (2 * (1 - sp.cos(eta)))
        self.eta = eta
        self.radius = R.evalf(subs={L: 1})
        self.center = [cx.evalf(subs={L: length}), cy.evalf(subs={L: length})]

        x1, x2 = sp.symbols('x[0], x[1]')

        gamma_sp = [None, None, None]
        gamma_sp[0] = X
        gamma_sp[1] = x2
        gamma_sp[2] = Z

        if dim == 2:
            del gamma_sp[1]
        self._build_geo(gamma_sp, length, x1, x2, dim)
Ejemplo n.º 8
0
def tilt_flame_rad_heat_pc(H, R, theta, rad_heat):
    try:
        Y_c = Symbol('Y_c')
        #rad_heat=rad_heat
        #R_c=0
        #Example:
        #H=20
        #X=50
        theta = theta / 180 * pi
        a = H / R
        b = Y_c / R
        FV2=-(a*a*sin(theta)*cos(theta)/(4*pi*(b*b+a*a*sin(theta)*sin(theta))))*log((a*a+b*b-1-2*a*pow((b*b-1),0.5)*sin(theta)/b)/(a*a+b*b-1+2*a*pow((b*b-1),0.5)*sin(theta)/b))+cos(theta)/(2*pi*pow((b*b-sin(theta)*sin(theta)),0.5))\
            *(atan((a*b/pow(b*b-1,0.5)+sin(theta))/(pow(b*b-sin(theta)*sin(theta),0.5)))+atan((a*b/pow(b*b-1,0.5)-sin(theta))/(pow(b*b-sin(theta)*sin(theta),0.5))))-a*b*cos(theta)/(pi*(b*b+a*a*sin(theta)*sin(theta)))\
            *atan(pow(((b-1)/(b+1)),0.5))+(a*b*cos(theta)*(a*a+b*b+1))/(2*pi*(b*b+a*a*sin(theta)*sin(theta))*pow((pow(a*a+b*b+1,2)-4*(b*b+a*a*sin(theta)*sin(theta))),0.5))\
            *(atan(((a*a+(b+1)*(b+1))*pow((b-1)/(b+1),0.5)-2*a*sin(theta))/(pow(((pow((a*a+b*b+1),2))-(4*(b*b+a*a*sin(theta)*sin(theta)))),0.5)))+atan(((a*a+(b+1)*(b+1))*pow((b-1)/(b+1),0.5)+2*a*sin(theta))/(pow(((pow((a*a+b*b+1),2))-(4*(b*b+a*a*sin(theta)*sin(theta)))),0.5))))
        #This is for test:f_qv_r0=FV1-0.118
        #for i in range(5):
        func_qh_yc = FV2 * E - rad_heat
        result = nsolve(
            func_qh_yc, Y_c, R + 0.3
        )  # 20 is the initial guess, this is required for nsolve function
        Y_c = result
        #this is the Hazardous Radius (5 values)
        print(Y_c)
        return (Y_c)
    except Exception as e:
        return 0
        traceback.print_exc()
Ejemplo n.º 9
0
def tilt_flame_rad_heat_pa(H, R, theta, rad_heat):
    try:
        X_a = Symbol('X_a')
        #rad_heat=rad_heat
        #Example:
        #H=20
        #X=50
        theta = theta / 180 * pi
        a = H / R
        #b=X/R
        b = X_a / R
        x1 = a * a + (b + 1) * (b + 1) - 2 * a * (b + 1) * sin(theta)
        x2 = a * a + (b - 1) * (b - 1) - 2 * a * (b - 1) * sin(theta)
        FH1=atan(pow(((b+1)/(b-1)),0.5))/pi+sin(theta)/(pi*pow(1+(b*b-1)*cos(theta)*cos(theta),0.5))\
            *((atan((a*b-(b*b-1)*sin(theta))/(pow((b*b-1),0.5)*pow((1+(b*b-1)*cos(theta)*cos(theta)),0.5))))+(atan(((b*b-1)*sin(theta))/(pow((b*b-1),0.5)*pow((1+(b*b-1)*cos(theta)*cos(theta)),0.5)))))\
            -(a*a+(b+1)*(b+1)-2*(b+1+a*b*sin(theta)))/(pi*(pow(x1,0.5)*pow(x2,0.5)))\
            *atan(pow(((a*a+(b+1)*(b+1)-2*a*(b+1)*sin(theta))/(a*a+(b-1)*(b-1)-2*a*(b-1)*sin(theta))),0.5)*pow(((b-1)/(b+1)),0.5))
        #This is for test:f_qv_r0=FV1-0.118
        func_qh_xa = FH1 * E - rad_heat
        result = nsolve(
            func_qh_xa, X_a, R + 0.3
        )  # 20 is the initial guess, this is required for nsolve function
        X_a = result
        #this is the Hazardous Radius (5 values)
        # print(X_a)
        return (X_a)
    except Exception as e:
        return 0
Ejemplo n.º 10
0
    def locate(self,times,exclude):
        """locate(t,exclude)
        input: list-of-times in microseconds
        and what to exclude in calculations
        output (x, y) in meters
        """
        sos = 340.2;
        
        times = times[:];
        pts = self.sensors[:];
        del pts[exclude];
        del times[exclude];
        x,y,t = sympy.symbols('x y t');
        a,b = pts[0];
        c,d = pts[1];
        e,f = pts[2];
        #print(a,b,c,d,e,f);
        t_1 = mpf(times[0])/1e6;
        t_2 = mpf(times[1])/1e6;
        t_3 = mpf(times[2])/1e6;
        #t_1,t_2,t_3 = 0,t_2-t_1,t_3-t_1;
        
        f_1 = (x-a)**2 + (y-b)**2 - ((t_1-t)*sos)**2;
        f_2 =  (x-c)**2 + (y-d)**2 - ((t_2-t)*sos)**2;
        f_3 = (x-e)**2 + (y-f)**2 - ((t_3-t)*sos)**2;

        try:
            res = sympy.nsolve((f_1,f_2,f_3),(x,y,t),(0,0,min(t_1,t_2,t_3)));
            return ( float(res[0]), float(res[1]) );
        except(ValueError,ZeroDivisionError):
            return ( float('NaN'), float('NaN') );
Ejemplo n.º 11
0
def calculate(args):
    '''For 20 values of n, set vals[n] to float representation of eigenvalue
    and set funcs[n] to corresponding eigenfunction with lambda as free
    variable.
    '''
    from first import LO
    if len(vals) != 0:
        return
    t, lam = sympy.symbols('t lam'.split())
    old = 1.0
    delta = 0
    ns = np.arange(1, args.n_calculate)
    for n in ns:
        T = 1.0 / n
        A = LO(T, 1.0 / 3000)
        A.power(op=A.matvec, small=1.0e-8)
        vals_n[n] = A.eigenvalue
        funcs_n[n] = A.eigenvector
        F = Piecewise(n)
        funcs[n] = F
        new_ = sympy.nsolve(lam - F.integrate(), lam, old + delta)
        vals[n] = new_
        delta = new_ - old
        old = new_
        print('For n={0:d}, lambda={1}, delta={2}'.format(n, new_, delta))
Ejemplo n.º 12
0
def solve_equation(x, y, d):
    # Równanie powiędzy 1 i 2
    f1 = sympy.sqrt(np.abs((x[1] - a)**2 - (y[1] - b)**2)) - sympy.sqrt(
        np.abs((x[0] - a)**2 - (y[0] - b)**2)) - d[0]
    # Równanie powiędzy 1 i 3
    f2 = sympy.sqrt(np.abs((x[2] - a)**2 - (y[2] - b)**2)) - sympy.sqrt(
        np.abs((x[0] - a)**2 - (y[0] - b)**2)) - d[1]
    # Równanie powiędzy 2 i 3
    f3 = sympy.sqrt(np.abs((x[2] - a)**2 - (y[2] - b)**2)) - sympy.sqrt(
        np.abs((x[1] - a)**2 - (y[1] - b)**2)) - d[2]
    x_dz = []
    y_dz = []
    while len(x_dz) < 10:
        pp1 = np.random.uniform(x[0] - 5, x[2] + 5)
        pp2 = np.random.uniform(y[0] - 5, y[2] + 5)

        try:
            p, q = nsolve((f1, f2, f3), (a, b), (pp1, pp2), verify=False)
            if abs(p) < 10 and (0 < -q < 10):
                x_dz.append(p)
                y_dz.append(q)
        except:
            pass
    print(x_dz)
    print(y_dz)

    return np.median(x_dz), np.median(y_dz)
Ejemplo n.º 13
0
def neutral_axis_MN(M, N, b, d, d1, d2, As, As1, n=15):
    "presso-flessione"
    d0 = M/N - (d+d1)/2
    x = sp.symbols('x')
    eq = 1/6*b*x**3 + 1/2*b*d0*x**2 + (n*As1*(d0+d2) + n*As*(d0+d))*x - n*As1*d2*(d0+d2) - n*As*d*(d0+d)
    sol = sp.nsolve(eq, x, d/2, dict=True)[0][x] #d/2 is the starting point 
    return sol
Ejemplo n.º 14
0
def tangent_intersection(p, yq_pos):
	"""
	calculate and return the value of the tangent-intersection coordinates
	(xq, yq) of the line through (xp, yp) with the curve.

	the easiest way to find the tangent point (q) of the line which passes
	through point p is to equate the two different slope equations:

	1) m = 3xq^2 / 2yq
	2) m = (yp - yq) / (xp - xq)

	(1) is the tangent slope and (2) is the non-tangent slope. we can use these
	equations to solve for xq, knowing that:

	yq = [+/-]sqrt(xq^3 + 7)

	where + or - is determined by the input variable yq_pos. note that it is a
	very difficult (impossible?) equation to solve for certain values of p, so
	we will solve numerically.

	this function works best if you pick an xp value between cuberoot(-7) and
	-0.5. for xp values outside this range you will need to adjust the numerical
	solver function - ie pick a different starting point and algorythm.
	"""
	(xp, yp) = p
	if float(xp) < -7**(1 / 3.0):
		raise ValueError("xp must be greater than cuberoot(-7)")
	xq = sympy.symbols("xq")
	yq = y_ec(xq, yq_pos)
	q = (xq, yq)
	m1 = tan_slope(q)
	m2 = non_tan_slope(p, q)
	# solve numerically, and start looking for solutions at xq = 0
	xq = float(sympy.nsolve(m1 - m2, xq, 0))
	return (xq, y_ec(xq, yq_pos))
Ejemplo n.º 15
0
    def x_boundary(self):
        x = self.x
        x_value = self.x_value
        s_boundary = self.s_boundary()
        s = self.ProblemSettings.s(x)

        f = np.ndarray((
            2,
            len(x),
        ), 'object')
        for i in range(2):
            for j in range(len(x)):
                f[i][j] = s[j] - s_boundary[i][j]

        x_boundary = np.ndarray((
            2,
            len(x),
        ))
        for i in range(2):
            for j in range(len(x)):
                x_boundary[i][j] = syp.nsolve((f[i][0], f[i][1]), \
                                             (x[0], x[1]), \
                                             (x_value[0], x_value[1]) \
                                             )[j]

        return x_boundary
Ejemplo n.º 16
0
    def eta_fil(self, x, V_app, apprx=(0, 0, 0, 0)):
        m_eff = self.m_r * const.electron_mass

        mpmath.mp.dps = 20
        x0 = Symbol('x0')  # eta_fil
        x1 = Symbol('x1')  # eta_ac
        x2 = Symbol('x2')  # eta_hop
        x3 = Symbol('x3')  # V_tunnel

        f0 = const.Boltzmann * self.T / (1 - self.alpha) / const.elementary_charge / self.z * \
             ln(self.A_fil/self.A_ac*(exp(- self.alpha * const.elementary_charge * self.z / const.Boltzmann / self.T * x0) - 1) + 1) - x1# eta_ac = f(eta_fil) x1 = f(x0)
        f1 = x*2*const.Boltzmann*self.T/self.a/self.z/const.elementary_charge*\
             asinh(self.j_0et/self.j_0hop*(exp(- self.alpha * const.elementary_charge * self.z / const.Boltzmann / self.T * x0) - 1)) - x2# eta_hop = f(eta_fil)
        f2 = x1 - x0 + x2 - x3

        f3 = -V_app + ((self.C * 3 * sqrt(2 * m_eff * ((4+x3/2)*const.elementary_charge)) / 2 / x * (const.elementary_charge / const.Planck)**2 * \
             exp(- 4 * const.pi * x / const.Planck * sqrt(2 * m_eff * ((4+x3/2)*const.elementary_charge))) * self.A_fil*x3)
                       + (self.j_0et*self.A_fil*(exp(-self.alpha*const.elementary_charge*self.z*x0/const.Boltzmann/self.T) - 1))) * (self.R_el + self.R_S + self.rho_fil*(self.L - x) / self.A_fil) \
             + x3

        eta_fil, eta_ac, eta_hop, V_tunnel = nsolve((f0, f1, f2, f3), [x0, x1, x2, x3], apprx)
        eta_fil = np.real(np.complex128(eta_fil))
        eta_ac = np.real(np.complex128(eta_ac))
        eta_hop = np.real(np.complex128(eta_hop))
        V_tunnel = np.real(np.complex128(V_tunnel))
        current = ((self.C * 3 * sqrt(2 * m_eff * ((4+V_tunnel)*const.elementary_charge)) / 2 / x * (const.elementary_charge / const.Planck)**2 * \
            exp(- 4 * const.pi * x / const.Planck * sqrt(2 * m_eff * ((4+V_tunnel)*const.elementary_charge))) * self.A_fil*V_tunnel)
                       + (self.j_0et*self.A_fil*(exp(-self.alpha*const.elementary_charge*self.z*eta_fil/const.Boltzmann/self.T) - 1)))
        print(eta_fil, eta_ac, eta_hop, V_tunnel)
        # print(eta_ac - eta_fil + eta_hop - V_tunnel)
        return eta_fil, eta_ac, eta_hop, V_tunnel, current
Ejemplo n.º 17
0
    def equations(self, point_pairs, is_less):
        """
        以一条线段作为直角三角形的一条边,从这条线段的起点向该线段引一条距离为d的垂线,
        用垂线的另一点和该线段组成一个直角三角形,这个垂线上的另一点即为要扩展的轮廓的一点
        用以下两个方程组成二元二次方程组,求解可获得这点坐标
        ① 直角,向量法.(x-x1)(x2-x1)+(y-y1)(y2-y1)=0
        ② L,两点距离公式.(x-x1)²+(y-y1)²=l²
        解二元二次方程
        :param point_pairs:直角三角形的一条直角边
        :param is_less:初值的x坐标值是否大于直角边起点的x坐标值
        :return:返回一个解(x,y)
        :rtype: object
        """
        try:
            x1 = point_pairs[0][0]
            y1 = point_pairs[0][1]
            x2 = point_pairs[1][0]
            y2 = point_pairs[1][1]
            deta = 0.05
            if is_less:
                init_pairs = [x1 - deta, y1]
            else:
                init_pairs = [x1 + deta, y1]

            x = Symbol('x')
            y = Symbol('y')
            func = [(x2 - x1) * (x - x1) + (y2 - y1) * (y - y1),
                    (x - x1)**2 + (y - y1)**2 - self.d**2]
            return nsolve(func, [x, y], init_pairs)
        except Exception as err:
            return None
Ejemplo n.º 18
0
    def eta_fil(self, x, V_app, apprx=(0, 0, 0, 0)):
        m_eff = self.m_r * const.electron_mass

        mpmath.mp.dps = 20
        x0 = Symbol('x0')  # eta_fil
        x1 = Symbol('x1')  # eta_ac
        x2 = Symbol('x2')  # eta_hop
        x3 = Symbol('x3')  # V_tunnel

        f0 = const.Boltzmann * self.T / (1 - self.alpha) / const.elementary_charge / self.z * \
             ln(self.A_fil/self.A_ac*(exp(- self.alpha * const.elementary_charge * self.z / const.Boltzmann / self.T * x0) - 1) + 1) - x1# eta_ac = f(eta_fil) x1 = f(x0)
        f1 = x*2*const.Boltzmann*self.T/self.a/self.z/const.elementary_charge*\
             asinh(self.j_0et/self.j_0hop*(exp(- self.alpha * const.elementary_charge * self.z / const.Boltzmann / self.T * x0) - 1)) - x2# eta_hop = f(eta_fil)
        f2 = x1 - x0 + x2 - x3

        f3 = -V_app + ((self.C * 3 * sqrt(2 * m_eff * ((4+x3/2)*const.elementary_charge)) / 2 / x * (const.elementary_charge / const.Planck)**2 * \
             exp(- 4 * const.pi * x / const.Planck * sqrt(2 * m_eff * ((4+x3/2)*const.elementary_charge))) * self.A_fil*x3)
                       + (self.j_0et*self.A_fil*(exp(-self.alpha*const.elementary_charge*self.z*x0/const.Boltzmann/self.T) - 1))) * (self.R_el + self.R_S + self.rho_fil*(self.L - x) / self.A_fil) \
             + x3

        eta_fil, eta_ac, eta_hop, V_tunnel = nsolve((f0, f1, f2, f3),
                                                    [x0, x1, x2, x3], apprx)
        eta_fil = np.real(np.complex128(eta_fil))
        eta_ac = np.real(np.complex128(eta_ac))
        eta_hop = np.real(np.complex128(eta_hop))
        V_tunnel = np.real(np.complex128(V_tunnel))
        current = ((self.C * 3 * sqrt(2 * m_eff * ((4+V_tunnel)*const.elementary_charge)) / 2 / x * (const.elementary_charge / const.Planck)**2 * \
            exp(- 4 * const.pi * x / const.Planck * sqrt(2 * m_eff * ((4+V_tunnel)*const.elementary_charge))) * self.A_fil*V_tunnel)
                       + (self.j_0et*self.A_fil*(exp(-self.alpha*const.elementary_charge*self.z*eta_fil/const.Boltzmann/self.T) - 1)))
        print(eta_fil, eta_ac, eta_hop, V_tunnel)
        # print(eta_ac - eta_fil + eta_hop - V_tunnel)
        return eta_fil, eta_ac, eta_hop, V_tunnel, current
Ejemplo n.º 19
0
def get_selu_parameters(fixed_point_mean=0.0, fixed_point_var=1.0):
    """ Finding the parameters of the SELU activation function. The function returns alpha and lambda for the desired
    fixed point. """
    aa = Symbol('aa')
    ll = Symbol('ll')
    nu = fixed_point_mean
    tau = fixed_point_var
    mean = 0.5 * ll * (
        nu + np.exp(-nu**2 / (2 * tau)) * np.sqrt(2 / np.pi) * np.sqrt(tau) +
        nu * erf(nu / (np.sqrt(2 * tau))) -
        aa * erfc(nu / (np.sqrt(2 * tau))) + np.exp(nu + tau / 2) * aa * erfc(
            (nu + tau) / (np.sqrt(2 * tau))))
    var = 0.5 * ll**2 * (
        np.exp(-nu**2 /
               (2 * tau)) * np.sqrt(2 / np.pi * tau) * nu + (nu**2 + tau) *
        (1 + erf(nu / (np.sqrt(2 * tau)))) + aa**2 * erfc(nu /
                                                          (np.sqrt(2 * tau))) -
        aa**2 * 2 * np.exp(nu + tau / 2) * erfc(
            (nu + tau) /
            (np.sqrt(2 * tau))) + aa**2 * np.exp(2 * (nu + tau)) * erfc(
                (nu + 2 * tau) / (np.sqrt(2 * tau)))) - mean**2
    eq1 = mean - nu
    eq2 = var - tau
    res = nsolve((eq2, eq1), (aa, ll), (1.67, 1.05))
    return float(res[0]), float(res[1])
Ejemplo n.º 20
0
def fit_curv(cheb_polynom, age_lb, age_ub):
    age = sympy.Symbol("age")
    b = sympy.Symbol("b")
    c = sympy.Symbol("c")
    d = sympy.Symbol("d")

    g = sympy.exp(b * (age)**2 + c * (age) + d)

    g_dif = sympy.diff(g, age)

    cheb_dif = sympy.diff(cheb_polynom)

    eq1 = cheb_polynom.subs(age, age_lb) - g.subs(age, age_lb)

    eq2 = cheb_dif.subs(age, age_lb) - g_dif.subs(age, age_lb)

    eq3 = g_dif.subs(age, age_ub) + 0.05

    # Using 0 as initial guesses, not sure whether they work for other cases
    sols = sympy.nsolve([eq1, eq2, eq3], [b, c, d], [0, 0, 0])

    sol_b = sols[0, :][0, 0]
    sol_c = sols[1, :][0, 0]
    sol_d = sols[2, :][0, 0]
    g_sol = g.subs([(b, sol_b), (c, sol_c), (d, sol_d)])

    f = lambdify(age, g_sol)

    age_bins = np.arange(age_lb, age_ub + 1)

    fit_values = f(age_bins)

    return fit_values
Ejemplo n.º 21
0
def calculateTemp(cc, rlc, rse, asw, asc, rsm, a03, alc, rsc, alw, eps_a, sigma, eps_e, ps0, f, alpha, beta):
    
    #atmosfære-koeffs
    refl_sw = (1-cc)*rsm + cc*rsc  # vektet refl for mol og sky
    abs_sw = ((1-cc)*(0.5*asw + 0.5*a03) + cc*asc)

    refl_lw = cc*rlc
    abs_lw = ((1-cc)*alw + cc*alc)  # vektet abs for molekyl og sky ganger

    #---------------Ledd for likning 1---------------------------#
    Pae = eps_a * sigma * x**4
    Pea_refl = refl_lw * eps_e * sigma * y**4
    # Psa_trans = ps0*(1-(asw+rsm))*(1-(a03+rsm))*(1-cc*(asc+rsc)) #3 -lags
    Psa_trans = (1-abs_sw) * (1-refl_sw) * ps0

    Pse_refl = Psa_trans * rse
    Pea_em = eps_e * sigma * y**4
    Pea_hl = -(alpha+beta)*(x-y)
    Pse_refl2 = Pse_refl * refl_sw

    # Equation 1
    eq1 = Pae + Pea_refl + Psa_trans - Pse_refl - Pea_hl - Pea_em + Pse_refl2  

    # Ledd for likning 2
    Ps0 = ps0
    Psa_refl = ps0 * refl_sw
    Pea_trans = Pea_em*(1-abs_lw)*(1-refl_lw)
    Pas = f*eps_a*sigma*x**4
    Pse_refl_trans = Pse_refl * (1-abs_sw) * (1-refl_sw)

    # Equation 2
    eq2 = - Ps0 + Psa_refl + Pea_trans + Pas +  Pse_refl_trans

    los = nsolve((eq1, eq2), (x, y), (320, 350))
    return [los[0],los[1]]
Ejemplo n.º 22
0
def calculate(args):
    '''For 20 values of n, set vals[n] to float representation of eigenvalue
    and set funcs[n] to corresponding eigenfunction with lambda as free
    variable.
    '''
    from first import LO
    if len(vals) != 0:
        return
    t,lam = sympy.symbols('t lam'.split())
    old = 1.0
    delta = 0
    ns = np.arange(1, args.n_calculate)
    for n in ns:
        T = 1.0/n
        A = LO(T, 1.0/3000)
        A.power(op=A.matvec, small=1.0e-8)
        vals_n[n] = A.eigenvalue
        funcs_n[n] = A.eigenvector
        F = Piecewise(n)
        funcs[n] = F
        new_ = sympy.nsolve(lam-F.integrate(), lam, old+delta)
        vals[n] = new_
        delta = new_ - old
        old = new_
        print('For n={0:d}, lambda={1}, delta={2}'.format(n,new_,delta))
Ejemplo n.º 23
0
def allroots(expr, degree, prec, chop=True):
    roots = set()
    start = random.random() + random.random()*I
    MAX_ITERATIONS = 5*degree
    i = 0
    while len(roots) < degree:
        i += 1
        if i > MAX_ITERATIONS:
            raise RuntimeError("MAX_ITERATIONS exceeded. Could only find %s roots" % len(roots))
        try:
            r = nsolve(expr/Mul(*[t - r for r in roots]), start,
                maxsteps=1.7*prec, prec=prec)
        except ValueError:
            start = 10*(random.random() + random.random()*I)
        else:
            roots.add(r)

    # Because we started with a complex number, real roots will have a small
    # complex part. Assume that the roots with the smallest complex parts are
    # real. We could also check which roots are conjugate pairs.
    if chop:
        from sympy.core.compatibility import GROUND_TYPES
        if GROUND_TYPES == 'python':
            warnings.simplefilter('default')
            warnings.warn("It is recommended to install gmpy2 to speed up transmutagen")
        n_real_roots = count_roots(nsimplify(expr))
        roots = sorted(roots, key=lambda i:abs(im(i)))
        real_roots, complex_roots = roots[:n_real_roots], roots[n_real_roots:]
        real_roots = [re(i) for i in real_roots]
        roots = {*real_roots, *complex_roots}
    return roots
Ejemplo n.º 24
0
def get_S95(b0, sigma):

    S95 = sy.Symbol('S95', positive=True, real=True)
    b = sy.Symbol('b', positive=True)
    chi21 = sy.Symbol('chi21')
    chi22 = sy.Symbol('chi22')

    chi2 = 3.84
    N = b0

    replacements = [(b, (b0 - S95 - sigma**2) / 2 + 1. / 2 *
                     ((b0 - S95 - sigma**2)**2 + 4 *
                      (sigma**2 * N - S95 * sigma**2 + S95 * b0))**0.5)]

    replacements2 = [(S95, 0.)]

    chi21 = -2 * (N * sy.log(S95 + b) - (S95 + b) - ((b - b0) / sigma)**2)

    chi21 = chi21.subs(replacements)
    chi22 = chi21.subs(replacements2)

    eq = chi2 - chi21 + chi22

    S95_new = sy.nsolve(eq, S95, 1)

    return float(S95_new)
Ejemplo n.º 25
0
def area_calc(r1, r2):

    # convert r1 and r2 from the main program in meters to inches for the calculation
    r1 = r1 * 100 / 2.54
    r2 = r2 * 100 / 2.54

    # ISO 160 pipe dia in inches
    pipedia = 5.83

    a1 = pi * r1**2
    asm = pi * ((pipedia / 2)**2)

    # d is the distance between the center points of the two circles
    # d1 is the distance from the origin to the intersection point
    def d1(d):
        return (r1**2 - r2**2 + d**2) / (2 * d)

    # d2 is the distance from the intersection point to the center of circle 2
    def d2(d):
        return d - d1(d)

    # t is defined but not used (used in main program as pipethickcheck) used for debugging at one point
    def t(d):
        return r1 - r2 + d

    # a(d) is the area of the crescent shape
    def a(d):
        return a1 - r1**2 * acos(
            d1(d) / r1) + d1(d) * sqrt(r1**2 - d1(d)**2) - r2**2 * acos(
                d2(d) / r2) + d2(d) * sqrt(r2**2 - d2(d)**2)

    # Solve for the height of the second circle above the x-axis assuming the are is the same
    x = symbols('x', real=True)

    h = re(nsolve(a(x) - asm, x, 10))

    # print(t(h))
    # Solve for the intersection angles assuming h is the height of the 2nd circle above the x-axis
    ang = symbols('ang')

    th = nsolve(r1 - h * sin(ang) - sqrt(h**2 * sin(ang)**2 - h**2 + r2**2),
                ang, 2)

    hmeter = h * 2.54 / 100
    # return this angle and height to the main program
    return th, hmeter
Ejemplo n.º 26
0
 def solve(self, guess, **kwargs):
     guess = tuple(guess)
     try:
         abc = sp.nsolve(self.equation_set, self.variables, guess, **kwargs)
     except ValueError:
         # non convergence of solver
         abc = [None] * len(guess)
     return np.array(abc, dtype=np.float)
Ejemplo n.º 27
0
def ytm(ytm=None, fv=None, cpn=None, n=None, p=None, should_round=True):
    """Converts between present money and future money taking into account interest rates and years past.
    ytm: Yield to maturity.
    fv: future value including coupon payments and payout.
    cpn: coupon payment amount in dollars.
    n: number of coupon payment periods.
    p: Current market price.
    """
    global FORMULAS
    name = 'ytm'

    # generate all rearrangements of the given expression
    if name not in FORMULAS:
        _ytm, _fv, _cpn, _p, _n = sympy.symbols("ytm fv cpn p n")
        p_expr = _cpn * (1 / _ytm) * (1 - (1 /
                                           (1 + _ytm)**_n)) + (_fv /
                                                               (1 + _ytm)**_n)
        FORMULAS[name] = all_functions(_p, p_expr, [_ytm, _fv, _cpn, _n, _p])

    # insist on the right number of arguments
    supplied = sum(1 if v is not None else 0 for v in (ytm, fv, cpn, n, p))
    if supplied != 4:
        raise Exception("Invalid number of arguments")

    if ytm is None:
        ret = FORMULAS[name]['p'].equation.subs({
            'p': p,
            'cpn': cpn,
            'n': n,
            'fv': fv
        })
        rets = []
        for i in range(1000):
            try:
                rets.append(
                    sympy.nsolve(ret, sympy.Symbol("ytm"), (i + 1) / 1000))
            except ValueError:
                pass
            finally:
                pass
        logging.debug(rets)
        ret = [rets[0], "YTM"]
    elif fv is None:
        ret = [FORMULAS[name]['fv'](ytm=ytm, cpn=cpn, n=n, p=p), "FV"]
    elif cpn is None:
        print(FORMULAS[name]['cpn'].equation)
        ret = [FORMULAS[name]['cpn'](ytm=ytm, fv=fv, n=n, p=p), "CPN"]
    elif n is None:
        ret = [FORMULAS[name]['n'](ytm=ytm, fv=fv, cpn=cpn, p=p), "n"]
    elif p is None:
        ret = [FORMULAS[name]['p'](ytm=ytm, fv=fv, cpn=cpn, n=n), "P"]
    else:
        print("You supplied all the arguments, there's nothing to calculate")
        return None

    if should_round:
        ret[0] = round(ret[0], RESULT_PRECISION)
    return ret
Ejemplo n.º 28
0
def queuing_model(x, q):
    '''x : variable de contrôle array taille M
    renvoie le y associé à x par le queuing model'''
    mu = calc_mu(x)

    var = []
    eqn = []

    for i in range(N):

        lambda_eff = symbols('lambda{}'.format(i))
        rho_eff = symbols('rho{}'.format(i))
        P = symbols('P{}'.format(i))

        var.append(lambda_eff)
        var.append(rho_eff)
        var.append(P)

    for i in range(N):

        lambda_eff = var[3 * i]
        rho_eff = var[3 * i + 1]
        P = var[3 * i + 2]

        gamma = q[1][i][1]
        k = q[1][i][0]

        eqn1 = -lambda_eff + gamma * (1 - P)

        for j in range(N):
            eqn1 += q[0][j][i] * var[3 * j]

        eqn2 = -rho_eff + lambda_eff / mu[i]
        S1 = 0
        S2 = 0
        for j in range(N):
            p = q[0][i][j]
            S1 += p * var[3 * j + 2]
            if (p != 0):
                S2 += var[3 * j + 1]
        eqn2 += S1 * S2

        eqn3 = -P + (1 - rho_eff) / (1 - rho_eff**(k + 1)) * rho_eff**k

        eqn.append(eqn1)
        eqn.append(eqn2)
        eqn.append(eqn3)

    y0 = np.array([0] * (3 * N))
    sol = nsolve(eqn, var, y0)

    y = np.zeros((N, 3))
    for i in range(N):
        y[i][0] = sol[3 * i]
        y[i][1] = sol[3 * i + 1]
        y[i][2] = sol[3 * i + 2]

    return y
Ejemplo n.º 29
0
    def compute_mus():

        def reduce_mu():
            omega = [e0 - sum([mu[site_mu_map[i]]*sum(c0[i,:]) for i in range(n)])]
            x = solve(omega)
            return x

        # Compute trial mu
        mu_red = reduce_mu()
        #print mu_red

        mult = multiplicity
        #for ind in specie_site_index_map:
        #    print ind[0], ind[1]
        specie_concen = [sum(mult[ind[0]:ind[1]]) for ind in specie_site_index_map]
        #print 'specie_concent', specie_concen
        y_vect = [specie_concen[-1]/specie_concen[i] for i in range(m)]
        #print 'y_vect', y_vect
        vector_func = [y_vect[i]-c_ratio[i] for i in range(m-1)]
        vector_func.append(omega)
        #print vector_func
        #vector_func.append(mu_equalities)
        #print 'y0', y0
        min_diff = 1e10
        mu_vals = None
        c_val = None
        m1_min = -20.0
        if e0 > 0:
            m1_max = 10            # Search space needs to be modified
        else:
            m1_max = 0
        for m1 in np.arange(m1_min,m1_max,0.1):
            m0 = mu_red[mu[0]].subs(mu[-1],m1)

            try:
                x = nsolve(vector_func,mu,[m0,m1],module="numpy")
                # Line needs to be modified to include all mus when n > 2
            except:
                continue

            c_val = c.subs(dict(zip(mu,x)))
            #print c_val
            #if all(x >= 0 for x in c_val):
            specie_concen = []
            for ind in specie_site_index_map:
                specie_concen.append(sum([sum(c_val[i,:]) for i in range(*ind)]))
            y_comp = [specie_concen[-1]/specie_concen[i] for i in range(m)]
            diff = math.sqrt(sum([pow(abs(y_comp[i]-y_vect[i]),2) for i in range(m)]))
            if diff < min_diff:
                min_diff = diff
                mu_vals = x

        if mu_vals:
            mu_vals = [float(mu_val) for mu_val in mu_vals]
        else:
            raise ValueError()
        print mu_vals
        return mu_vals
Ejemplo n.º 30
0
    def find_eigenvalues_sympy(self, scatter_eigenvalues, start=None):
        """
        ToDo: Get the execution time to a finite value for channels >= 5.

        In the moment this function only supports small number of channels.
        Sympy has some problems when the number of channels gets higher.

        Use find_eigenvalues_v2, that is more stable.

        >>> import pytest; pytest.skip('Bingham is to slow')
        >>> import sympy
        >>> trainer = ComplexBinghamTrainer(2)
        >>> trainer.find_eigenvalues_sympy([0.9, 0.1])
        array([[ 0.        ],
               [-9.99544094]])

        >>> trainer.grad_log_norm([0.9, 0.1])
        array([0.56596622, 0.43403378])

        >>> trainer.grad_log_norm([0., -9.99544094])
        array([0.9, 0.1])
        >>> trainer.grad_log_norm([0. + 10, -9.99544094 + 10])
        array([0.9, 0.1])

        # >>> ComplexBinghamDistribution.estimateParameterMatrix([0.9, 0, 0; 0, 0.06, 0; 0, 0, 0.04])
        >>> trainer = ComplexBinghamTrainer(3)
        >>> trainer.find_eigenvalues_sympy([0.9, 0.06, 0.04])
        array([[  0.        ],
               [-16.59259207],
               [-24.95061675]])
        >>> trainer.find_eigenvalues_sympy([0.9, 0.05, 0.05])
        array([[  0.        ],
               [-19.93827431],
               [-19.93827213]])

        """
        inverse_permutation, scatter_eigenvalues = ComplexBingham._remove_duplicate_eigenvalues(
            np.array(scatter_eigenvalues))

        import sympy
        out_to_solve = [
            sympy.simplify(o - i)
            for o, i in zip(self.grad_log_norm_symbolic, scatter_eigenvalues)
        ]
        if start is None:
            #  The Complex Bingham Distribution and Shape Analysis
            #  Eq. (3.3)
            start = list(-1 / np.array(scatter_eigenvalues))
        result = sympy.nsolve(out_to_solve,
                              self.eigenvalues_symbol,
                              start,
                              tol=1e-6)

        res = np.array(result.tolist()).astype(np.float64)
        res = res - np.amax(res)
        return res[inverse_permutation]
Ejemplo n.º 31
0
 def stone(A,F,C,L,rho):
         """ computation of stoneley velocity """
         
         x = symbols('x')
         seq  = x + (((x-L)/(x-A))**.5)*((C*(x-A)+F**2)/(C*L)**.5)
         sol = nsolve(seq,0)
         csol = N(sol,n=12, chop=True)
         check = seq.subs(x,csol)
         velocity = (csol/rho)**.5
         return(csol,check,velocity)   
Ejemplo n.º 32
0
def bug_not_high_precision():
    var('g', positive=True)
    f = -48*asin(sqrt(2)/sqrt(-g**2 + 4)) - 48*asin(1/sqrt(-g**2 + 4)) + 24*pi
    assert 0 == nsimplify(f.subs(g,1))
    sympy.mpmath.mp.dps = 100
    x = nsolve(f, g, 1)
    '''str(x)='0.99...' or "mpf('0.99...')" '''
    return '0.9999999999999990760' in str(x)
    assert str(x)[6:][:21] == '0.9999999999999990760'
    assert '0.9999999999999990760' in str(x)
Ejemplo n.º 33
0
def paper_cram_error(degree, t0, prec=200):
    from ..partialfrac import t, customre

    from sympy import re, exp, nsolve, diff

    paper_part_frac = get_paper_part_frac(degree).replace(customre, re)

    E = paper_part_frac - exp(-t)

    return E.subs(t, nsolve(diff(E, t), t0, prec=prec))
Ejemplo n.º 34
0
def e_val(tau, start=None):
    '''Calculate approximate eigenvalue using eq:2
    '''
    t, lam = sympy.symbols('t lam'.split())
    f = t - lam * sympy.exp((t - 1) / lam)
    f_tau = f.subs(t, tau)
    if start == None:
        start = tau
    rv = sympy.nsolve(f_tau, lam, start)  #, tol=1e-8)
    return rv
Ejemplo n.º 35
0
def e_val(tau, start=None):
    '''Calculate approximate eigenvalue using eq:2
    '''
    t,lam = sympy.symbols('t lam'.split())
    f = t - lam*sympy.exp((t-1)/lam)
    f_tau = f.subs(t,tau)
    if start == None:
        start = tau
    rv = sympy.nsolve(f_tau, lam, start)#, tol=1e-8)
    return rv
Ejemplo n.º 36
0
def ellipse_points(a,b,R,precision=0.2*math.pi/180, step_R=0.1,plot=True):

    """

    Function ellipse_points finds points on an ellipse equaly spaced
    Arguments:
    1. a: semi-major axis of the ellipse
    2. b: semi-minor axis of the ellipse
    3. R: spacing between points
    Optional arguments:
    4. precision: the precision in radians on spacing
    5. step_R: the step in spacing between each iteration
    """
    x = Symbol('x')
    y = Symbol('y')
    ellipse = (x/a)**2 + (y/b)**2 - 1
    t_final=math.pi/2
    iter_nb=0    
    continue_loop = True
    while continue_loop:
        iter_nb += 1
        if iter_nb > 1:
            print('Iterations: {0:.0f}, deviation at final position {1:4.2f} degrees'.format(iter_nb-1,(t-t_final)*180/math.pi))
        t=0 #math.pi/10
        x_sol=[a*math.cos(t)]
        y_sol=[b*math.sin(t)]
        t_sol=[t]
        while t < t_final-precision:
            x0 = a*math.cos(t)
            y0 = b*math.sin(t)
            cercle = (x-x0)**2 + (y-y0)**2 -R**2
            trynextguess=True
            nbguessiter=0
            while (trynextguess and nbguessiter < 10):
                try:
                    derivative= [-a*math.sin(t),b*math.cos(t)]
                    direction = R/np.linalg.norm(derivative)*np.array(derivative)
                    guess = np.array([x0,y0])+direction
                    sol=nsolve((ellipse,cercle), (x, y), (guess[0],guess[1]))
                    trynextguess=False
                except ValueError,e:
                    nbguessiter += 1
                    print(e)
                    print('Initial guess changed. We retry: {0:4.0f} iterations'.format(
                    nbguessiter))
                    t+=math.atan(R/4/a)
            #print(sol)            
            t =  math.acos(float(sol[0])/a)
            t_sol.append(t)
            x_sol.append(a*math.cos(t))
            y_sol.append(b*math.sin(t))
        if math.fabs(t-t_final) < precision: 
            continue_loop = False
        else:
            R-=step_R
Ejemplo n.º 37
0
def get_cut_model_probs(etas,interactions,k,use_scipy=True,method='hybr',seed=0):
    dim = len(interactions.keys()[0])
    etasKeys = filter(lambda keys: sum(keys) <= k, etas.keys())
    intsKeys = filter(lambda keys: sum(keys) > k,interactions.keys())
    def getPaddedBinaries(ints,minL):
        padStr = reduce(lambda x,y:x+y,['0' for i in range(minL)])
        binaries = [bin(i)[2:] for i in ints]
        return map(lambda binStr: padStr[:minL-len(binStr)]+binStr,binaries)

    varStrings = ['p'+binStr for binStr in getPaddedBinaries(xrange(2**dim),dim)]
    varSymbols = [S(varStr) for varStr in varStrings]
    eqs = []

    # all probabilities should sum to 1
    eqs.append('('+reduce(lambda x,y: x+'+'+y,varStrings)+'-1)')

    # for each marginal, add a constraint for the sum of all patterns containing the marginal indices
    for etaKey in etasKeys:
        zeroIdxs = filter(lambda i: etaKey[i]==0,range(dim))
        containingPatternsFlips = subsets(set(zeroIdxs))
        containingPatterns = map(lambda idxs: 'p'+reduce(lambda x,y: str(x)+str(y),idxs),map(lambda flipIdxs: flip(etaKey,flipIdxs),containingPatternsFlips))
        eqs.append('('+reduce(lambda x,y: x+'+'+y,containingPatterns)+'-{0})'.format(etas[etaKey]))

    # for each interaction, add a constraint
    for intKey in intsKeys:
        oneIdxs = filter(lambda i: intKey[i]==1,range(dim))
        subPatternFlips = subsets(set(oneIdxs))
        subPatterns = [flip(intKey,flipIdxs) for flipIdxs in subPatternFlips]
        expr = '(1.0'
        for i,pattern in enumerate(subPatterns):
            patternId = 'p'+reduce(lambda x,y: str(x)+str(y),pattern)
            if len(subPatternFlips[i]) % 2 ==0:
                expr = expr+'*{0}'.format(patternId)
            else:
                expr = expr+'/{0}'.format(patternId)
        eqs.append(expr+'-{0})'.format(np.exp(interactions[intKey])))
    exprs = tuple([sympify(eq) for eq in eqs])
    
    if use_scipy:
        from scipy.optimize import root,fmin_tnc,minimize,fsolve
        evaluators = [lambdify(tuple(varSymbols),expr) for expr in exprs]
        
        def objective_fun(x0):
            return np.array([evaluator(*x0) for evaluator in evaluators])
        np.random.seed(seed)
        x0 = np.random.rand(2**dim)/2**(dim-1)
        x0 = x0/np.sum(x0)
        res,idict,c,d=fsolve(objective_fun, x0,full_output=True)#,method=method)
        return res,idict,c,d
            
     
    else:
        res = nsolve(exprs,tuple(varSymbols),tuple([1.0/2**dim for _ in xrange(2**dim)]))
        return np.array(([float(r) for r in res]))
	def run_finally(cls, cxn, parameters_dict, all_data, det):    
		print "switching the 866 back to ON"
		cxn.pulser.switch_manual('866DP', True)

		ident = int(cxn.scriptscanner.get_running()[-1][0])
		print " sequence ident" , ident

		all_data = np.array(all_data)
		try:
			all_data = all_data.sum(1)
		except ValueError:
			return

		p = parameters_dict
		duration = p.DriftTrackerRabi.line_1_pi_time
		freq = np.pi/duration

		ind1 = np.where(det == -1)
		ind2 = np.where(det == 1)

		det1 = det[ind1][0] * 2.39122444/p.DriftTrackerRabi.line_1_pi_time
		det2 = det[ind2][0] * 2.39122444/p.DriftTrackerRabi.line_1_pi_time

		p1 = all_data[ind1][0]
		p2 = all_data[ind2][0]

		print "at ",det1, " the pop is", p1
		print "at ",det2, " the pop is", p2

		from sympy import sin, symbols, nsolve
		x = symbol('x')

		relative_det_1 = nsolve(freq**2 / (freq**2 + (x + det1)**2) * (sin((freq**2 + (x - det1)**2)**0.5 * duration / 2))**2 - p1, 0)
		relative_det_2 = nsolve(freq**2 / (freq**2 + (x + det2)**2) * (sin((freq**2 + (x - det2)**2)**0.5 * duration / 2))**2 - p2, 0)

		global detuning_1_global
		detuning_1_global = U((relative_det_1 + relative_det_2)/2, 'kHz')

		print "detuning 1", (relative_det_1 + relative_det_2)/2
Ejemplo n.º 39
0
def get_r_and_n(dist_W, dist_E, dx_min, n_tel, init_r):
    """Numerically solve for the nW, nE, and r

    Sum of geometric sequence in standard form:
    a + a*r + a*r^2 + ... + a*r^(n-1) = a(1 - r^n)/(1 - r)
    However, I want to start at a*r^1, not a*r^0
    a*r + a*r^2 + ... + a*r^(n-1) = a((1 - r^n)/(1 - r) - 1)
    """
    #
    # Define the three unknowns
    nE = Symbol('nE')
    nW = Symbol('nW')
    r = Symbol('r')
    #
    # Equations to be solved
    eqns = [(dist_W/dx_min)*(1 - r) + r**(nW+1) - r,
            (dist_E/dx_min)*(1 - r) + r**(nE+1) - r,
            nW + nE - n_tel]

    # Put arguments in list and provide an initial guess
    args = [nW, nE, r]
    total_log_dist_sum = np.log(dist_W) + np.log(dist_E)
    nW_guess = np.log(dist_W)/total_log_dist_sum*n_tel
    nE_guess = np.log(dist_E)/total_log_dist_sum*n_tel

    # Find the solution numerically

    # The initial guess is pretty important, especially init_r
    # Want to ensure we don't get r = 1, which is the trivial but useless soln
    # This ends up being suprisingly robust

    r_found = False
    while not r_found:
        try:
            out = nsolve(eqns, args, [nW_guess, nE_guess, init_r])
            # Check for trivial soln (comes about from init_r being too low)
            if float(out[2]) == 1.0:
                # Over compensate by setting init_r far too high and starting
                # again
                init_r = 5
            else:
                r_found = True
        except ValueError:
            # Reduce r (if r = 1.5, set it to 1.25, then 1.125, etc until
            # solution is found)
            init_r = 1 + (init_r - 1)/2

    nW, nE, r = out
    nW, nE = [np.round(float(X)).astype(int) for X in [nW, nE]]
    r = float(r)
    return nW, nE, r
Ejemplo n.º 40
0
    def _solve_A(self, A, **kwargs):
        """
        d, L are given in mm

        """

        d = kwargs.get('d', 40.)
        L = kwargs.get('L', 150.)
        acc_check = kwargs.get('acc_check', 0.0000001)
        solve_acc = kwargs.get('solve_acc', 20)

        # set the accuracy target of the solver
        sympy.mpmath.mp.dps = solve_acc
        psi = sympy.Symbol('psi')
        f1 = L - (L*sympy.tan(psi)) + (d/(2.*sympy.cos(psi))) - A
        # initial guess: solve system for delta_x = 0
        psi0 = math.atan(1 - (A/L))
        # solve the equation numerically with sympy
        psi_sol = sympy.nsolve(f1, psi, psi0)

        # verify if the solution is valid
        delta_x = d / (2.*math.cos(psi_sol))
        x = L*math.tan(psi_sol)
        Asym = sympy.Symbol('Asym')
        f_check = x - L + Asym - delta_x
        # verify that f_check == 0
        if not sympy.solvers.checksol(f_check, Asym, A):
            # in the event that it does not pass the checksol, see how close
            # the are manually. Seems they are rather close
            check_A = L + delta_x - x
            error = abs(A - check_A) / A
            if error > acc_check:
                msg = 'sympy\'s solution does not passes checksol()'
                msg += '\n A_check=%.12f <=> A=%.12f' % (check_A, A)
                raise ValueError, msg
            else:
                msg = 'sympy.solvers.checksol() failed, manual check is ok. '
                msg += 'A=%.2f, rel error=%2.3e' % (A, error)
                logging.warning(msg)

        return psi_sol*180./math.pi, psi0*180./math.pi
Ejemplo n.º 41
0
def solveSS(gamma,xsi,a):
	beta  = 0.98
	alpha = 0.4
	delta = 0.10
	zbar  = 0.
	tao   = 0.05
	expZbar = 1.
	epsilon = .1
	rho = 0.90


	#Solve SS
	Css = Symbol('Css')
	rss = Symbol('rss')
	lss = Symbol('lss')
	wss = Symbol('wss')
	Tss = Symbol('Tss')
	kss = Symbol('kss')

	#-----------------------------------------------------------------#
	#------------------Variables/Equations----------------------------#
	#-----------------------------------------------------------------#
	f1 = Css - (1.-tao)*(wss*lss + (rss-delta)*kss) - Tss
	f2 = 1. - beta*((rss-delta)*(1. - tao) +1)
	f3 = (a/((1.-lss)**xsi))-((1./Css**gamma)*wss*(1.-tao))
	f4 = rss - ((alpha)*(kss**(alpha-1.))*(lss**(1.-alpha)))
	f5 = wss - ((1. - alpha)*(kss**alpha)*(lss**(-alpha)))
	f6 = Tss - (tao*(wss*lss + (rss - delta)*kss))

	# use nsolve to solve for SS values
	SOLSS = nsolve((f1,f2,f3,f4,f5,f6),(Css, rss, lss, wss, Tss, kss),
                   (.75,.12,.55,1.32,.041,4.05))

	cs = float(SOLSS[0])
	rs = float(SOLSS[1])
	ls = float(SOLSS[2])
	ws = float(SOLSS[3])
	Ts = float(SOLSS[4])
	ks = float(SOLSS[5])
	return cs,rs,ls,ws,Ts,ks
Ejemplo n.º 42
0
    def nsolve(self, x0):
        """Attempt a numeric solution and return a Result object.

        Will raise a value error if self does not contain an
        equation. Returns None if no solution was found.

        """
        if not isinstance(self.raw_result, sympy.Equality):
            raise ValueError("Trying to solve something that is not an "
                             "equation.")
        try:
            solution = sympy.nsolve(self.raw_result, x0)
        except ValueError:
            return None
        # Wrap in sympy. TODO: precision    
        solution = (
            sympy.Float(solution.real, 1000)
            + sympy.Float(solution.imag, 1000) * sympy.I
        )
        return self.__class__(self.input_str,
                              self.parsed,
                              solution,
                              True)
def find_best_threshold_and_error(u_size,n_std,samples):
    '''
        u_error is when we detect uniform as normal
    '''
    # print(find_best_threshold_and_error(8.8,1,10))
    u_n_error_ratio=3
    if 1: # much faster way...:
        u_error = simplify("u_n_error_ratio*((x * 2.0 / u_size)^samples)".replace("u_n_error_ratio",str(u_n_error_ratio)))
        cdf = "(0.5 + 0.5*erf(-x/(sqrt(2)*n_std)))"
        n_error = simplify("1 - (1-2*cdf)^ samples".replace('cdf',cdf))
    else:
        nor = Normal(x, 0, n_std)
        u_error = simplify("(x * 2.0 / u_size)^samples")
        n_error = simplify("1 - (1-2*cdf)^samples")
        n_error = n_error.subs(Symbol("cdf"),P(nor>x))
    eqtn=n_error-u_error
    # pprint(eqtn)
    subs=[(Symbol("samples"),samples),(Symbol("n_std"),n_std),(Symbol("u_size"),u_size)]
    eqtn=eqtn.subs(subs)
    threshold=nsolve(eqtn,x,(n_std,u_size/2.0),simplify=False,rational=False , solution_dict=False, verify=False)
    error=u_error.subs(x,threshold).subs(subs).evalf()
    # print("u size: %g, n std: %6.04g, samples: %2d, threshold: %6.04g, error: %6.04g"%(u_size,n_std,samples,threshold,error))
    return float(threshold),float(error)
Ejemplo n.º 44
0
    def compute_mus():

        def reduce_mu():
            host_concen = 1-solute_concen
            new_c0 = c0.astype(float)
            for i in range(n):
                new_c0[i,i] = host_concen*c0[i,i]
            new_c0[n,n] = 2*solute_concen
            omega = [
                e0-sum([mu[site_mu_map[i]]*sum(new_c0[i,:])
                    for i in range(n+1)])]
            x = solve(omega)
            return x

        # Compute trial mu
        mu_red = reduce_mu()
        #print(('mu_red', mu_red))

        mult = multiplicity
        #for ind in specie_site_index_map:
        #    print(ind[0], ind[1])
        specie_concen = [
            sum(mult[ind[0]:ind[1]]) for ind in specie_site_index_map]
        #print('specie_concen', specie_concen)
        max_host_specie_concen = 1-solute_concen
        host_specie_concen_ratio = [specie_concen[i]/sum(specie_concen)* \
                                    max_host_specie_concen for i in range(m)]
        host_specie_concen_ratio[-1] = solute_concen
        #print('hostspecie_concen_rat', host_specie_concen_ratio)


        y_vect = host_specie_concen_ratio
        #print(('y_vect', y_vect))
        vector_func = [y_vect[i]-c_ratio[i] for i in range(m)]
        vector_func.append(omega)
        #print((vector_func))
        mu_vals = None
        c_val = None
        m_min = -15.0
        if e0 > 0:
            m_max = 10            # Search space needs to be modified
        else:
            m_max = 0
        for m1 in np.arange(m_min,m_max,0.3):
            for m2 in np.arange(m_min,m_max,0.3):
                m0 = mu_red[mu[0]].subs([(mu[1],m1),(mu[2],m2)])
                try:
                    #print(m1,m2)
                    mu_vals = nsolve(vector_func,mu,[m0,m1,m2],module="numpy")
                    #mu_vals = nsolve(vector_func,mu,[m0,m1,m2])
                    # Line needs to be modified to include all mus when n > 2
                except:
                    continue
                break
            if mu_vals:
                mu_vals = [float(mu_val) for mu_val in mu_vals]
                break
        else:
            raise ValueError("Couldn't find mus")
        #print (('mu_vals', mu_vals))
        return mu_vals
Ejemplo n.º 45
0
def solute_site_preference_finder(
        structure, e0, T, vac_defs, antisite_defs,  solute_defs,
        solute_concen=0.01, trial_chem_pot = None):

    """
    Compute the solute defect densities using dilute solution model.
    Args:
        structure: pymatgen.core.structure.Structure object representing the
            primitive or unitcell of the crystal.
        e0: The total energy of the undefected system.
            This is E0 from VASP calculation.
        T: Temperature in Kelvin
        vac_defs: List of vacancy defect parameters in the dictionary format.
            The keys of the dict associated with each vacancy defect are
            1) site_index, 2) site_specie, 3) site_multiplicity, and
            4) energy. 1-3 can be obtained from
            pymatgen.analysis.defects.point_defects.Vacancy class.
            Site index is expected to start with 1 (fortran index).
        antisite_defs: List of antisite defect parameters in the dictionary
            format. The keys of the dict associated with each antisite
            defect are 1) site_index, 2) site_specie, 3) site_multiplicity,
            4) substitution_specie, and 5) energy. 1-3 can be obtained
            from pymatgen.analysis.defects.point_defects.Vacancy class.
        solute_defs: List of solute defect parameters in the dictionary
            format. Similary to that of antisite defs, wtih solute specie
            specified in substitution_specie
        solute_concen: Solute concentration (in fractional value)
        trial_chem_pot: Trial chemical potentials to speedup the plot
            generation. Format is {el1:mu1,...}

    Returns:
        plot_data: The data for plotting the solute defect concentration.
    """

    if not check_input(vac_defs):
        raise ValueError('Vacancy energy is not defined')
    if not check_input(antisite_defs):
        raise ValueError('Antisite energy is not defined')

    formation_energies = {}
    formation_energies['vacancies'] = copy.deepcopy(vac_defs)
    formation_energies['antisites'] = copy.deepcopy(antisite_defs)
    formation_energies['solute'] = copy.deepcopy(solute_defs)
    for vac in formation_energies['vacancies']:
        del vac['energy']
    for asite in formation_energies['antisites']:
        del asite['energy']
    for solute in formation_energies['solute']:
        del solute['energy']
    # Setup the system
    site_species = [vac_def['site_specie'] for vac_def in vac_defs]
    solute_specie = solute_defs[0]['substitution_specie']
    site_species.append(solute_specie)
    multiplicity = [vac_def['site_multiplicity'] for vac_def in vac_defs]
    m = len(set(site_species))      # distinct species
    n = len(vac_defs)           # inequivalent sites

    # Reduce the system and associated parameters such that only distinctive
    # atoms are retained
    comm_div = gcd(*tuple(multiplicity))
    multiplicity = [val/comm_div for val in multiplicity]
    multiplicity.append(0)
    e0 = e0/comm_div
    T = Integer(T)

    c0 = np.diag(multiplicity)
    #print(('c0', c0))
    mu = [Symbol('mu'+str(i)) for i in range(m)]

    # Generate maps for hashing
    # Generate specie->mu map and use it for site->mu map
    specie_order = []       # Contains hash for site->mu map    Eg: [Al, Ni]
    site_specie_set = set()             # Eg: {Ni, Al}
    for i in range(len(site_species)):
        site_specie  = site_species[i]
        if site_specie not in site_specie_set:
            site_specie_set.add(site_specie)
            specie_order.append(site_specie)
    site_mu_map = []     # Eg: [mu0,mu0,mu0,mu1] where mu0->Al, and mu1->Ni
    for i in range(len(site_species)):
        site_specie  = site_species[i]
        j = specie_order.index(site_specie)
        site_mu_map.append(j)
    specie_site_index_map = []      # Eg: [(0,3),(3,4)] for Al & Ni
    for i in range(m):
        low_ind = site_species.index(specie_order[i])
        if i < m-1:
            hgh_ind = site_species.index(specie_order[i+1])
        else:
            hgh_ind = len(site_species)
        specie_site_index_map.append((low_ind,hgh_ind))

    """
    dC: delta concentration matrix:
    dC[i,j,k]: Concentration change of atom i, due to presence of atom
    j on lattice site k
    Special case is [i,i,i] which is considered as vacancy
    Few cases: dC[i,i,i] = -1 due to being vacancy special case
                dC[k,k,i] = +1 due to increment in k at i lattice if i
                               lattice type is of different element
                dC[i,k,i] = -1 due to decrement of ith type atom due to
                presence of kth type atom on ith sublattice and kth type
                atom specie is different from ith sublattice atom specie
                dC[i,k,k] = 0 due to no effect on ith type atom
                dC[i,j,k] = 0 if i!=j!=k
    """
    dC = np.zeros((n+1,n+1,n), dtype=np.int)
    for i in range(n):
        for j in range(n):
            for k in range(n):
                if i == j and site_species[j] != site_species[k] and \
                        site_species[i] != site_species:
                    dC[i,j,k] = 1
        for j in range(n+1):
            for k in range(n):
                if i == k:
                    #if j == k or site_species[j] != site_species[k]:
                        dC[i,j,k] = -1
    for k in range(n):
        dC[n,n,k] = 1
    for k in range(n):
        for j in range(n):
            if i != j:
                if site_species[i] == site_species[k]:
                    dC[i,j,k] = 0

    for ind_map in specie_site_index_map:
        if ind_map[1]-ind_map[0] > 1:
            for index1 in range(ind_map[0]+1,ind_map[1]):
                for index2 in range(ind_map[0]):
                    for i in range(n):
                        print (i, index1, index2)
                        dC[i,index1,index2] = 0
                for index2 in range(ind_map[1],n):
                    for i in range(n):
                        print (i, index1, index2)
                        dC[i,index1,index2] = 0

    print ('dC', dC)
    # dE matrix: Flip energies (or raw defect energies)
    els = [vac_def['site_specie'] for vac_def in vac_defs]
    dE = []
    for i in range(n+1):
        dE.append([])
    for i in range(n+1):
        for j in range(n):
            dE[i].append(0)

    for j in range(n):
        for i in range(n):
            if i == j:
                dE[i][j] = vac_defs[i]['energy']
            else:
                sub_specie = vac_defs[i]['site_specie']
                site_specie = vac_defs[j]['site_specie']
                if site_specie == sub_specie:
                    dE[i][j] = 0
                else:
                    for as_def in antisite_defs:
                        if int(as_def['site_index']) == j+1 and \
                                sub_specie == as_def['substitution_specie']:
                            dE[i][j] = as_def['energy']
                            break
        # Solute
        site_specie = vac_defs[j]['site_specie']
        for solute_def in solute_defs:
            def_site_ind = int(solute_def['site_index'])
            def_site_specie = solute_def['site_specie']
            #print((def_site_specie, site_specie))
            #print((def_site_ind, j+1))
            if def_site_specie == site_specie and def_site_ind == j+1:
                #print(('se', solute_def['energy']))
                dE[n][j] = solute_def['energy']
                break

    dE = np.array(dE)
    #np.where(dE == np.array(None), 0, dE)

    # Initialization for concentrations
    # c(i,p) == presence of ith type atom on pth type site
    c = Matrix(n+1,n,[0]*n*(n+1))
    for i in range(n+1):
        for p in range(n):
            c[i,p] = Integer(c0[i,p])
            #print((c[i,p]))
            for epi in range(n+1):
                sum_mu = sum([mu[site_mu_map[j]]*Integer(
                        dC[j,epi,p]) for j in range(n+1)])
                #print((sum_mu))
                #print((multiplicity[p], dC[i,epi,p], dE[epi,p]))
                c[i,p] += Integer(multiplicity[p]*dC[i,epi,p]) * \
                        exp(-(dE[epi,p]-sum_mu)/(k_B*T))
    #print(("--------c---------"))
    #for i in range(n+1):
    #    print((c[i,:]))
    #print(("--------c---------"))

    #specie_concen = [sum(mult[ind[0]:ind[1]]) for ind in specie_site_index_map]
    #total_c = [sum(c[ind[0]:ind[1]]) for ind in specie_site_index_map]
    total_c = []
    for ind in specie_site_index_map:
        total_c.append(sum([sum(c[i,:]) for i in range(*ind)]))
    #total_c = [sum(c[i,:]) for i in range(n)]
    c_ratio = [total_c[i]/sum(total_c) for i in range(m)]
    print(('-------c_ratio-------------'))
    for i in range(m):
        print((c_ratio[i]))

    # Expression for Omega, the Grand Potential
    omega = e0 - sum([mu[site_mu_map[i]]*sum(c0[i,:]) for i in range(n+1)])
    for p_r in range(n):
        for epi in range(n):
            sum_mu = sum([mu[site_mu_map[j]]*Integer(
                    dC[j,epi,p_r]) for j in range(n+1)])
            omega -= k_B*T*multiplicity[p_r]*exp(-(dE[epi,p_r]-sum_mu)/(k_B*T))

    print ('omega')
    print (omega)
    def compute_mus():

        def reduce_mu():
            host_concen = 1-solute_concen
            new_c0 = c0.astype(float)
            for i in range(n):
                new_c0[i,i] = host_concen*c0[i,i]
            new_c0[n,n] = 2*solute_concen
            omega = [
                e0-sum([mu[site_mu_map[i]]*sum(new_c0[i,:])
                    for i in range(n+1)])]
            x = solve(omega)
            return x

        # Compute trial mu
        mu_red = reduce_mu()
        #print(('mu_red', mu_red))

        mult = multiplicity
        #for ind in specie_site_index_map:
        #    print(ind[0], ind[1])
        specie_concen = [
            sum(mult[ind[0]:ind[1]]) for ind in specie_site_index_map]
        #print('specie_concen', specie_concen)
        max_host_specie_concen = 1-solute_concen
        host_specie_concen_ratio = [specie_concen[i]/sum(specie_concen)* \
                                    max_host_specie_concen for i in range(m)]
        host_specie_concen_ratio[-1] = solute_concen
        #print('hostspecie_concen_rat', host_specie_concen_ratio)


        y_vect = host_specie_concen_ratio
        #print(('y_vect', y_vect))
        vector_func = [y_vect[i]-c_ratio[i] for i in range(m)]
        vector_func.append(omega)
        #print((vector_func))
        mu_vals = None
        c_val = None
        m_min = -15.0
        if e0 > 0:
            m_max = 10            # Search space needs to be modified
        else:
            m_max = 0
        for m1 in np.arange(m_min,m_max,0.3):
            for m2 in np.arange(m_min,m_max,0.3):
                m0 = mu_red[mu[0]].subs([(mu[1],m1),(mu[2],m2)])
                try:
                    #print(m1,m2)
                    mu_vals = nsolve(vector_func,mu,[m0,m1,m2],module="numpy")
                    #mu_vals = nsolve(vector_func,mu,[m0,m1,m2])
                    # Line needs to be modified to include all mus when n > 2
                except:
                    continue
                break
            if mu_vals:
                mu_vals = [float(mu_val) for mu_val in mu_vals]
                break
        else:
            raise ValueError("Couldn't find mus")
        #print (('mu_vals', mu_vals))
        return mu_vals

    if not trial_chem_pot:
        mu_vals = compute_mus()
    else:
        try:
            mu_vals = [trial_chem_pot[element] for element in specie_order]
        except:
            mu_vals = compute_mus()
    #print(('mu_vals', mu_vals))


    # Compute ymax
    max_host_specie_concen = 1-solute_concen
    mult = multiplicity
    specie_concen = [
            sum(mult[ind[0]:ind[1]]) for ind in specie_site_index_map]
    host_specie_concen_ratio = [specie_concen[i]/sum(specie_concen)* \
                                max_host_specie_concen for i in range(m)]
    host_specie_concen_ratio[-1] = solute_concen
    #print('hostspecie_concen_rat', host_specie_concen_ratio)
    li = specie_site_index_map[0][0]
    hi = specie_site_index_map[0][1]
    comp1_min = sum(multiplicity[li:hi])/sum(multiplicity)* \
                max_host_specie_concen - 0.01
    comp1_max = sum(multiplicity[li:hi])/sum(multiplicity)* \
                max_host_specie_concen + 0.01
    #print(ymin, ymax)
    delta = (comp1_max - comp1_min)/50.0

    #for i in range(len(mu)):
    #    print(mu[i], mu_vals[i])

    # Compile mu's for all composition ratios in the range
    #+/- 1% from the stoichiometry
    result = {}
    for y in np.arange(comp1_min,comp1_max+delta,delta):
        result[y] = []
        y_vect = []
        y_vect.append(y)
        y2 = max_host_specie_concen - y
        y_vect.append(y2)
        y_vect.append(solute_concen)
        #print ('y_vect', y_vect)
        vector_func = [y_vect[i]-c_ratio[i] for i in range(1,m)]
        vector_func.append(omega)
        #try:
        #print (vector_func)
        #print (mu)
        #print (mu_vals)

        x = nsolve(vector_func,mu,mu_vals,module="numpy")
        #x = nsolve(vector_func,mu,mu_vals)
        #except:
        #    del result[y]
        #    continue

        result[y].append(x[0])
        result[y].append(x[1])
        result[y].append(x[2])


    res = []

    #print ('result', result.keys())
    # Compute the concentrations for all the compositions
    for key in sorted(result.keys()):
        mu_val = result[key]
        total_c_val = [total_c[i].subs(dict(zip(mu,mu_val))) \
                for i in range(len(total_c))]
        c_val = c.subs(dict(zip(mu,mu_val)))
        #print ('c_val', c_val)
        # Concentration of first element/over total concen
        res1 = []
        res1.append(float(total_c_val[0]/sum(total_c_val)))

        sum_c0 = sum([c0[i,i] for i in range(n)])
        #print ('c_val_n_0', c_val[n,0])
        #print ('c_val_n_1', c_val[n,1])
        for i in range(n+1):
            for j in range(n):
                if i == j:              # Vacancy
                    #res1.append(float((c0[i,i]-sum(c_val[:,i]))/c0[i,i]))
                    vac_conc = float(exp(-(mu_val[site_mu_map[i]]+dE[i,i])/(k_B*T)))
                    res1.append(vac_conc)
                else:                   # Antisite
                    res1.append(float(c_val[i,j]/c0[j,j]))
        res.append(res1)

    #print ('c0', c0)
    #print ('res', res)
    res = np.array(res)
    #print ('res', res)
    dtype = [(str('x'),np.float64)]+[(str('y%d%d' % (i, j)), np.float64) \
            for i in range(n+1) for j in range(n)]
    res1 = np.sort(res.view(dtype),order=[str('x')],axis=0)

    conc = []
    for i in range(n+1):
        conc.append([])
        for j in range(n):
            conc[i].append([])
    #print(conc)
    for i in range(n+1): # Append vacancies
        for j in range(n):
            y1 = [dat[0][i*n+j+1] for dat in res1]
            conc[i][j] = y1
    #print(type(conc[i][j]))

    plot_data = {}
    """Because all the plots have identical x-points storing it in a
    single array"""
    #for dat in res1:
    #    print dat
    plot_data['x'] = [dat[0][0] for dat in res1]         # x-axis data
    # Element whose composition is varied. For x-label
    plot_data['x_label'] = els[0]+ "_mole_fraction"
    plot_data['y_label'] = "Fraction of {} at {} sites".format(
        solute_specie,els[0])

    y_data = []
    #for i in range(n):      # Vacancy plots
    inds = specie_site_index_map[m-1]
    #print ('inds', inds)
    data1 = np.sum([conc[ind][0] for ind in range(*inds)],axis=0)
    #print ('data1', data1)
    data2 = np.sum([conc[ind][1] for ind in range(*inds)],axis=0)
    #print ('data2', data2)
    frac_data = data1/(data1+data2)
    #print ('frac_data', frac_data)
    frac_data = frac_data.tolist()
    y_data.append({'data':frac_data})

    plot_data['y'] = y_data

    return plot_data
Ejemplo n.º 46
0
def dilute_solution_model(structure, e0, vac_defs, antisite_defs, T,
        trial_chem_pot = None, generate='plot'):

    """
    Compute the defect densities using dilute solution model.

    Args:
        structure: pymatgen.core.structure.Structure object representing the
            primitive or unitcell of the crystal.
        e0: The total energy of the undefected system.
            This is E0 from VASP calculation.
        vac_defs: List of vacancy defect parameters in the dictionary format.
            The keys of the dict associated with each vacancy defect are
            1) site_index, 2) site_specie, 3) site_multiplicity, and
            4) energy. 1-3 can be obtained from
            pymatgen.analysis.defects.point_defects.Vacancy class.
            Site index is expected to start with 1 (fortran index).
        antisite_defs: List of antisite defect parameters in the dictionary
            format. The keys of the dict associated with each antisite defect
            are 1) site_index, 2) site_specie, 3) site_multiplicity,
            4) substitution_specie, and 5) energy. 1-3 can be obtained
            from pymatgen.analysis.defects.point_defects.Vacancy class.
        T: Temperature in Kelvin
        trial_chem_pot (optional): Trial chemical potentials to speedup
            the plot generation. Format is {el1:mu1,...}
        generate (string): Options are plot or energy
            Chemical potentials are also returned with energy option.
            If energy option is not chosen, plot is generated.

    Returns:
        If generate=plot, the plot data is generated and returned in
        HighCharts format.
        If generate=energy, defect formation enthalpies and chemical
        potentials are returned.
    """

    if not check_input(vac_defs):
        raise ValueError('Vacancy energy is not defined')
    if not check_input(antisite_defs):
        raise ValueError('Antisite energy is not defined')

    formation_energies = {}
    formation_energies['vacancies'] = copy.deepcopy(vac_defs)
    formation_energies['antisites'] = copy.deepcopy(antisite_defs)
    for vac in formation_energies['vacancies']:
        del vac['energy']
    for asite in formation_energies['antisites']:
        del asite['energy']
    # Setup the system
    site_species = [vac_def['site_specie'] for vac_def in vac_defs]
    multiplicity = [vac_def['site_multiplicity'] for vac_def in vac_defs]
    m = len(set(site_species))      # distinct species
    n = len(vac_defs)           # inequivalent sites

    # Reduce the system and associated parameters such that only distinctive
    # atoms are retained
    comm_div = gcd(*tuple(multiplicity))
    multiplicity = [val/comm_div for val in multiplicity]
    e0 = e0/comm_div
    T = Integer(T)

    c0 = np.diag(multiplicity)
    #print ('c0',c0)
    mu = [Symbol('mu'+i.__str__()) for i in range(m)]

    # Generate maps for hashing
    # Generate specie->mu map and use it for site->mu map
    specie_order = []       # Contains hash for site->mu map    Eg: [Al, Ni]
    site_specie_set = set()             # Eg: {Ni, Al}
    for i in range(n):
        site_specie  = site_species[i]
        if site_specie not in site_specie_set:
            site_specie_set.add(site_specie)
            specie_order.append(site_specie)
    site_mu_map = []     # Eg: [mu0,mu0,mu0,mu1] where mu0->Al, and mu1->Ni
    for i in range(n):
        site_specie  = site_species[i]
        j = specie_order.index(site_specie)
        site_mu_map.append(j)
    specie_site_index_map = []      # Eg: [(0,3),(3,4)] for Al & Ni
    for i in range(m):
        low_ind = site_species.index(specie_order[i])
        if i < m-1:
            hgh_ind = site_species.index(specie_order[i+1])
        else:
            hgh_ind = n
        specie_site_index_map.append((low_ind,hgh_ind))


    """
    dC: delta concentration matrix:
    dC[i,j,k]: Concentration change of atom i, due to presence of atom
    j on lattice site k
    Special case is [i,i,i] which is considered as vacancy
    Few cases: dC[i,i,i] = -1 due to being vacancy special case
                dC[k,k,i] = +1 due to increment in k at i lattice if i
                               lattice type is of different element
                dC[i,k,i] = -1 due to decrement of ith type atom due to
                presence of kth type atom on ith sublattice and kth type
                atom specie is different from ith sublattice atom specie
                dC[i,k,k] = 0 due to no effect on ith type atom
                dC[i,j,k] = 0 if i!=j!=k
    """
    dC = np.zeros((n,n,n), dtype=np.int)
    for i in range(n):
        for j in range(n):
            for k in range(n):
                if i == j and site_species[j] != site_species[k] and \
                                site_species[i] != site_species[k]:
                    dC[i,j,k] = 1
        for j in range(n):
            for k in range(n):
                if i == k:
                    #if j == k or site_species[j] != site_species[k]:
                        dC[i,j,k] = -1
    for k in range(n):
        for j in range(n):
            for i in range(n):
                if i != j:
                    if site_species[j] == site_species[k]:
                        dC[i,j,k] = 0
        #for j in range(n):
        #    if k != j:
        #        for i in range(n):
        #            if i == j:
        #                if abs(i-j) <= 1 and abs(j-k) <= 1 and abs(i-k) <= 1:
        #                    dC[i,j,k] = 0

    for ind_map in specie_site_index_map:
        if ind_map[1]-ind_map[0] > 1:
            for index1 in range(ind_map[0]+1,ind_map[1]):
                for index2 in range(ind_map[0]):
                    for i in range(n):
                        #print (i, index1, index2)
                        dC[i,index1,index2] = 0
                for index2 in range(ind_map[1],n):
                    for i in range(n):
                        #print (i, index1, index2)
                        dC[i,index1,index2] = 0


    #print ('dC', dC)
    # dE matrix: Flip energies (or raw defect energies)
    els = [vac_def['site_specie'] for vac_def in vac_defs]
    dE = []
    for i in range(n):
        dE.append([])
    for i in range(n):
        for j in range(n):
            dE[i].append(0)

    for j in range(n):
        for i in range(n):
            if i == j:
                dE[i][j] = vac_defs[i]['energy']
            else:
                sub_specie = vac_defs[i]['site_specie']
                site_specie = vac_defs[j]['site_specie']
                if site_specie == sub_specie:
                    dE[i][j] = 0
                else:
                    for as_def in antisite_defs:
                        if int(as_def['site_index']) == j+1 and \
                                sub_specie == as_def['substitution_specie']:
                            dE[i][j] = as_def['energy']
                            break
    dE = np.array(dE)
    #np.where(dE is None, dE, 0)
    #print ('dE', dE)

    # Initialization for concentrations
    # c(i,p) == presence of ith type atom on pth type site
    c = Matrix(n,n,[0]*n**2)
    for i in range(n):
        for p in range(n):
            c[i,p] = Integer(c0[i,p])
            site_flip_contribs = []
            for epi in range(n):
                sum_mu = sum([mu[site_mu_map[j]]*Integer(dC[j,epi,p]) \
                        for j in range(n)])
                #print (i, epi, p, dC[i,epi, p], sum_mu)
                #c[i,p] += Integer(multiplicity[p]*dC[i,epi,p]) * \
                #        exp(-(dE[epi,p]-sum_mu)/(k_B*T))
                flip = Integer(multiplicity[p]*dC[i,epi,p]) * \
                        exp(-(dE[epi,p]-sum_mu)/(k_B*T))
                if flip not in site_flip_contribs:
                    site_flip_contribs.append(flip)
                    c[i,p] += flip
                #else:
                    #print (i, epi, p)
                    #print ('flip already present in site_flips')

    #print ('c', c)
    total_c = []
    for ind in specie_site_index_map:
        total_c.append(sum([sum(c[i,:]) for i in range(*ind)]))
    c_ratio = [total_c[-1]/total_c[i] for i in range(m)]
    #print ('c_ratio')
    #for i in range(len(c_ratio)):
    #    print(c_ratio[i])

    # Expression for Omega, the Grand Potential
    omega = e0 - sum([mu[site_mu_map[i]]*sum(c0[i,:]) for i in range(n)])
    for p_r in range(n):
        for epi in range(n):
            sum_mu = sum([mu[site_mu_map[j]]*Float(
                    dC[j,epi,p_r]) for j in range(n)])
            omega -= k_B*T*multiplicity[p_r]*exp(-(dE[epi,p_r]-sum_mu)/(k_B*T))

    def compute_mus():

        def reduce_mu():
            omega = [e0 - sum([mu[site_mu_map[i]]*sum(c0[i,:]) for i in range(n)])]
            x = solve(omega)
            return x

        # Compute trial mu
        mu_red = reduce_mu()

        mult = multiplicity
        specie_concen = [sum(mult[ind[0]:ind[1]]) for ind in specie_site_index_map]
        y_vect = [specie_concen[-1]/specie_concen[i] for i in range(m)]
        vector_func = [y_vect[i]-c_ratio[i] for i in range(m-1)]
        vector_func.append(omega)
        min_diff = 1e10
        mu_vals = None
        c_val = None
        m1_min = -20.0
        if e0 > 0:
            m1_max = 10            # Search space needs to be modified
        else:
            m1_max = 0
        for m1 in np.arange(m1_min,m1_max,0.1):
            m0 = mu_red[mu[0]].subs(mu[-1],m1)

            try:
                x = nsolve(vector_func,mu,[m0,m1],module="numpy")
            except:
                continue

            c_val = c.subs(dict(zip(mu,x)))
            #if all(x >= 0 for x in c_val):
            specie_concen = []
            for ind in specie_site_index_map:
                specie_concen.append(sum([sum(c_val[i,:]) for i in range(*ind)]))
            y_comp = [specie_concen[-1]/specie_concen[i] for i in range(m)]
            diff = math.sqrt(sum([pow(abs(y_comp[i]-y_vect[i]),2) for i in range(m)]))
            if diff < min_diff:
                min_diff = diff
                mu_vals = x

        if mu_vals:
            mu_vals = [float(mu_val) for mu_val in mu_vals]
        else:
            raise ValueError()
        return mu_vals

    def compute_def_formation_energies():
        i = 0
        for vac_def in vac_defs:
            site_specie = vac_def['site_specie']
            ind = specie_order.index(site_specie)
            uncor_energy = vac_def['energy']
            formation_energy = uncor_energy + mu_vals[ind]
            formation_energies['vacancies'][i]['formation_energy'] = formation_energy
            specie_ind = site_mu_map[i]
            indices = specie_site_index_map[specie_ind]
            specie_ind_del = indices[1]-indices[0]
            cur_ind = i - indices[0] + 1
            if not specie_ind_del-1:
                label = '$V_{'+site_specie+'}$'
            else:
                label = '$V_{'+site_specie+'_'+str(cur_ind)+'}$'
            formation_energies['vacancies'][i]['label'] = label
            i += 1
        i = 0
        for as_def in antisite_defs:
            site_specie = as_def['site_specie']
            sub_specie = as_def['substitution_specie']
            ind1 = specie_order.index(site_specie)
            ind2 = specie_order.index(sub_specie)
            uncor_energy = as_def['energy']
            formation_energy = uncor_energy + mu_vals[ind1] - mu_vals[ind2]
            formation_energies['antisites'][i]['formation_energy'] = formation_energy
            specie_ind = site_mu_map[i]
            indices = specie_site_index_map[specie_ind]
            specie_ind_del = indices[1]-indices[0]
            cur_ind = i - indices[0] + 1
            if not specie_ind_del-1:
                label = '$'+sub_specie+'_{'+site_specie+'}$'
            else:
                label = '$'+sub_specie+'_{'+site_specie+'_'+str(cur_ind)+'}$'
            formation_energies['antisites'][i]['label'] = label
            i += 1
        return formation_energies

    if not trial_chem_pot:
        mu_vals = compute_mus()
    else:
        try:
            mu_vals = [trial_chem_pot[element] for element in specie_order]
        except:
            mu_vals = compute_mus()


    if generate == 'energy':
        formation_energies = compute_def_formation_energies()
        mu_dict = dict(zip(specie_order,mu_vals))
        return formation_energies, mu_dict

    #sys.exit()

    # Compute ymax
    li = specie_site_index_map[0][0]
    hi = specie_site_index_map[0][1]
    comp1_min = int(sum(multiplicity[li:hi])/sum(multiplicity)*100)-1
    comp1_max = int(sum(multiplicity[li:hi])/sum(multiplicity)*100)+1
    delta = float(comp1_max-comp1_min)/120.0
    yvals = []
    for comp1 in np.arange(comp1_min,comp1_max+delta,delta):
        comp2 = 100-comp1
        y = comp2/comp1
        yvals.append(y)
    #ymin = comp2_min/comp1_max
    #print comp1_min, comp1_max
    #print comp2_min, comp2_max
    #print ymax, ymin

    # Compile mu's for all composition ratios in the range
    #+/- 1% from the stoichiometry
    result = {}
    #for y in np.arange(ymin,ymax+delta,delta):
    for y in yvals:
        result[y] = []
        vector_func = [y-c_ratio[0]]
        vector_func.append(omega)
        x = nsolve(vector_func,mu,mu_vals,module="numpy")
        result[y].append(x[0])
        result[y].append(x[1])

    res = []
    new_mu_dict = {}
    # Compute the concentrations for all the compositions
    for key in sorted(result.keys()):
        mu_val = result[key]
        total_c_val = [total_c[i].subs(dict(zip(mu,mu_val))) \
                for i in range(len(total_c))]
        c_val = c.subs(dict(zip(mu,mu_val)))
        res1 = []
        # Concentration of first element/over total concen
        res1.append(float(total_c_val[0]/sum(total_c_val)))
        new_mu_dict[res1[0]] = mu_val
        sum_c0 = sum([c0[i,i] for i in range(n)])
        #print res1[0]
        for i in range(n):
            for j in range(n):
                if i == j:              # Vacancy
                    #print (i,  c_val[:,i])
                    # Consider numerical accuracy
                    #res1.append(float((c0[i,i]-sum(c_val[:,i]))/c0[i,i]))
                    #print ((mu_val[site_mu_map[i]]-dE[i,i])/(k_B*T))
                    vac_conc = float(exp(-(mu_val[site_mu_map[i]]+dE[i,i])/(k_B*T)))
                    #print vac_conc
                    res1.append(vac_conc)
                else:                   # Antisite
                    res1.append(float(c_val[i,j]/c0[j,j]))
        res.append(res1)

    res = np.array(res)
    dtype = [(str('x'),np.float64)]+[(str('y%d%d' % (i, j)), np.float64) \
            for i in range(n) for j in range(n)]
    res1 = np.sort(res.view(dtype), order=[str('x')],axis=0)


    conc_data = {}
    """Because all the plots have identical x-points storing it in a
    single array"""
    conc_data['x'] = [dat[0][0] for dat in res1]         # x-axis data
    # Element whose composition is varied. For x-label
    conc_data['x_label'] = els[0]+ " mole fraction"
    conc_data['y_label'] = "Point defect concentration"
    conc = []
    for i in range(n):
        conc.append([])
        for j in range(n):
            conc[i].append([])
    for i in range(n): 
        for j in range(n):
            y1 = [dat[0][i*n+j+1] for dat in res1]
            conc[i][j] = y1

    y_data = []
    for i in range(n):      
        data = conc[i][i]
        specie = els[i]
        specie_ind = site_mu_map[i]
        indices = specie_site_index_map[specie_ind]
        specie_ind_del = indices[1]-indices[0]
        cur_ind = i - indices[0] + 1
        #if 'V' not in els:
        #    vac_string = "$V_{"
        #else:
        vac_string = "$Vac_{"
        if not specie_ind_del-1:
            label = vac_string+specie+'}$'
        else:
            label = vac_string+specie+'_'+str(cur_ind)+'}$'
        # Plot data and legend info
        y_data.append({'data':data,'name':label})

    for i in range(n):      
        site_specie = els[i]
        specie_ind = site_mu_map[i]
        indices = specie_site_index_map[specie_ind]
        specie_ind_del = indices[1]-indices[0]
        cur_ind = i - indices[0] + 1
        for j in range(m):          # Antisite plot dat
            sub_specie = specie_order[j]
            if sub_specie == site_specie:
                continue
            if not specie_ind_del-1:
                label = '$'+sub_specie+'_{'+site_specie+'}$'
            else:
                label = '$'+sub_specie+'_{'+site_specie+'_'+str(cur_ind)+'}$'
            inds = specie_site_index_map[j]
            data = np.sum([conc[ind][i] for ind in range(*inds)],axis=0)
            data = data.tolist()
            y_data.append({'data':data,'name':label})

    conc_data['y'] = y_data

    # Compute the  formation energies
    def compute_vac_formation_energies(mu_vals):
        en = []
        for vac_def in vac_defs:
            site_specie = vac_def['site_specie']
            ind = specie_order.index(site_specie)
            uncor_energy = vac_def['energy']
            formation_energy = uncor_energy + mu_vals[ind]
            en.append(float(formation_energy))
        return en
    en_res = []
    for key in sorted(new_mu_dict.keys()):
        mu_val = new_mu_dict[key]
        en_res.append(compute_vac_formation_energies(mu_val))

    en_data = {'x_label':els[0]+' mole fraction', 'x':[]}
    en_data['x'] = [dat[0][0] for dat in res1]         # x-axis data

    i = 0
    y_data = []
    for vac_def in vac_defs:
        data = [data[i] for data in en_res]
        site_specie = vac_def['site_specie']
        ind = specie_order.index(site_specie)
        specie_ind = site_mu_map[i]
        indices = specie_site_index_map[specie_ind]
        specie_ind_del = indices[1]-indices[0]
        cur_ind = i - indices[0] + 1
        vac_string = "$Vac_{"
        if not specie_ind_del-1:
            label = vac_string+site_specie+'}$'
        else:
            label = vac_string+site_specie+'_'+str(cur_ind)+'}$'
        y_data.append({'data':data,'name':label})
        i += 1

    def compute_as_formation_energies(mu_vals):
        en = []
        for as_def in antisite_defs:
            site_specie = as_def['site_specie']
            sub_specie = as_def['substitution_specie']
            ind1 = specie_order.index(site_specie)
            ind2 = specie_order.index(sub_specie)
            uncor_energy = as_def['energy']
            form_en = uncor_energy + mu_vals[ind1] - mu_vals[ind2]
            en.append(form_en)
        return en
    en_res = []
    for key in sorted(new_mu_dict.keys()):
        mu_val = new_mu_dict[key]
        en_res.append(compute_as_formation_energies(mu_val))
    i = 0
    for as_def in antisite_defs:
        data = [data[i] for data in en_res]
        site_specie = as_def['site_specie']
        sub_specie = as_def['substitution_specie']
        ind1 = specie_order.index(site_specie)
        ind2 = specie_order.index(sub_specie)
        specie_ind = site_mu_map[i]
        indices = specie_site_index_map[specie_ind]
        specie_ind_del = indices[1]-indices[0]
        cur_ind = i - indices[0] + 1
        if not specie_ind_del-1:
            label = '$'+sub_specie+'_{'+site_specie+'}$'
        else:
            label = '$'+sub_specie+'_{'+site_specie+'_'+str(cur_ind)+'}$'
        y_data.append({'data':data,'name':label})
        i += 1

    en_data['y'] = y_data

    # Return chem potential as well
    mu_data = {'x_label':els[0]+' mole fraction', 'x':[]}
    mu_data['x'] = [dat[0][0] for dat in res1]         # x-axis data

    y_data = []
    for j in range(m):
        specie = specie_order[j]
        mus = [new_mu_dict[key][j] for key in sorted(new_mu_dict.keys())]
        y_data.append({'data':mus, 'name':specie})
    mu_data['y'] = y_data

    return conc_data, en_data, mu_data
Ejemplo n.º 47
0
def _solve_A(A, **kwargs):
    r"""
    Centrifugal corrected equivalent moment
    =======================================
    
    Convert beam loading into a single equivalent bending moment. Note that
    this is dependent on the location in the cross section. Due to the 
    way we measure the strain on the blade and how we did the calibration
    of those sensors.
    
    .. math::

        \epsilon = \frac{M_{x_{equiv}}y}{EI_{xx}} = \frac{M_x y}{EI_{xx}} 
        + \frac{M_y x}{EI_{yy}} + \frac{F_z}{EA}
        
        M_{x_{equiv}} = M_x + \frac{I_{xx}}{I_{yy}} M_y \frac{x}{y}  
        + \frac{I_{xx}}{Ay} F_z
    
    Parameters
    ----------
    
    st_arr : np.ndarray(19)
        Only one line of the st_arr is allowed and it should correspond
        to the correct radial position of the strain gauge.
    
    load : list(6)
        list containing the load time series of following components
        .. math:: load = F_x, F_y, F_z, M_x, M_y, M_z
        and where each component is an ndarray(m)
    
    """

    d = kwargs.get("d", 40.0)
    L = kwargs.get("L", 150.0)
    acc_check = kwargs.get("acc_check", 0.0000001)
    solve_acc = kwargs.get("solve_acc", 20)

    # set the accuracy target of the solver
    sympy.mpmath.mp.dps = solve_acc
    psi = sympy.Symbol("psi")
    f1 = L - (L * sympy.tan(psi)) + (d / (2.0 * sympy.cos(psi))) - A
    # initial guess: solve system for delta_x = 0
    psi0 = math.atan(1 - (A / L))
    # solve the equation numerically with sympy
    psi_sol = sympy.nsolve(f1, psi, psi0)

    # verify if the solution is valid
    delta_x = d / (2.0 * math.cos(psi_sol))
    x = L * math.tan(psi_sol)
    Asym = sympy.Symbol("Asym")
    f_check = x - L + Asym - delta_x

    # verify that f_check == 0
    if not sympy.solvers.checksol(f_check, Asym, A):
        # in the event that it does not pass the checksol, see how close
        # the are manually. Seems they are rather close
        check_A = L + delta_x - x
        error = abs(A - check_A) / A
        if error > acc_check:
            msg = "sympy's solution does not passes checksol()"
            msg += "\n A_check=%.12f <=> A=%.12f" % (check_A, A)
            raise ValueError, msg
        else:
            msg = "sympy.solvers.checksol() failed, manual check is ok. "
            msg += "A=%.2f, rel error=%2.3e" % (A, error)
            logging.warning(msg)

    return psi_sol * 180.0 / math.pi, psi0 * 180.0 / math.pi
Ejemplo n.º 48
0
    def bestEffortFit(self,VV,II):

        #splineTestVV=np.linspace(VV[0],VV[-1],1000)
        #splineTestII=iFitSpline(splineTestVV)
        #p1, = plt.plot(splineTestVV,splineTestII)
        #p3, = plt.plot(VV,II,ls='None',marker='o', label='Data')
        #plt.draw()
        #plt.show()            

        #data point selection:
        #lowest voltage (might be same as Isc)
        V_start_n = VV[0]
        I_start_n = II[0]

        #highest voltage
        V_end_n = VV[-1]
        I_end_n = II[-1]

        #Isc
        iFit = interpolate.interp1d(VV,II)
        V_sc_n = 0
        try:
            I_sc_n = float(iFit(V_sc_n))
        except:
            return([[nan,nan,nan,nan,nan], [nan,nan,nan,nan,nan], nan, "hard fail", 10])

        #mpp
        VVcalc = VV-VV[0]
        IIcalc = II-min(II)
        Pvirtual= np.array(VVcalc*IIcalc)
        vMaxIndex = Pvirtual.argmax()
        V_vmpp_n = VV[vMaxIndex]
        I_vmpp_n = II[vMaxIndex]

        #Vp: half way in voltage between vMpp and the start of the dataset:
        V_vp_n = (V_vmpp_n-V_start_n)/2 +V_start_n
        try:
            I_vp_n = float(iFit(V_vp_n))
        except:
            return([[nan,nan,nan,nan,nan], [nan,nan,nan,nan,nan], nan, "hard fail", 10])

        #Ip: half way in current between vMpp and the end of the dataset:
        I_ip_n = (I_vmpp_n-I_end_n)/2 + I_end_n
        iFit2 = interpolate.interp1d(VV,II-I_ip_n)
        try:
            V_ip_n = optimize.brentq(iFit2, VV[0], VV[-1])
        except:
            return([[nan,nan,nan,nan,nan], [nan,nan,nan,nan,nan], nan, "hard fail", 10])

        diaplayAllGuesses = False
        def evaluateGuessPlot(dataX, dataY, myguess):
            myguess = [float(x) for x in myguess]
            print "myguess:"
            print myguess
            vv=np.linspace(min(dataX),max(dataX),1000)
            ii=vectorizedCurrent(vv,myguess[0],myguess[1],myguess[2],myguess[3],myguess[4])
            plt.title('Guess and raw data')
            plt.plot(vv,ii)
            plt.scatter(dataX,dataY)
            plt.grid(b=True)
            plt.draw()
            plt.show()

        #phase 1 guesses:
        I_L_initial_guess = I_sc_n
        R_sh_initial_guess = 1e6

        #compute intellegent guesses for Iph, Rsh by forcing the curve through several data points and numerically solving the resulting system of eqns
        newRhs = rhs - I
        aLine = Rsh*V+Iph-I
        eqnSys1 = aLine.subs([(V,V_start_n),(I,I_start_n)])
        eqnSys2 = aLine.subs([(V,V_vp_n),(I,I_vp_n)])

        eqnSys = (eqnSys1,eqnSys2)

        try:
            nGuessSln = sympy.nsolve(eqnSys,(Iph,Rsh),(I_L_initial_guess,R_sh_initial_guess),maxsteps=10000)
        except:
            return([[nan,nan,nan,nan,nan], [nan,nan,nan,nan,nan], nan, "hard fail", 10])


        I_L_guess = nGuessSln[0]
        R_sh_guess = -1*1/nGuessSln[1]
        R_s_guess = -1*(V_end_n-V_ip_n)/(I_end_n-I_ip_n)
        n_initial_guess = 2 #TODO: maybe a more intelegant guess for n can be found using http://pvcdrom.pveducation.org/CHARACT/IDEALITY.HTM
        I0_initial_guess = eyeNot[0].evalf(subs={Vth:thermalVoltage,Rs:R_s_guess,Rsh:R_sh_guess,Iph:I_L_guess,n:n_initial_guess,I:I_ip_n,V:V_ip_n})                         

        initial_guess = [I0_initial_guess, I_L_guess, R_s_guess, R_sh_guess, n_initial_guess]
        if diaplayAllGuesses:
            evaluateGuessPlot(VV, II, initial_guess)
            
        # let's try the fit now, if it works great, we're done, otherwise we can continue
        #try:
            #guess = initial_guess
            #fitParams, fitCovariance, infodict, errmsg, ier = optimize.curve_fit(optimizeThis, VV, II,p0=guess,full_output = True,xtol=1e-13,ftol=1e-15)
            #return(fitParams, fitCovariance, infodict, errmsg, ier)
        #except:
            #pass        

        #refine guesses for I0 and Rs by forcing the curve through several data points and numerically solving the resulting system of eqns
        eqnSys1 = newRhs.subs([(Vth,thermalVoltage),(Iph,I_L_guess),(V,V_ip_n),(I,I_ip_n),(n,n_initial_guess),(Rsh,R_sh_guess)])
        eqnSys2 = newRhs.subs([(Vth,thermalVoltage),(Iph,I_L_guess),(V,V_end_n),(I,I_end_n),(n,n_initial_guess),(Rsh,R_sh_guess)])
        eqnSys = (eqnSys1,eqnSys2)
        
        try:
            nGuessSln = sympy.nsolve(eqnSys,(I0,Rs),(I0_initial_guess,R_s_guess),maxsteps=10000)
        except:
            return([[nan,nan,nan,nan,nan], [nan,nan,nan,nan,nan], nan, "hard fail", 10])

        I0_guess = nGuessSln[0]
        R_s_guess = nGuessSln[1]
        
        #Rs_initial_guess = RsEqn[0].evalf(subs={I0:I0_initial_guess,Vth:thermalVoltage,Rsh:R_sh_guess,Iph:I_L_guess,n:n_initial_guess,I:I_end_n,V:V_end_n})
        #I0_guess = I0_initial_guess
        #R_s_guess = Rs_initial_guess
        
        guess = [I0_guess, I_L_guess, R_s_guess, R_sh_guess, n_initial_guess]
        if diaplayAllGuesses:
            evaluateGuessPlot(VV, II, guess)
            
        #nidf

        #give 5x weight to data around mpp
        #nP = II*VV
        #maxIndex = np.argmax(nP)
        #weights = np.ones(len(II))
        #halfRange = (V_ip_n-VV[vMaxIndex])/2
        #upperTarget = VV[vMaxIndex] + halfRange
        #lowerTarget = VV[vMaxIndex] - halfRange
        #lowerTarget = 0
        #upperTarget = V_oc_n
        #lowerI = np.argmin(abs(VV-lowerTarget))
        #upperI = np.argmin(abs(VV-upperTarget))
        #weights[range(lowerI,upperI)] = 3
        #weights[maxnpi] = 10
        #todo: play with setting up "key points"

        guess = [float(x) for x in guess]

        #odrMod = odr.Model(odrThing)
        #myData = odr.Data(VV,II)
        #myodr = odr.ODR(myData, odrMod, beta0=guess,maxit=5000,sstol=1e-20,partol=1e-20)#
        #myoutput = myodr.run()
        #myoutput.pprint()
        #see http://docs.scipy.org/doc/external/odrpack_guide.pdf


        try:
            #myoutput = myodr.run()
            #fitParams = myoutput.beta
            #print myoutput.stopreason
            #print myoutput.info
            #ier = 1
            fitParams, fitCovariance, infodict, errmsg, ier = optimize.curve_fit(optimizeThis, VV, II,p0=guess,full_output = True,xtol=1e-13,ftol=1e-15)
            #fitParams, fitCovariance, infodict, errmsg, ier = optimize.leastsq(func=residual, args=(VV, II, np.ones(len(II))),x0=guess,full_output=1,xtol=1e-12,ftol=1e-14)#,xtol=1e-12,ftol=1e-14,maxfev=12000
            #fitParams, fitCovariance, infodict, errmsg, ier = optimize.leastsq(func=residual, args=(VV, II, weights),x0=fitParams,full_output=1,ftol=1e-15,xtol=0)#,xtol=1e-12,ftol=1e-14            
        
            alwaysShowRecap = False
            if  alwaysShowRecap:
                vv=np.linspace(VV[0],VV[-1],1000)
                print "fit:"
                print fitParams                
                print "guess:"
                print guess
                print ier
                print errmsg
                ii=vectorizedCurrent(vv,guess[0],guess[1],guess[2],guess[3],guess[4])
                ii2=vectorizedCurrent(vv,fitParams[0],fitParams[1],fitParams[2],fitParams[3],fitParams[4])
                plt.title('Fit analysis')
                p1, = plt.plot(vv,ii, label='Guess',ls='--')
                p2, = plt.plot(vv,ii2, label='Fit')
                p3, = plt.plot(VV,II,ls='None',marker='o', label='Data')
                #p4, = plt.plot(VV[range(lowerI,upperI)],II[range(lowerI,upperI)],ls="None",marker='o', label='5x Weight Data')
                ax = plt.gca()
                handles, labels = ax.get_legend_handles_labels()
                ax.legend(handles, labels, loc=3)
                plt.grid(b=True)
                plt.draw()
                plt.show()
            return(fitParams, fitCovariance, infodict, errmsg, ier)
        except:
            return([[nan,nan,nan,nan,nan], [nan,nan,nan,nan,nan], nan, "hard fail", 10])
Ejemplo n.º 49
0
#def make_dictionary(max_length=10, **entries):
#    return dict([(key, entries[key]) for i, key in enumerate(entries.keys()) if i < max_length])

# my guess for the fit parameters
# [I0, I_L, R_s, R_sh, n]
guess = [7.974383037191594e-11, 0.00627619846736794, 12.743239329693433, 5694.842341863068, 2.0]
#guess = {'I0': 1e-15, 'Iph': 8.6889261535882785, 'Rs': 0.5155903798902628, 'Rsh': 788.22883822837741, 'n': 40.0}
#guess = [guess['I0'],guess['Iph'],guess['Rs'],guess['Rsh'],guess['n']]


eqnSys1 = newRhs.subs([(Vth,thermalVoltage),(Iph,I_L_guess),(V,V_ip_n),(I,I_ip_n),(n,n_initial_guess),(Rsh,R_sh_guess)])
eqnSys2 = newRhs.subs([(Vth,thermalVoltage),(Iph,I_L_guess),(V,V_end_n),(I,I_end_n),(n,n_initial_guess),(Rsh,R_sh_guess)])
eqnSys = (eqnSys1,eqnSys2)

try:
    nGuessSln = sympy.nsolve(eqnSys,(I0,Rs),(I0_initial_guess,R_s_guess),maxsteps=10000)
except:
    return([[nan,nan,nan,nan,nan], [nan,nan,nan,nan,nan], nan, "hard fail", 10])

I0_guess = nGuessSln[0]
R_s_guess = nGuessSln[1]

#guess = [np.complex128(x) for x in guess]

# bounds on parameters
I0_bounds = [0, inf]
I_L_bounds = [0, inf]
R_s_bounds = [0, inf]
R_sh_bounds = [0, inf]
n_bounds = [0, 40]
myBounds=([I0_bounds[0], I_L_bounds[0], R_s_bounds[0], R_sh_bounds[0], n_bounds[0]], [I0_bounds[1], I_L_bounds[1], R_s_bounds[1], R_sh_bounds[1], n_bounds[1]])
Ejemplo n.º 50
0
#
#     return F




# log(pdc) + thetam + log(abs(1- 2 * exp(-TIm/t1c) / (1 + exp(-(TIm + TD + tau)/t1c)) )) = log(msc)
# zguess = np.array([800,1200,800])
# z = fsolve(myFunction,zguess)

thetam, TIm, TD  = sp.symbols('thetam, TIm, TD')
tau = 2600
efc = sp.log(pdc) + thetam + sp.log((1 - 2*sp.exp(-TIm/t1c)/(1 + sp.exp(-(TIm + TD + tau)/t1c)))) - sp.log(msc) - sp.log(100)
efg = sp.log(pdg) + thetam + sp.log((1 - 2*sp.exp(-TIm/t1g)/(1 + sp.exp(-(TIm + TD + tau)/t1g)))) - sp.log(msg)- sp.log(100)
efw = sp.log(pdw) + thetam + sp.log((1 - 2*sp.exp(-TIm/t1w)/(1 + sp.exp(-(TIm + TD + tau)/t1w)))) - sp.log(msw)- sp.log(100)
sol = sp.nsolve((efc, efg, efw),(thetam, TIm,TD), (800,1900,800))

thetamh = float(sol[0])
TImh = float(sol[1])
TDh = float(sol[2])

# read atlas betaspace
betaspace_filename = '/home/amod/mimecs/IPMI2013_BetaspaceRegression/code/msAtlas_hybrid_pd_t1_mprage_t2_true_betaspace.csv'
ms_atlas_betaspace = np.genfromtxt(betaspace_filename, delimiter=',')

atlas_pd = np.array(ms_atlas_betaspace[:,0].tolist(),dtype=np.float32)
atlas_t1 = np.array(ms_atlas_betaspace[:,1].tolist(),dtype=np.float32)
atlas_t2 = np.array(ms_atlas_betaspace[:,2].tolist(),dtype=np.float32)

synth_ms_atlas_fg = np.exp(np.log(atlas_pd) + thetamh + np.log(1 - 2*np.exp(-TImh/atlas_t1)/(1 + np.exp(-(TImh + TDh + tau)/atlas_t1)))- np.log(100))
Ejemplo n.º 51
0
delta_theta = 0.1
theta1 = theta0 + delta_theta * 1
theta2 = theta0 + delta_theta * 2
theta3 = theta0 + delta_theta * 3
s1 = s(theta1, P)
s2 = s(theta2, P)
s3 = s(theta3, P)

from sympy import Symbol, nsolve #@UnresolvedImport
import sympy #@UnusedImport @UnresolvedImport
from sympy import sin, cos #@UnresolvedImport

r = Symbol('r')
beta = Symbol('beta')
d0 = Symbol('d0')
d1 = Symbol('d1')
d2 = Symbol('d2')
d3 = Symbol('d3')



fx1 = r + cos(beta - s0) * d0 - (cos(theta1) * r + cos(theta1 + beta - s1) * d1)
fy1 = 0 + sin(beta - s0) * d0 - (sin(theta1) * r + sin(theta1 + beta - s1) * d1)
fx2 = r + cos(beta - s0) * d0 - (cos(theta2) * r + cos(theta2 + beta - s2) * d2)
fy2 = 0 + sin(beta - s0) * d0 - (sin(theta2) * r + sin(theta2 + beta - s2) * d2)
fx3 = r + cos(beta - s0) * d0 - (cos(theta3) * r + cos(theta3 + beta - s3) * d3)
fy3 = 0 + sin(beta - s0) * d0 - (sin(theta3) * r + sin(theta3 + beta - s3) * d3) 

print nsolve((fx1, fx2, fx3, fy1, fy2, fy3), (r, beta, d0, d1, d2, d3), (3.1, 0.1, 5, 5, 5, 5))
pdb.set_trace()
#torque_answers_dict = solve(subbed_equations, [l_hip_torque, r_hip_torque])
#solved_dict = solve(subbed_value_equations, [l_hip_torque, r_hip_torque, theta1])

forcing_matrix = kane.forcing

forcing_matrix = simplify(forcing_matrix)

forcing_matrix = simplify(forcing_matrix.subs(zero_speed_dict).subs(parameter_dict).subs(torque_dict))

answer_vector = []
lhiptorque = []
rhiptorque = []
threshold = 0.1
x = -120
y = -120

while (x < 120):
  x = x + 5
  y = -120
  while (y < 120):
    solution_matrix = forcing_matrix.subs(dict(zip([l_hip_torque, r_hip_torque], [x,y])))
    solution_dict = solve(solution_matrix, (sin(theta1 + theta2), sin(theta1 + theta2 + theta3), sin(theta1)))
    f1 = solution_dict[sin(theta1 + theta2)] - sin(theta1+theta2)
    f2 = solution_dict[sin(theta1 + theta2 + theta3)] - sin(theta1 + theta2 + theta3)
    f3 = solution_dict[sin(theta1)] - sin(theta1)
    answer_vector.append(nsolve((f1,f2,f3), (theta1, theta2, theta3), (0,0,0)))
    rhiptorque.append(y)
    lhiptorque.append(x)
    y = y + 5
Ejemplo n.º 53
0
wss = Symbol("wss")
Tss = Symbol("Tss")
kss = Symbol("kss")

# -----------------------------------------------------------------#
# ------------------Variables/Equations----------------------------#
# -----------------------------------------------------------------#
f1 = Css - (1.0 - tao) * (wss * lss + (rss - delta) * kss) - Tss
f2 = 1.0 - beta * ((rss - delta) * (1.0 - tao) + 1)
f3 = (a / ((1.0 - lss) ** xsi)) - ((1.0 / Css ** gamma) * wss * (1.0 - tao))
f4 = rss - ((alpha) * (kss ** (alpha - 1.0)) * (lss ** (1.0 - alpha)))
f5 = wss - ((1.0 - alpha) * (kss ** alpha) * (lss ** (-alpha)))
f6 = Tss - (tao * (wss * lss + (rss - delta) * kss))

# use nsolve to solve for values#
SOLSS = nsolve((f1, f2, f3, f4, f5, f6), (Css, rss, lss, wss, Tss, kss), (0.75, 0.12, 0.55, 1.32, 0.041, 4.05))

cs = float(SOLSS[0])
rs = float(SOLSS[1])
ls = float(SOLSS[2])
ws = float(SOLSS[3])
Ts = float(SOLSS[4])
ks = float(SOLSS[5])

solVec = sp.array([[ks, ls], [ks, ls], [ks, ls], [zbar], [zbar]])

theta0 = np.mat([ks, ls, ks, ls, ks, ls, zbar, zbar])

# define vars t_1 = t-1
ct, ct1 = symbols("ct, ct1")
rt, rt1 = symbols("rt, rt1")
Ejemplo n.º 54
0
# We now find the predicted y values so we can find the residuals.
Y_hat = np.dot(X.T, Beta.T).T
resid = no_lag - Y_hat
sigma = np.cov(resid)  # This is the sigma we will use to find A_0 inverse.
print sigma

## Solving for A_0_inv
# Applying short run restrictions means that A_0 inv. will have no (1,2) entry.
# We will be left with sigma = [[a11**2, 0], [a11*a22, a21**2 + a22**2]]
# We solve this equation symbolically below.
a11, a21, a22 = symbols(["a11", "a21", "a22"])
f1 = a11 ** 2 - sigma[0, 0]
f2 = a11 * a21 - sigma[1, 0]
f3 = a21 ** 2 + a22 ** 2 - sigma[1, 1]
AoInvSol = nsolve((f1, f2, f3), (a11, a21, a22), (0.5, -0.5, 0.5))
A_0_inv = sp.matrix([[0.0, 0.0], [0.0, 0.0]])
A_0_inv[0, 0] = AoInvSol[0]
A_0_inv[1, 0] = AoInvSol[1]
A_0_inv[1, 1] = AoInvSol[2]
print A_0_inv
A_0 = npla.inv(A_0_inv)

## Solving for D matricies
# Stack betas for easy D creation
bet = Beta[:, 1:]
B1, B2, B3, B4, B5, B6, B7, B8 = [
    np.mat(bet[:, 0:2]),
    np.mat(bet[:, 2:4]),
    np.mat(bet[:, 4:6]),
    np.mat(bet[:, 6:8]),
Ejemplo n.º 55
0
    def linearize(self, x_o, u_o):
        if x_o.lines != self.x.lines:
            raise Exception, "Different line size"

        if x_o.cols != self.x.cols:
            raise Exception, "Different line size"

        if u_o.lines != self.u.lines:
            raise Exception, "Different line size"

        if u_o.cols != self.u.cols:
            raise Exception, "Different line size"


        A = self.fun_f.jacobian(self.x)
        B = self.fun_f.jacobian(self.u)
        C = self.fun_h.jacobian(self.x)
        
        for fun in self.functions:
            for args in fun[3]:
                for i in xrange(len(args)):

                    f = fun[1]
                    g = fun[2]
                    y = var("y")
                    F = (
                        g(y,*args) - f(y,*args)).diff(args[i]) / (
                        f(y,*args) - g(y,*args)).diff(y)

                    F = F.subs(y, fun[0](*args))
                    sub = {fun[0](*args).diff(args[i]): F}

                    A = A.subs(sub)
                    B = B.subs(sub)
                    C = C.subs(sub)


        num = True


        for fun in self.functions:
            for args in fun[3]:

                sub = dict(map(
                        lambda i: (self.x[i],x_o[i]),
                        xrange(self.x.lines * self.x.cols))
                           + map(
                        lambda i: (self.u[i],u_o[i]),
                        xrange(self.u.lines * self.u.cols)))

                args_o = map(lambda x: x.subs(sub),args)

                num = True
                for arg in args_o:
                    num &= arg.is_number

                if num:
                                        
                    y = var("y")
                    y = nsolve(
                        fun[1](y,*args_o)- fun[2](y,*args_o),
                        0.7)

                    A = A.subs(fun[0](*args), y)
                    B = B.subs(fun[0](*args), y)
                    C = C.subs(fun[0](*args), y)


        sub = dict(map(
                lambda i: (self.x[i],x_o[i]),
                xrange(self.x.lines * self.x.cols))
                   + map(
                lambda i: (self.u[i],u_o[i]),
                xrange(self.u.lines * self.u.cols)))
        
        A = A.subs(sub).evalf()
        B = B.subs(sub).evalf()
        C = C.subs(sub).evalf()

        return  (A,B,C)
Ejemplo n.º 56
0
#Use differentionation to solve convex minimization problem from earlier
f=(sy.sin(x)+.05*x**2+sy.sin(y)+.05*y**2)

#Get partial derivatives in terms of x and y

del_x=sy.diff(f,x)
del_x
#0.1*x + cos(x)

del_y=sy.diff(f,y)
del_y
#0.1*y + cos(y)

#using educated guess we can achieve results similar to global minimum,local minimum method
x0=sy.nsolve(del_x,-1.5)
y0=sy.nsolve(del_y,-1.5)

print x0, y0
#-1.42755177876459 -1.42755177876459
f.subs({x:x0,y:y0}).evalf()
#-1.77572565314742

#Without having the best guess estimates may prove inaccruate due to only finding a local minimum
x0=sy.nsolve(del_x,1.5)
y0=sy.nsolve(del_y,1.5)

print x0, y0
#1.74632928225285 1.74632928225285
f.subs({x:x0,y:y0}).evalf()
#2.27423381055640
Ejemplo n.º 57
0
resid = no_lag - Y_hat
sigma = np.cov(resid) # This is the sigma we will use to find A_0 inverse.


## Solve for D(1) and then C(1)
# Solve for D(1)
B_1 = np.eye(2) - B1 - B2 - B3 - B4 - B5 - B6 - B7 - B8
D_1 = npla.inv(B_1)

#Solve symbolically for C_1
c11, c21, c22 = symbols(['c1', 'c2', 'c3'])
C_12 =  np.dot(np.dot(D_1, sigma),D_1.T)
g1 = c11**2 - C_12[0,0]
g2 = c11*c21 - C_12[1,0]
g3 = c21**2 + c22**2 - C_12[1,1]
c_1_sol =  nsolve((g1,g2,g3),(c11,c21,c22),(-.03,.113,-.3))
C_1 = np.empty([2,2])
C_1[0,0] = c_1_sol[0]
C_1[1,0] = c_1_sol[1]
C_1[1,1] = c_1_sol[2]


## Compute A_0_inv and A_0
A_0_inv = np.dot(npla.inv(D_1), C_1)
A_0 = npla.inv(A_0_inv)

## Create D matricies
D0 = np.mat(np.eye(n_vars))
D1 = B1*D0
D2 = B1*D1 + B2*D0
D3 = B1*D2 + B2*D1 + B3*D0