Beispiel #1
0
def func(param, return_oofunvalue=False):
    
    num = len(param["Substrate"])
    
    p, s = oovars(2, size = num)
    
    equations = [
                 (0==-param["Protein"]+(ones(num)+param['k1']*s)*p)(tol=tolerence),
                 (0==-param['Substrate']+(ones(num)+param['k1']*p)*s)(tol=tolerence),
                 ]
    
    startpoint = {p:param["Protein"], s:param['Substrate']}
    
    system = SNLE(equations, startpoint, iprint = -100)
    
    
    if local_constrained:
        # Slow but works when not close
        system.constraints = [
                      p > zeros(num), s > zeros(num),
                      p < param['Protein'], s < param['Substrate']
                      ]
        solutions = system.solve('nssolve')
    else:
        # Fast and good if close
        solutions = system.solve('scipy_fsolve')
    
    
    P, S = p(solutions), s(solutions)
    
    return param['s']*(param['k1'])*P*S/param['Substrate']
Beispiel #2
0
def calcScatteringPlaneTilt (h1, h2, UBmatrix, wavelength,stars):
   "Calculates the chi and phi for the scattering plane defined by h1 and h2. Used with calcIdealAngles2."
   #Accepts two scattering plane vectors, h1 and h2, the UB matrix, and the wavelength
   h1p = N.dot(UBmatrix, h1)
   h2p = N.dot(UBmatrix, h2)
   
   x0 = [0.0, 0.0, 0.0, 0.0]
   
   q = calcq (h1[0], h1[1], h1[2], stars)
   twotheta1 = 2.0 * N.arcsin(wavelength * q / 4.0 / N.pi)
   q = calcq (h2[0], h2[1], h2[2], stars)
   twotheta2 = 2.0 * N.arcsin(wavelength * q / 4.0 / N.pi)
   s1='before NLSP\n'
   genout(s1)
   p0 = SNLE(scatteringEquationsTilt, x0, args=(h1p, h2p, wavelength, twotheta1, twotheta2))
   s1=s1+'after NLSP\n'
   genout(s1)
   p0.xtol=1e-8
   p0.ftol=1e-8   
   r0 = p0.solve('nlp:ralg')
   s1=s1+'after solve\n'
   genout(s1)
   upper = N.degrees(r0.xf[0]) #xf is the final array, xf[0] = chi
   lower = N.degrees(r0.xf[1]) #                       xf[1] = phi
   
   return lower,upper
    def calcIdealAngles(self, desiredh, chi, phi, UBmatrix, stars, ubcalc):
        "Calculates the twotheta, theta, and omega values for a desired h vector. Uses chi and phi from calcScatteringPlane."
        #Accepts the desired h vector, chi, phi, the UB matrix, the wavelength, and the stars dictionary

        desiredhp = np.dot(UBmatrix, desiredh[0:3])

        #Old code (scipy.optimize.fsolve) produced inaccurate results with far-off estimates
        #solutions = scipy.optimize.fsolve(equations, x0, args=(h1p, h2p, wavelength))

        q = calcq(desiredh[0], desiredh[1], desiredh[2], stars)

        #twotheta = 2.0 * np.arcsin(wavelength * q / 4.0 / np.pi)

        ei = desiredh[3]
        ef = desiredh[4]
        #q=calc_q_inelastic(ei,ef,desiredh[0],desiredh[1],desiredh[2])
        twotheta = calc_tth_inelastic(ei, ef, q)

        x0 = [0.0]
        p = SNLE(self.secondequations,
                 x0,
                 args=(desiredhp, chi, phi, ei, twotheta, ubcalc))
        r = p.solve('nlp:ralg')
        omega = r.xf[0]
        #theta = twotheta/2.0 + omega   # ------ ALTERNATE SOLUTION FOR THETA ------

        #theta=calc_th_inelastic(ei,ef,np.radians(twotheta))

        theta = twotheta / 2.0 + omega

        #theta = r.xf[1]  # ------ SOLVER POTENTIALLY INACCURATE FOR THETA ------

        solutions = [twotheta, theta, omega]
        return solutions  #% 360
Beispiel #4
0
def func(param, return_oofunvalue=False):
    #print traits
    #ImportOld.calltimes += 1
    #print x
    #print "I have been called: " + str(ImportOld.calltimes) + " times"
    num = len(param["x"])

    p = oovar(size=num)
    d = oovar(size=num)

    equations = [
        (0 == -param["x"] + (ones(num) + param['k1'] * d) * p)(tol=1e-8),
        (0 == -param['NCPconc'] + (ones(num) + param['k1'] * p) * d)(tol=1e-8)
    ]

    startpoint = {p: param['x'], d: param['NCPconc']}

    system = SNLE(equations, startpoint, iprint=10)

    if Data.constrained:
        # Slow but works when not close
        system.constraints = [
            p > zeros(num), d > zeros(num), p < param['x'],
            d < param['NCPconc']
        ]

        solutions = system.solve('nssolve')
    else:
        # Fast and good if close
        solutions = system.solve('scipy_fsolve')

    P, D = p(solutions), d(solutions)

    return param['s'] * (
        param['k1']) * P * D / param['NCPconc'] + param['offset']
    def calcIdealAngles(self,desiredh, chi, phi, UBmatrix, stars,ubcalc):
        "Calculates the twotheta, theta, and omega values for a desired h vector. Uses chi and phi from calcScatteringPlane."
        #Accepts the desired h vector, chi, phi, the UB matrix, the wavelength, and the stars dictionary

        desiredhp = np.dot(UBmatrix, desiredh[0:3])

        #Old code (scipy.optimize.fsolve) produced inaccurate results with far-off estimates
        #solutions = scipy.optimize.fsolve(equations, x0, args=(h1p, h2p, wavelength)) 

        q = calcq (desiredh[0], desiredh[1], desiredh[2], stars)

        #twotheta = 2.0 * np.arcsin(wavelength * q / 4.0 / np.pi)

        ei=desiredh[3]
        ef=desiredh[4]
        #q=calc_q_inelastic(ei,ef,desiredh[0],desiredh[1],desiredh[2])
        twotheta=calc_tth_inelastic(ei,ef,q)

        x0 = [0.0]
        p = SNLE(self.secondequations, x0, args=(desiredhp, chi, phi, ei, twotheta,ubcalc))
        r = p.solve('nlp:ralg')
        omega = r.xf[0]
        #theta = twotheta/2.0 + omega   # ------ ALTERNATE SOLUTION FOR THETA ------

        #theta=calc_th_inelastic(ei,ef,np.radians(twotheta))

        theta=twotheta/2.0+omega

        #theta = r.xf[1]  # ------ SOLVER POTENTIALLY INACCURATE FOR THETA ------


        solutions = [twotheta, theta, omega]
        return solutions #% 360
def solve_gamma_3D(gammas): #y={eta_fixed, mu_fixed, nu_fixed}
	gamma_array = []
	sol_1_array = []
	sol_2_array = []
	sol_3_array = []
	sol_4_array = []

	eta, mu, nu = oovars(3)
	start_point = {eta:3.0, mu:0.7, nu:0.20}

	for gamma in gammas:
		# gamma = gamma.tolist()
		global alpha, beta, tau_l, tau_k, Lambda, delta, A, N, phi_k, phi_l, theta

		# Set equations
		L = N * (mu * (1-mu/2) + theta * (1-mu))
		
		f_1 = -nu - delta + N * mu * beta / (1 + beta) * ((1 - tau_l) * (1 - mu / 2) * (1 - alpha) * A * L**(-alpha) *eta ** (alpha - 1) - gamma)

		f_2 = mu * phi_k * alpha * (1-alpha)*A* L**(1-alpha) *eta**alpha / (alpha*A*L**(1-alpha)*eta**(alpha-1) + N*mu*gamma) + (1-mu)*phi_l* (tau_l*(1-alpha)**2*A*L**(-alpha)*eta**alpha + tau_k*alpha*(1-alpha)*A*L**(1-alpha)*eta**alpha-1) / (tau_l*(1-alpha)*A*L**(-alpha)*eta**(alpha-1) + tau_k*(alpha*A*L**(1-alpha)*eta**(alpha-1)+N*mu*gamma)-eta**(-1))

		c_yk = 1/(1+beta) * ( (1-tau_l)* (1-mu)* (1-alpha)* A* eta**(alpha-1)* L**(-alpha) - gamma)

		c_ok = beta * (1-tau_k) * (1+alpha*A*eta**(alpha-1)*L**(1-alpha) - delta) / (1+beta) * ( (1-tau_l)* (1-mu)* (1-alpha)* A* eta**(alpha-1)* L**(-alpha) - gamma)

		c_yl = (1-tau_l)* theta * (1-alpha)* A* eta**(alpha-1)* L**(-alpha)

		c_ol = 1/(N*(1-mu)) * (tau_l*(1-alpha)*A*eta**(alpha-1)*L**(1-alpha) + tau_k* (alpha*A*eta**(alpha-1)*L**(1-alpha) +N*mu*gamma) - eta**(-1))

		U_k = c_yk * c_ok**beta
		U_l = c_yl * c_ol**beta

		f3 = U_k-U_l

		equations = (f_1 == 0, f_2 == 0, f3 == 0)

		p = SNLE(equations, start_point)

		cons_1 = Lambda * A * eta ** alpha + tau_k * mu * gamma * eta - 1
		cons_2 = eta - ((1 - alpha) * A) ** (-1 / alpha)
		cons_3 = (1 - tau_l) * (1 - mu) * (1 - alpha) * A * eta ** (alpha - 1) - gamma
		p.constraints = [0 < mu, mu < 1,  cons_1 > 0, cons_2 > 0, cons_3 >=0, nu>0]

		r = p.solve('nssolve')
		sol_1, sol_2, sol_3 = r(eta, mu, nu)
		sol_4 = N * (sol_2 * (1-sol_2/2) + theta * (1-sol_2))
	
		print('Solution: eta=%f,   mu=%f, nu=%f, L=%f' % (sol_1, sol_2, sol_3, sol_4))
		if r.stopcase>0:
			gamma_array.append(gamma)
			sol_1_array.append(sol_1)
			sol_2_array.append(sol_2)
			sol_3_array.append(sol_3)
			sol_4_array.append(sol_4)				

	return gamma_array, sol_1_array, sol_2_array, sol_3_array, sol_4_array
    def calcScatteringPlane(self, h1, h2, UBmatrix, ei, stars):
        "Returns the chi and phi for the scattering plane defined by h1 and h2. Used with calcIdealAngles2."
        #Accepts two scattering plane vectors, h1 and h2, the UB matrix, and the wavelength
        #Should we allow the scattering plane to be defined by two vectors at different energies?
        #For now, I say NoN

        h1p = np.dot(UBmatrix, h1)
        h2p = np.dot(UBmatrix, h2)

        x0 = [0.0, 0.0, 0.0, 0.0]
        wavelength = e_to_wavelength(ei)
        q1 = calcq(h1[0], h1[1], h1[2], stars)
        twotheta1 = np.degrees(2.0 * np.arcsin(wavelength * q1 / 4.0 / np.pi))
        q2 = calcq(h2[0], h2[1], h2[2], stars)
        twotheta2 = np.degrees(2.0 * np.arcsin(wavelength * q2 / 4.0 / np.pi))

        if 1:
            #original openopt
            #outp=self.scatteringEquations([45,90,-90,0],h1p, h2p, q1, q2,wavelength,twotheta1/2,twotheta2/2)
            p0 = SNLE(self.scatteringEquations,
                      x0,
                      args=(h1p, h2p, q1, q2),
                      contol=1e-15,
                      ftol=1e-15,
                      maxFunEvals=1e8,
                      maxIter=1e5)
            r0 = p0.solve('nlp:ralg')
            #outp=self.scatteringEquations(r0.xf,h1p, h2p, q1, q2,wavelength,twotheta1/2,twotheta2/2)

            chi = r0.xf[0]  #xf is the final array, xf[0] = chi
            phi = r0.xf[1]  #                       xf[1] = phi
        if 0:
            import bumps
            from bumps.fitters import FIT_OPTIONS, FitDriver, DreamFit, StepMonitor, ConsoleMonitor
            import bumps.modelfn, bumps.fitproblem
            fn = lambda chi, phi, omega1, omega2: np.linalg.norm(
                self.scatteringEquations([chi, phi, omega1, omega2], h1p, h2p,
                                         q1, q2))
            print fn(chi=45, phi=72.4, omega1=-90, omega2=0)
            M = bumps.modelfn.ModelFunction(fn,
                                            chi=0.0,
                                            phi=0.0,
                                            omega1=0.0,
                                            omega2=0.0)
            M._parameters['chi'].range(30, 60.)
            M._parameters['phi'].range(0, 90.)
            M._parameters['omega1'].range(-90, 90.)
            M._parameters['omega2'].range(-90, 90.)
            problem = bumps.fitproblem.FitProblem(M)
            fitdriver = FitDriver(DreamFit, problem=problem, burn=1000)
            best, fbest = fitdriver.fit()
            print best, fbest
            print 'done'

        print 'chi, phi', chi, phi
        return chi, phi
def solve_eqn_np(theta, gamma, N): #y={eta_fixed, mu_fixed, nu_fixed}

	nu, eta, mu, = oovars(3)
	# start_point = {nu:0.08, eta:4, mu:0.8}		
	# start_point = {nu:0.2, eta:3.4, mu:0.55}	#Cololado
	# start_point = {nu:0.15, eta:2.5, mu:0.55} # Alabama not feasible
	start_point = {nu:0.2, eta:2.5, mu:0.55}

	global alpha, beta, tau_l, tau_k, Lambda, delta, A

	L = N*(mu*(1-mu/2)+(1-mu)*theta)

	f_1 = -nu - delta + N * mu * beta / (1 + beta) * ((1 - tau_l) * (1 - mu / 2) * (1 - alpha) * A * L**(-alpha) *eta ** (alpha - 1) - gamma)

	Log = log(((1-tau_l)*(1-mu)*(1-alpha)*A*L**(-alpha)*eta**(alpha-1) -gamma)/ ((1-tau_l)*(1-alpha)*A*L**(-alpha)*eta**(alpha-1)) -gamma)

	dV_yk = (1-alpha)*mu*eta - gamma/((1-tau_l)*A*L**(-alpha)*eta**(alpha-2))*Log
	dV_yl =  (1-mu)*(1-alpha)*eta
	dV_ok = beta* mu * alpha * (1-alpha)*A* L**(1-alpha) *eta**alpha / (alpha*A*L**(1-alpha)*eta**(alpha-1) + N*mu*gamma) 
	dV_ol = beta * (1-mu)* (tau_l*(1-alpha)**2*A*L**(-alpha)*eta**alpha + tau_k*alpha*(1-alpha)*A*L**(1-alpha)*eta**alpha-1) / (tau_l*(1-alpha)*A*L**(-alpha)*eta**(alpha-1) + tau_k*(alpha*A*L**(1-alpha)*eta**(alpha-1)+N*mu*gamma)-eta**(-1))

	f_2 = dV_yk + dV_yl + dV_ok + dV_ol

	c_yk = 1/(1+beta) * ( (1-tau_l)* (1-mu)* (1-alpha)* A* eta**(alpha-1)* L**(-alpha) - gamma)

	c_ok = beta * (1-tau_k) * (1+alpha*A*eta**(alpha-1)*L**(1-alpha) - delta) / (1+beta) * ( (1-tau_l)* (1-mu)* (1-alpha)* A* eta**(alpha-1)* L**(-alpha) - gamma)

	c_yl = (1-tau_l)* theta * (1-alpha)* A* eta**(alpha-1)* L**(-alpha)

	c_ol = 1/(N*(1-mu)) * (tau_l*(1-alpha)*A*eta**(alpha-1)*L**(1-alpha) + tau_k* (alpha*A*eta**(alpha-1)*L**(1-alpha) +N*mu*gamma) - eta**(-1))

	U_k = c_yk * c_ok**beta
	U_l = c_yl * c_ol**beta

	f_3 = U_k-U_l

	equations = (f_1 == 0, f_2 == 0, f_3==0)

	p = SNLE(equations, start_point)

	# cons_1 = Lambda * A * eta ** alpha + tau_k * mu * gamma * eta - 1
	# cons_2 = eta - ((1 - alpha) * A) ** (-1 / alpha)
	cons_3 = (1 - tau_l) * (1 - mu) * (1 - alpha) * A * eta ** (alpha - 1) - gamma
	
	p.constraints = [nu>0, eta>0,  0< mu, mu < 1, cons_3 >0]
	# cons_1>=0, cons_2 >=0,
	r = p.solve('nssolve')

	nu_s, eta_s, mu_s = r(nu, eta, mu)
	print('Solution: x1=%f,   x2=%f, x3=%f'  %(nu_s, eta_s, mu_s))

	L = N*(mu_s*(1-mu_s/2)+(1-mu_s)*theta)
	Y_K_ratio = A*eta_s**(alpha-1)*L**(1-alpha)

	return nu_s, Y_K_ratio, eta_s, mu_s, L
def func(param, return_oofunvalue=False, snle_style=False):
    #print traits
    #ImportOld.calltimes += 1
    #print x
    #print "I have been called: " + str(ImportOld.calltimes) + " times"
    num = len(param["x"])

    p = oovar(size=num)
    print param
    #    equations = [
    #                 (0.0 == param["x"] - p * (ones(num) + param['k1'] * s * (ones(num) + 2.0 * param['k2'] * p)))(tol=1e-12),
    #                 (0.0 == param["Substrate"] - s * (ones(num) + param['k1'] * p * (ones(num) + param['k2'] * p)))(tol=1e-12),
    #                 ]

    # m == k2/k1
    #
    s = param["N"]
    equations = [
        (0.0 == param['od'] * param["x"] - p *
         (ones(num) + param['k1'] * s *
          (ones(num) + 2.0 * param['k1'] * param['m'] * p)))(tol=1e-12)
    ]

    #startpoint = {p:param['x']/2.0, s:param['Substrate']/2.0}
    startpoint = {p: param['x']}
    #startpoint = {p:zeros(num), s:zeros(num)}

    system = SNLE(equations, startpoint, iprint=1000)

    if Data.local_constrained:
        # Slow but works when not close
        constraints = [
            p > zeros(num), s > zeros(num), p < param['x'],
            s < param['Substrate'], p > param['x'] - 2 * param['Substrate']
        ]
        system.constraints = constraints
        #solutions = system.solve('interalg')

    if Data.local_constrained:
        solutions = system.solve('nssolve')

    else:
        # Fast and good if close
        solutions = system.solve('scipy_fsolve')

    P = p(solutions)
    print "Protein:"
    print P

    return s * (ones(num) + param['k1'] * P *
                (ones(num) + param['k1'] * param['m'] * P)) / param['od']
def solve_eqn(nu, eta, phi_k, phi_l, tau_k, tau_l): #y={eta_fixed, mu_fixed, nu_fixed}

	theta, mu, gamma = oovars(3)
	start_point = {theta:0.5, mu:0.8, gamma:0.2}	

	global alpha, beta, delta, A
	Lambda = alpha * tau_k + (1 - alpha) * tau_l

	# Set equations
	L = 1
	N = L / (mu*(1-mu/2)+(1-mu)*theta)

	f_1 = -nu - delta + N * mu * beta / (1 + beta) * ((1 - tau_l) * (1 - mu / 2) * (1 - alpha) * A * L**(-alpha) *eta ** (alpha - 1) - gamma)

	f_2 = mu * phi_k * alpha * (1-alpha)*A* L**(1-alpha) *eta**alpha / (alpha*A*L**(1-alpha)*eta**(alpha-1) + N*mu*gamma) + (1-mu)*phi_l* (tau_l*(1-alpha)**2*A*L**(-alpha)*eta**alpha + tau_k*alpha*(1-alpha)*A*L**(1-alpha)*eta**alpha-1) / (tau_l*(1-alpha)*A*L**(-alpha)*eta**(alpha-1) + tau_k*(alpha*A*L**(1-alpha)*eta**(alpha-1)+N*mu*gamma)-eta**(-1))

	c_yk = 1/(1+beta) * ( (1-tau_l)* (1-mu)* (1-alpha)* A* eta**(alpha-1)* L**(-alpha) - gamma)

	c_ok = beta * (1-tau_k) * (1+alpha*A*eta**(alpha-1)*L**(1-alpha) - delta) / (1+beta) * ( (1-tau_l)* (1-mu)* (1-alpha)* A* eta**(alpha-1)* L**(-alpha) - gamma)

	c_yl = (1-tau_l)* theta * (1-alpha)* A* eta**(alpha-1)* L**(-alpha)

	c_ol = 1/(N*(1-mu)) * (tau_l*(1-alpha)*A*eta**(alpha-1)*L**(1-alpha) + tau_k* (alpha*A*eta**(alpha-1)*L**(1-alpha) +N*mu*gamma) - eta**(-1))

	U_k = c_yk * c_ok**beta
	U_l = c_yl * c_ol**beta

	f_3 = U_k-U_l

	equations = (f_1 == 0, f_2 == 0, f_3==0)

	p = SNLE(equations, start_point)

	cons_1 = Lambda * A * eta ** alpha + tau_k * mu * gamma * eta - 1
	cons_2 = eta - ((1 - alpha) * A) ** (-1 / alpha)
	cons_3 = (1 - tau_l) * (1 - mu) * (1 - alpha) * A * eta ** (alpha - 1) - gamma
	
	p.constraints = [0 < mu, mu < 1,  cons_1 > 0, cons_2 > 0, cons_3 >=0, N>1, gamma > 0, theta>0, theta<1 ]

	r = p.solve('nssolve')

	theta_s, mu_s, gamma_s = r(theta, mu, gamma)
	print('Solution: x1=%f,   x2=%f, x3=%f'  %(theta_s, mu_s, gamma_s))

	# theta = ( 1/N - mu_s*( 1 - mu_s/2) )/(1 - mu_s)
	N = 1 / (mu_s*(1-mu_s/2)+(1-mu_s)*theta_s)

	return theta_s, mu_s, gamma_s, N, eta
Beispiel #11
0
    def calcScatteringPlane(self,h1, h2, UBmatrix, ei,stars):
        "Returns the chi and phi for the scattering plane defined by h1 and h2. Used with calcIdealAngles2."
        #Accepts two scattering plane vectors, h1 and h2, the UB matrix, and the wavelength
        #Should we allow the scattering plane to be defined by two vectors at different energies?
        #For now, I say NoN

        h1p = np.dot(UBmatrix, h1)
        h2p = np.dot(UBmatrix, h2)

        x0 = [0.0, 0.0, 0.0, 0.0]
        wavelength=e_to_wavelength(ei)
        q1 = calcq (h1[0], h1[1], h1[2], stars)
        twotheta1 = np.degrees(2.0 * np.arcsin(wavelength * q1 / 4.0 / np.pi))
        q2 = calcq (h2[0], h2[1], h2[2], stars)
        twotheta2 = np.degrees(2.0 * np.arcsin(wavelength * q2 / 4.0 / np.pi))


        if 1:
            #original openopt
            #outp=self.scatteringEquations([45,90,-90,0],h1p, h2p, q1, q2,wavelength,twotheta1/2,twotheta2/2)
            p0 = SNLE(self.scatteringEquations, x0, args=(h1p, h2p, q1, q2),contol=1e-15, ftol=1e-15,maxFunEvals=1e8,maxIter=1e5)
            r0 = p0.solve('nlp:ralg')
            #outp=self.scatteringEquations(r0.xf,h1p, h2p, q1, q2,wavelength,twotheta1/2,twotheta2/2)


            chi = r0.xf[0] #xf is the final array, xf[0] = chi
            phi = r0.xf[1] #                       xf[1] = phi
        if 0:
            import bumps
            from bumps.fitters import FIT_OPTIONS, FitDriver, DreamFit, StepMonitor, ConsoleMonitor
            import bumps.modelfn, bumps.fitproblem
            fn=lambda chi,phi,omega1,omega2: np.linalg.norm(self.scatteringEquations([chi,phi,omega1,omega2], h1p, h2p,q1,q2))
            print fn(chi=45, phi=72.4, omega1=-90, omega2=0)
            M=bumps.modelfn.ModelFunction(fn,chi=0.0,phi=0.0,omega1=0.0,omega2=0.0)
            M._parameters['chi'].range(30,60.)
            M._parameters['phi'].range(0,90.)
            M._parameters['omega1'].range(-90,90.)
            M._parameters['omega2'].range(-90,90.)
            problem=bumps.fitproblem.FitProblem(M)
            fitdriver = FitDriver(DreamFit, problem=problem, burn=1000)
            best, fbest = fitdriver.fit()
            print best,fbest
            print 'done'

        print 'chi, phi', chi, phi
        return chi, phi   
Beispiel #12
0
def func(param, return_oofunvalue=False):
    #print param
    #ImportOld.calltimes += 1
    #print "I have been called: " + str(ImportOld.calltimes) + " times"

    num = len(param["x"])

    p = oovar(size=num)
    d = oovar(size=num)
    n = oovar(size=num)

    equations = [
        (0 == (ones(num) + param['k1'] * d + param['k2'] * n +
               param['k2'] * param['k4'] * d * n) * p -
         exp(param['x']))(tol=1e-8),
        (0 == (ones(num) + param['k1'] * p + param['k2'] * param['k4'] * p * n)
         * d - param['dnaconc'])(tol=1e-8),
        (0 == (ones(num) + param['k2'] * p + param['k2'] * param['k4'] * p * d)
         * n - param['nconc'])(tol=1e-8)
    ]

    startpoint = {p: param['x'], d: param['dnaconc'], n: param['nconc']}

    system = SNLE(equations, startpoint, iprint=-1)

    if Data.constrained:
        # Slow but works when not close
        system.constraints = [
            p > zeros(num), d > zeros(num), n > zeros(num), p < param['x'],
            d < param['dnaconc'], n < param['nconc']
        ]
        solutions = system.solve('nssolve')

    else:
        # Fast and good if close
        solutions = system.solve('scipy_fsolve')

    P, D, N = p(solutions), d(solutions), n(solutions)
    #print "P: " + str(P)
    #print "D: " + str(D)
    #print "N: " + str(N)
    return log(param['s']) + log(
        (1.0 + param['k1'] * param['A'] * param['k2'] * param['k4'] *
         N)) - log(param['k1']) + log(P) + log(D) - log(param['dnaconc'])
Beispiel #13
0
    def calcIdealAngles(self, desiredh, chi, phi, UBmatrix, stars, ubcalc):
        "Calculates the twotheta, theta, and omega values for a desired h vector. Uses chi and phi from calcScatteringPlane."
        #Accepts the desired h vector, chi, phi, the UB matrix, the wavelength, and the stars dictionary

        desiredhp = np.dot(UBmatrix, desiredh[0:3])

        #Old code (scipy.optimize.fsolve) produced inaccurate results with far-off estimates
        #solutions = scipy.optimize.fsolve(equations, x0, args=(h1p, h2p, wavelength))

        q = calcq(desiredh[0], desiredh[1], desiredh[2], stars)

        #twotheta = 2.0 * np.arcsin(wavelength * q / 4.0 / np.pi)

        ei = desiredh[3]
        ef = desiredh[4]
        #q=calc_q_inelastic(ei,ef,desiredh[0],desiredh[1],desiredh[2])
        twotheta = calc_tth_inelastic(ei, ef, q)

        x0 = [0.0]
        p = SNLE(self.secondequations,
                 x0,
                 args=(desiredhp, chi, phi, ei, twotheta, ubcalc))
Beispiel #14
0
    df[1, 0] = 1
    df[1, 1] = -0.5
    df[2, 0] = 1
    df[2, 2] = -sin(x[2])
    return df


x0 = [8, 15, 80]

#w/o gradient:
#p = SNLE(f, x0)

p = SNLE(f,
         x0,
         df=df,
         maxFunEvals=1e5,
         iprint=10,
         plot=1,
         ftol=1e-8,
         contol=1e-15)

#optional: user-supplied gradient check:
#p.checkdf()

#optional: graphical output, requires matplotlib installed
#p.plot = 1

#set some constraints
p.lb, p.ub = [-inf] * 3, [inf] * 3
p.lb[2], p.ub[2] = 145, 150

# you could try also comment/uncomment nonlinear constraints:
Beispiel #15
0
    def calcRefineUB(self, observations, stars_dict):
        #observations are an array of dictionaries for each observed reflection
        #These can be taken at different energies, but should be elastic
        hvectors = []
        Uv = []
        omt = []
        for i in range(0, len(observations)):
            h = np.array([
                observations[i]['h'], observations[i]['k'],
                observations[i]['l']
            ], 'Float64')
            hvectors.append(h)
            '''
            sys.stderr.write('i %3.4f \n'%(observations[i]['h'],))
            sys.stderr.write('i %3.4f \n'%(observations[i]['k'],))
            sys.stderr.write('i %3.4f \n'%(observations[i]['l'],))
            sys.stderr.write('i %3.4f \n'%(observations[i]['twotheta'],))
            sys.stderr.write('i %3.4f \n'%(observations[i]['theta'],))
            sys.stderr.write('i %3.4f \n'%(observations[i]['chi'],))
            sys.stderr.write('i %3.4f \n'%(observations[i]['phi'],))
            '''

            theta = (observations[i]['theta']
                     )  #For us, theta is theta measured (or Lumsden's 's')
            chi = (observations[i]['chi'])
            phi = (observations[i]['phi'])
            twotheta = (observations[i]['twotheta'])
            ei = observations[i]['ei']
            ef = observations[i]['ei']  #reflections are elastic!!!!
            #omega = theta - twotheta/2.0  #diffraction...
            omega = calc_om_elastic(h[0], h[1], h[2], ei, theta, stars_dict)
            #omega=calc_om_inelastic(ei,ef,twotheta)
            u1_phi = self.calc_u_phi(omega, chi, phi)
            u1p, u2p, u3p = u1_phi
            omt.append(omega)
            #u1p = np.cos(omega)*np.cos(chi)*np.cos(phi) - np.sin(omega)*np.sin(phi)
            #u2p = np.cos(omega)*np.cos(chi)*np.sin(phi) + np.sin(omega)*np.cos(phi)
            #u3p = np.cos(omega)*np.sin(chi)

            #reflections are elastic
            q = calc_q_inelastic(ei, ei, twotheta)
            #uv1p=q*u1p
            #uv2p=q*u2p
            #uv3p=q*u3p

            #uv1p = 2.0*np.sin(twotheta/2) / wavelength * u1p
            #uv2p = 2.0*np.sin(twotheta/2) / wavelength * u2p
            #uv3p = 2.0*np.sin(twotheta/2) / wavelength * u3p

            uv1p = (q / (2 * np.pi)) * u1p
            uv2p = (q / (2 * np.pi)) * u2p
            uv3p = (q / (2 * np.pi)) * u3p
            #h1p[0] - (q1/(2*np.pi)) * u1[0]
            Uv.append(uv1p)
            Uv.append(uv2p)
            Uv.append(uv3p)

        x0 = [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]
        p = SNLE(
            self.UBRefinementEquations, x0,
            args=(hvectors,
                  Uv))  #,contol=1e-15, ftol=1e-15,maxFunEvals=1e8,maxIter=1e5)
        r = p.solve('nlp:ralg')

        a = r.xf[0]
        b = r.xf[1]
        c = r.xf[2]
        d = r.xf[3]
        e = r.xf[4]
        f = r.xf[5]
        g = r.xf[6]
        h = r.xf[7]
        j = r.xf[8]

        UB = 2 * np.pi * np.array([[a, b, c], [d, e, f], [g, h, j]], 'Float64')

        return UB
for i in range(n):
    no_a_i = no_a[i]
    Aeq.append([0.] * actagg[i] + [1.] * no_a_i + [0.] *
               (total_no_a - actagg[i] - no_a_i))
    x0 = x0 + [1.0 / no_a_i] * no_a_i
    actagg.append(actagg[i] + no_a_i)


#multiplies the vectors strat and Delta(strat); this product has to be 0 in equilibrium
def product(x):
    strat = []
    for i in range(n):
        strat.append(x[actagg[i]:actagg[i + 1]])
    return np.dot(x, Delta(strat))


p = SNLE(product, x0, lb=lb, ub=ub, Aeq=Aeq, beq=beq)
p.iprint = -1
r = p.solve('nssolve')

if r.stopcase == 1:
    print 'there is an equilibrium in which '
    for i in range(n):
        out = [round(item, 3) for item in r.xf[actagg[i]:actagg[i + 1]]]
        print 'player', i, 'uses the mixed strategy', out
else:
    print 'Error: solver cannot find an equilibrium'

print("--- %s seconds ---" % (time.time() - start_time))
Beispiel #17
0
# Let's solve some parametrized problems
from FuncDesigner import *
from openopt import NLP, SNLE

# let's create parameterized triangle :
a,b,c = oovars(3)
T = Triangle((1,2,a),(2,b,4),(c,6.5,7))

# let's create an initial estimation to the problems below
startValues = {a:1, b:0.5, c:0.1} # you could mere set any, but sometimes a good estimation matters

# let's find an a,b,c values wrt r = 1.5 with required tolerance 10^-5, R = 4.2 and tol 10^-4, a+c == 2.5 wrt tol 10^-7
# if no tol is provided, p.contol is used (default 10^-6)
equations = [(T.r == 1.5)(tol=1e-5) , (T.R == 4.2)(tol=1e-4), (a+c == 2.5)(tol=1e-7)]
prob = SNLE(equations, startValues)
result = prob.solve('nssolve', iprint = 0) # nssolve is name of the solver involved
print('\nsolution has%s been found' % ('' if result.stopcase > 0 else ' not'))
print('values:' + str(result(a, b, c))) # [1.5773327492140974, -1.2582702179532217, 0.92266725078590239]
print('triangle sides: '+str(T.sides(result))) # [8.387574299361475, 7.0470774415247455, 4.1815836020856336]
print('orthocenter of the triangle: ' + str(T.H(result))) # [ 0.90789867  2.15008869  1.15609611]

# let's find minimum inscribed radius subjected to the constraints a<1.5, a>-1, b<0, a+2*c<4,  log(1-b)<2] : 
objective = T.r
prob = NLP(objective, startValues, constraints = [a<1.5, a>-1, b<0, a+2*c<4,  log(1-b)<2])
result1 = prob.minimize('ralg', iprint = 0) # ralg is name of the solver involved, see http://openopt.org/ralg for details
print('\nminimal inscribed radius: %0.3f' % T.r(result1)) #  1.321
print('optimal values:' + str(result1(a, b, c))) # [1.4999968332804028, 2.7938728907900973e-07, 0.62272481283890913]

#let's find minimum outscribed radius subjected to the constraints a<1.5, a>-1, b<0, a+2*c<4,  log(1-b)<2] : 
prob = NLP(T.R, startValues, constraints = (a<1.5, a>-1, b<0, (a+2*c<4)(tol=1e-7),  log(1-b)<2))
Beispiel #18
0
f = (lambda x: x[0]**3 + x[1]**3 - 9, lambda x: x[0] - 0.5 * x[1],
     lambda x: cos(x[2]) + x[0] - 1.5)
# Python list, numpy.array are allowed as well:
#f = lambda x: [x[0]**3+x[1]**3-9, x[0]-0.5*x[1], cos(x[2])+x[0]-1.5]
#or f = lambda x: asfarray((x[0]**3+x[1]**3-9, x[0]-0.5*x[1], cos(x[2])+x[0]-1.5))

# start point
x0 = [8, 15, 80]

#optional: gradient
df = (lambda x: [3 * x[0]**2, 3 * x[1]**2, 0], lambda x: [1, -0.5, 0],
      lambda x: [1, 0, -sin(x[2])])

#w/o gradient:
#p = NLSP(f, x0)
p = SNLE(f, x0, df=df)

#optional: user-supplied gradient check:
#p.checkdf()

#optional: graphical output, requires matplotlib installed
p.plot = 1

p.maxFunEvals = 1e5
p.iprint = 10

#r = p.solve('scipy_fsolve')
#r = p.solve('nssolve')
#or using converter nlsp2nlp, try to minimize sum(f_i(x)^2):
r = p.solve('nlp:ralg', plot=1)
Beispiel #19
0
f = (lambda x: x[0]**3 + x[1]**3 - 9, lambda x: x[0] - 0.5 * x[1],
     lambda x: cos(x[2]) + x[0] - 1.5)
# Python list, numpy.array are allowed as well:
#f = lambda x: [x[0]**3+x[1]**3-9, x[0]-0.5*x[1], cos(x[2])+x[0]-1.5]
#or f = lambda x: asfarray((x[0]**3+x[1]**3-9, x[0]-0.5*x[1], cos(x[2])+x[0]-1.5))

# start point
x0 = [8, 15, 80]

#optional: gradient
df = (lambda x: [3 * x[0]**2, 3 * x[1]**2, 0], lambda x: [1, -0.5, 0],
      lambda x: [1, 0, -sin(x[2])])

#w/o gradient:
#p = SNLE(f, x0)
p = SNLE(f, x0, df=df)

#optional: user-supplied gradient check:
#p.checkdf()

#optional: graphical output, requires matplotlib installed
p.plot = 1

#r = p.solve('scipy_fsolve')
r = p.solve('nssolve')
#or using converter to nlp, try to minimize sum(f_i(x)^2):
#r = p.solve('nlp:ralg')

print('solution: %s' % r.xf)
print('max residual: %e' % r.ff)
###############################
Beispiel #20
0
#f = lambda x: (x[0]**3+x[1]**3-9, x[0]-0.5*x[1], cos(x[2])+x[0]-1.5)
# or:
f = (lambda x: x[0]**3+x[1]**3-9, lambda x: x[0]-0.5*x[1], lambda x: cos(x[2])+x[0]-1.5)
# Python list, numpy.array are allowed as well:
#f = lambda x: [x[0]**3+x[1]**3-9, x[0]-0.5*x[1], cos(x[2])+x[0]-1.5]
#or f = lambda x: asfarray((x[0]**3+x[1]**3-9, x[0]-0.5*x[1], cos(x[2])+x[0]-1.5))

# start point
x0 = [8,15, 80]

#optional: gradient
df = (lambda x: [3*x[0]**2, 3*x[1]**2,  0], lambda x: [1, -0.5,  0], lambda x:[1, 0, -sin(x[2])])

#w/o gradient:
#p = NLSP(f, x0)
p = SNLE(f, x0, df = df)

#optional: user-supplied gradient check:
#p.checkdf()

#optional: graphical output, requires matplotlib installed
p.plot = 1

p.maxFunEvals = 1e5
p.iprint = 10

#r = p.solve('scipy_fsolve')
#r = p.solve('nssolve')
#or using converter nlsp2nlp, try to minimize sum(f_i(x)^2):
r = p.solve('nlp:ralg', plot=1)
##    df[2,2] = cosh(x[2])
##    return df

N = 100
desired_ftol = 1e-6
assert desired_ftol - noise*len(x0) > 1e-7
#w/o gradient:
scipy_fsolve_failed, fs = 0, []
print '----------------------------------'
print 'desired ftol:', desired_ftol, 'objFunc noise:', noise
############################################################################
print '---------- fsolve fails ----------'
t = time()
print 'N log10(MaxResidual) MaxResidual'
for i in xrange(N):
    p = SNLE(f, x0, ftol = desired_ftol - noise*len(x0), iprint = -1, maxFunEvals = int(1e7))
    r = p.solve('scipy_fsolve')
    v = fvn(r.xf)
    fs.append(log10(v))
    if v > desired_ftol:
        scipy_fsolve_failed += 1
        print i+1, '       %0.2f       ' % log10(v), v
    else:
        print i+1, 'OK'
print 'fsolve time elapsed', time()-t
#print 'fsolve_failed number:', scipy_fsolve_failed , '(from', N, '),', 100.0*scipy_fsolve_failed / N, '%'
print 'counters:', count1, count2, count3
############################################################################
count1 = count2 = count3 = 0
t = time()
print '---------- nssolve fails ---------'
Beispiel #22
0
from numpy import arange

x, y, z = oovars(3)

n = 5000

equations = (
    x + 2 * y + 1 == 3 * z,  # n equations

    #x[i] + x[i+1] + y[i] + log(z[i]^2+15) = i+1, i = 0, 1, ..., n-1
    x + hstack(
        (x[1:n], x[0])) + y + log(z**2 + 15) == arange(1,
                                                       n + 1),  # n equations
    z + 2 * x + 5 * y == 100  # n equations
)
# you can use equations with custom tolerances
# equations = (x**3 + y**3 - 9==0, (x - 0.5*y==0)(tol=1e-9), (cos(z) + x == 1.5) (tol=1e-9))
# if no tol is assigned for an equation, p.ftol (default 10^-6) will be used for that one

startPoint = {x: [0] * n, y: [0] * n, z: [0] * n}

p = SNLE(equations, startPoint)

# for some OpenOpt SNLE solvers we can set some constraints
# p.constraints = [z<70,  z>50,  z + sin(x) < 60]

r = p.solve('matlab_fsolve', matlab='/usr/local/MATLAB/R2012a/bin/matlab')
# Notebook Intel Atom 1.6 GHz:
# Solver:   Time Elapsed = 189.23 	(MATLAB preload time ~ 30 sec)
# peak memory consumption for n = 5000 (thus 15000 variables) 160 MB
Beispiel #23
0
#f = lambda x: (x[0]**3+x[1]**3-9, x[0]-0.5*x[1], cos(x[2])+x[0]-1.5)
# or:
f = (lambda x: x[0]**3+x[1]**3-9, lambda x: x[0]-0.5*x[1], lambda x: cos(x[2])+x[0]-1.5)
# Python list, numpy.array are allowed as well:
#f = lambda x: [x[0]**3+x[1]**3-9, x[0]-0.5*x[1], cos(x[2])+x[0]-1.5]
#or f = lambda x: asfarray((x[0]**3+x[1]**3-9, x[0]-0.5*x[1], cos(x[2])+x[0]-1.5))

# start point
x0 = [8,15, 80]

#optional: gradient
df = (lambda x: [3*x[0]**2, 3*x[1]**2,  0], lambda x: [1, -0.5,  0], lambda x:[1, 0, -sin(x[2])])

#w/o gradient:
#p = SNLE(f, x0)
p = SNLE(f, x0, df = df)

#optional: user-supplied gradient check:
#p.checkdf()

#optional: graphical output, requires matplotlib installed
p.plot = 1

#r = p.solve('scipy_fsolve')
r = p.solve('nssolve')
#or using converter to nlp, try to minimize sum(f_i(x)^2):
#r = p.solve('nlp:ralg')

print('solution: %s' % r.xf)
print('max residual: %e' % r.ff)
###############################
Beispiel #24
0
    def datafit(self,
                event,
                paramlinks,
                groups=[],
                ssrresult=None,
                timeresult=None,
                Main=False):
        def errfunc(fit_params,
                    x=None,
                    y=None,
                    yerr=None,
                    consts=None,
                    traits=None,
                    groups=None,
                    snle_style=False):
            fitrun = fitfunc(fit_params,
                             x,
                             consts,
                             traits,
                             groups,
                             return_oofunvalue=True,
                             snle_style=snle_style)
            #print "Fit Params: " + str(fitrun)
            #print "Bad Fit Adjust: " + str(ssr_mod_for_bad_fit[0])
            if snle_style:
                try:
                    if fitrun[0]:
                        fitrun[2].append(0 == ((fitrun[1] - y) /
                                               (array(yerr) + 1.0))**2.0)
                        return [fitrun[2], fitrun[3], fitrun[4]]
                except:
                    if fitrun[0]:
                        fitrun[2].append(0 == ((fitrun[1] - y) /
                                               (array(yerr) + 1.0))**2.0)
                        return [fitrun[2], fitrun[3]]
            else:
                return ((fitrun - y) / (array(yerr) + 1.0))**2.0
            #*(1.0+ssr_mod_for_bad_fit)

        def fitfunc(fit_params,
                    x,
                    consts=None,
                    traits=None,
                    groups=None,
                    return_oofunvalue=False,
                    snle_style=False):
            reload(self.Parent.Parent.model)
            tempparam = OrderedDict()
            k = 0
            m = 0

            templist = list()
            for j in range(len(paramlinks.keys())):
                key = paramlinks.keys()[j]

                if (paramlinks[key][2].IsChecked()):
                    tempparam[key] = fit_params[k]
                    k += 1

                elif (Main == True
                      and self.use_individual_fit_params[key].GetValue()):
                    tempparam[key] = list()
                    for group in groups:
                        tempparam[key].append(
                            list(
                                float(self.individualparamentrylinks[group]
                                      [key][1].GetValue()) *
                                ones(len(Data.currentdata.x(groups=group)))))
                    tempparam[key] = array(sum(tempparam[key], []))
                else:
                    try:
                        tempparam[key] = consts[m]
                        m += 1
                    except:
                        pass

            tempparam["x"] = x
            tempparam.update(traits)
            #print "Fit Params: "+str(fit_params)
            #print "x values: "+str(x)
            #print "consts: "+str(consts)
            #print "traits: "+str(traits)
            #print "Results:" +str(self.Parent.Parent.model.func(x, tempparam, traits))

            return self.Parent.Parent.model.func(
                tempparam,
                return_oofunvalue=return_oofunvalue,
                snle_style=snle_style)

        # Find Current Params
        params = OrderedDict()
        for param in paramlinks.keys():
            params[param] = float(paramlinks[param][1].GetValue())

        # Check for empty groups
        if groups == []:
            return False

        #from scipy.optimize import leastsq
        t = time()

        #results = fitting.solve('nlp:scipy_slsqp', iprint = 1)
        #results = fitting.solve('nlp:lincher', iprint = 1)

        print_level = 10
        # Best so far
        if Data.constrained and Data.snle:
            #fitting = NLLSP(
            p0 = list()
            consts = list()
            ibounds = list()
            sp = OrderedDict()
            # Setup fitted params and consts
            for j in range(len(params.keys())):
                key = params.keys()[j]
                value = params.values()[j]
                if paramlinks[key][2].IsChecked():
                    try:
                        point = oovar(size=len(value))
                    except TypeError:
                        point = oovar()
                    p0.append(point)
                    sp[point] = value
                    ibounds.append(Data.param_upper_bounds[key] > p0[-1] >
                                   Data.param_lower_bounds[key])
                else:
                    consts.append(array(value))
            equations = []
            startpoint = []
            equations = errfunc(p0,
                                y=Data.currentdata.y(groups=groups),
                                yerr=Data.currentdata.yerr(groups=groups),
                                consts=consts,
                                traits=Data.currentdata.traits(groups=groups),
                                x=Data.currentdata.x(groups=groups),
                                groups=groups,
                                snle_style=True)
            startpoint = equations[1]
            startpoint.update(sp)
            print startpoint
            fitting = SNLE(
                equations[0],
                startpoint,
                ftol=1e-10,
            )
            equations[2].extend(ibounds)
            fitting.constraints = equations[2]
            #results = fitting.solve('nlp:ralg', iprint=print_level)
            results = fitting.solve('nssolve', iprint=print_level, maxIter=1e8)

            p1 = results.xf

            for key in p1:
                try:
                    params[key]
                    params[key] = p1[key]
                except:
                    pass

        elif (not Data.constrained) and (not Data.snle):
            p0 = list()
            consts = list()
            ub = list()
            lb = list()
            # Setup fitted params and consts
            for j in range(len(params.keys())):
                key = params.keys()[j]
                value = params.values()[j]
                if paramlinks[key][2].IsChecked():
                    p0.append(array(value))
                    ub.append(Data.param_upper_bounds[key])
                    lb.append(Data.param_lower_bounds[key])
                else:
                    consts.append(array(value))

            equations = partial(
                errfunc,
                y=Data.currentdata.y(groups=groups),
                yerr=Data.currentdata.yerr(groups=groups),
                consts=consts,
                traits=Data.currentdata.traits(groups=groups),
                x=Data.currentdata.x(groups=groups),
                groups=groups,
                snle_style=False,
            )
            fitting = NLP(
                equations,
                p0,
            )
            results = fitting.solve('scipy_leastsq',
                                    iprint=print_level,
                                    maxIter=1e8)
            p1 = results.xf

            i = 0
            for j in range(len(params.keys())):
                key = params.keys()[j]
                if paramlinks[key][2].IsChecked():
                    params[key] = p1[i]
                    i += 1

        elif (Data.constrained) and (not Data.snle):
            p0 = list()
            consts = list()
            ub = list()
            lb = list()
            # Setup fitted params and consts
            for j in range(len(params.keys())):
                key = params.keys()[j]
                value = params.values()[j]
                if paramlinks[key][2].IsChecked():
                    p0.append(array(value))
                    ub.append(Data.param_upper_bounds[key])
                    lb.append(Data.param_lower_bounds[key])
                else:
                    consts.append(array(value))

            fitting = NLP(
                partial(
                    errfunc,
                    y=Data.currentdata.y(groups=groups),
                    yerr=Data.currentdata.yerr(groups=groups),
                    consts=consts,
                    traits=Data.currentdata.traits(groups=groups),
                    x=Data.currentdata.x(groups=groups),
                    groups=groups,
                    snle_style=False,
                ),
                p0,
                ub=ub,
                lb=lb,
                ftol=1e-16,
            )

            results = fitting.solve('ralg', iprint=print_level, maxIter=1e8)
            #results = fitting.solve('nssolve', iprint = print_level, maxIter = 1e8)
            p1 = results.xf

            i = 0
            for j in range(len(params.keys())):
                key = params.keys()[j]
                if paramlinks[key][2].IsChecked():
                    params[key] = p1[i]
                    i += 1

        # Good if close
        #results = fitting.solve('nlp:scipy_cobyla', iprint = 1)

        #print('solution: '+str(results.xf)+'\n||residuals||^2 = '+str(results.ff)+'\nresiduals: ')

        if not Main:
            #print groups
            #print p1
            #print Data.param_individual["3"].keys()
            #print Data.param
            try:
                i = 0
                for key in params.keys():
                    if paramlinks[key][2].IsChecked():
                        Data.param_individual[groups][key] = p1[i]
                        i += 1
            except:
                print "More than one group was passed, when there should have been only one."
            #print Data.param_individual
        """
        Cleanup and redraw
        """

        for key in paramlinks.keys():
            paramlinks[key][1].SetValue(str(params[key]))

        self.Parent.Parent.plotpanel.Update()

        self.xrange = Data.currentdata.x(groups=groups)
        currentfitvalues = fitfunc(
            p1,
            Data.currentdata.x(groups=groups),
            consts=consts,
            traits=Data.currentdata.traits(groups=groups),
            groups=groups)
        #ssr = sum((currentfitvalues - Data.currentdata.y(groups=groups)) ** 2)
        ssr = sum(
            map(lambda x: x**2, currentfitvalues -
                Data.currentdata.y(groups=groups))) / len(currentfitvalues)

        #print "SSR:" + str(ssr)
        Data.param = params

        ssrresult.SetLabel("SSR: " + str(ssr))
        timeresult.SetLabel("Time Elapsed: %f" % (time() - t))

        self.Parent.Parent.plotpanel.Update()
beq = [1.]*n#dito
x0 = []
actagg = [0]

for i in range(n):
    no_a_i = no_a[i]
    Aeq.append([0.]*actagg[i] + [1.]*no_a_i + [0.]*(total_no_a-actagg[i]-no_a_i))
    x0 = x0 + [1.0/no_a_i]*no_a_i
    actagg.append(actagg[i]+no_a_i)

#multiplies the vectors strat and Delta(strat); this product has to be 0 in equilibrium
def product(x):
    strat = []
    for i in range(n):
        strat.append(x[actagg[i]:actagg[i+1]])
    return np.dot(x,Delta(strat))

p = SNLE(product,x0,lb=lb,ub=ub,Aeq=Aeq,beq=beq)
p.iprint = -1
r = p.solve('nssolve')

if r.stopcase==1:
    print 'there is an equilibrium in which '
    for i in range(n):
        out = [round(item,3) for item in r.xf[actagg[i]:actagg[i+1]]]
        print 'player',i,'uses the mixed strategy',out
else:
    print 'Error: solver cannot find an equilibrium'

print("--- %s seconds ---" % (time.time() - start_time))
Beispiel #26
0
    def calcRefineUB(self,observations,stars_dict):
        #observations are an array of dictionaries for each observed reflection
        #These can be taken at different energies, but should be elastic
        hvectors = []
        Uv = []
        omt=[]
        for i in range(0, len(observations)):
            h = np.array([observations[i]['h'], observations[i]['k'], observations[i]['l']],'Float64')
            hvectors.append(h)

            '''
            sys.stderr.write('i %3.4f \n'%(observations[i]['h'],))
            sys.stderr.write('i %3.4f \n'%(observations[i]['k'],))
            sys.stderr.write('i %3.4f \n'%(observations[i]['l'],))
            sys.stderr.write('i %3.4f \n'%(observations[i]['twotheta'],))
            sys.stderr.write('i %3.4f \n'%(observations[i]['theta'],))
            sys.stderr.write('i %3.4f \n'%(observations[i]['chi'],))
            sys.stderr.write('i %3.4f \n'%(observations[i]['phi'],))
            '''

            theta =(observations[i]['theta'])  #For us, theta is theta measured (or Lumsden's 's')
            chi = (observations[i]['chi'])
            phi = (observations[i]['phi'])
            twotheta = (observations[i]['twotheta'])
            ei=observations[i]['ei']
            ef=observations[i]['ei']  #reflections are elastic!!!!
            #omega = theta - twotheta/2.0  #diffraction...
            omega=calc_om_elastic(h[0],h[1],h[2],ei,theta,stars_dict)
            #omega=calc_om_inelastic(ei,ef,twotheta)
            u1_phi=self.calc_u_phi(omega,chi,phi)
            u1p,u2p,u3p=u1_phi
            omt.append(omega)
            #u1p = np.cos(omega)*np.cos(chi)*np.cos(phi) - np.sin(omega)*np.sin(phi)
            #u2p = np.cos(omega)*np.cos(chi)*np.sin(phi) + np.sin(omega)*np.cos(phi)
            #u3p = np.cos(omega)*np.sin(chi)

            #reflections are elastic
            q=calc_q_inelastic(ei,ei,twotheta)
            #uv1p=q*u1p
            #uv2p=q*u2p
            #uv3p=q*u3p

            #uv1p = 2.0*np.sin(twotheta/2) / wavelength * u1p
            #uv2p = 2.0*np.sin(twotheta/2) / wavelength * u2p
            #uv3p = 2.0*np.sin(twotheta/2) / wavelength * u3p

            uv1p=(q/(2*np.pi))*u1p
            uv2p=(q/(2*np.pi))*u2p
            uv3p=(q/(2*np.pi))*u3p
            #h1p[0] - (q1/(2*np.pi)) * u1[0]
            Uv.append(uv1p)
            Uv.append(uv2p)
            Uv.append(uv3p)

        x0 = [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]
        p = SNLE(self.UBRefinementEquations, x0, args=(hvectors, Uv))#,contol=1e-15, ftol=1e-15,maxFunEvals=1e8,maxIter=1e5)
        r = p.solve('nlp:ralg')

        a = r.xf[0]
        b = r.xf[1]
        c = r.xf[2]
        d = r.xf[3]
        e = r.xf[4]
        f = r.xf[5]
        g = r.xf[6]
        h = r.xf[7]
        j = r.xf[8]

        UB = 2*np.pi*np.array([[a, b, c], [d, e, f], [g, h, j]],'Float64')

        return UB    
def df(x):
    df = zeros((3,3))
    df[0,0] = 3*x[0]**2
    df[0,1] = 3*x[1]**2
    df[1,0] = 1
    df[1,1] = -0.5
    df[2,0] = 1
    df[2,2] = -sin(x[2])
    return df

x0 = [8,15, 80]

#w/o gradient:
#p = SNLE(f, x0)

p = SNLE(f, x0, df = df, maxFunEvals = 1e5, iprint = 10, plot=1, ftol = 1e-8, contol=1e-15)

#optional: user-supplied gradient check:
#p.checkdf()

#optional: graphical output, requires matplotlib installed
#p.plot = 1

#set some constraints
p.lb, p.ub = [-inf]*3, [inf]*3
p.lb[2], p.ub[2] = 145, 150

# you could try also comment/uncomment nonlinear constraints:
p.c = lambda x: (x[2] - 146)**2-1.5
# optional: gradient
p.dc = lambda x: asfarray((0, 0, 2*(x[2]-146)))
Beispiel #28
0
N = 100
desired_ftol = 1e-6
assert desired_ftol - noise * len(x0) > 1e-7
#w/o gradient:
scipy_fsolve_failed, fs = 0, []
print '----------------------------------'
print 'desired ftol:', desired_ftol, 'objFunc noise:', noise
############################################################################
print '---------- fsolve fails ----------'
t = time()
print 'N log10(MaxResidual) MaxResidual'
for i in xrange(N):
    p = SNLE(f,
             x0,
             ftol=desired_ftol - noise * len(x0),
             iprint=-1,
             maxFunEvals=int(1e7))
    r = p.solve('scipy_fsolve')
    v = fvn(r.xf)
    fs.append(log10(v))
    if v > desired_ftol:
        scipy_fsolve_failed += 1
        print i + 1, '       %0.2f       ' % log10(v), v
    else:
        print i + 1, 'OK'
print 'fsolve time elapsed', time() - t
#print 'fsolve_failed number:', scipy_fsolve_failed , '(from', N, '),', 100.0*scipy_fsolve_failed / N, '%'
print 'counters:', count1, count2, count3
############################################################################
count1 = count2 = count3 = 0
Beispiel #29
0
from numpy import arange

x, y, z = oovars(3)

n = 5000

equations = (
             x + 2* y + 1 == 3*z,  # n equations
             
             #x[i] + x[i+1] + y[i] + log(z[i]^2+15) = i+1, i = 0, 1, ..., n-1
             x+hstack((x[1:n], x[0])) + y + log(z**2 + 15) == arange(1, n+1), # n equations
             
             z + 2*x + 5*y == 100 # n equations
             )
# you can use equations with custom tolerances
# equations = (x**3 + y**3 - 9==0, (x - 0.5*y==0)(tol=1e-9), (cos(z) + x == 1.5) (tol=1e-9))
# if no tol is assigned for an equation, p.ftol (default 10^-6) will be used for that one

startPoint = {x:[0]*n, y:[0]*n, z:[0]*n}

p = SNLE(equations, startPoint)

# for some OpenOpt SNLE solvers we can set some constraints
# p.constraints = [z<70,  z>50,  z + sin(x) < 60]

r = p.solve('matlab_fsolve', matlab='/usr/local/MATLAB/R2012a/bin/matlab')
# Notebook Intel Atom 1.6 GHz:
# Solver:   Time Elapsed = 189.23 	(MATLAB preload time ~ 30 sec)
# peak memory consumption for n = 5000 (thus 15000 variables) 160 MB