示例#1
0
文件: data.py 项目: martin1/thesis
def get_intersection_point(buy_x_list, buy_y_list, sell_x_list, sell_y_list, time=None):
    #calculate intersection point
    f_buy = lambda x: interp(x, buy_x_list, buy_y_list)
    f_sell = lambda x: interp(x, sell_x_list, sell_y_list)
        
    intersect_x = fsolve(lambda x : f_sell(x) - f_buy(x), 10000)
    return intersect_x, f_buy(intersect_x)
示例#2
0
def fit_data(file_name,
             usecols,
             title,
             out_name,
             threshold=0.99,
             out_dir=os.environ['OBER'] + '/doc/qc'):
    '''Fit a curve QC data and calculate a cutoff.'''

    # Load data
    data = np.loadtxt(file_name, skiprows=1, usecols=usecols, dtype=float)
    r, n, c = data[::2, 0], data[::2, 1], data[::2, 2]
    has_data = (n > 0)
    r, n, c = r[has_data], n[has_data], c[has_data]
    r = 1.0 - r / r[-1]  # Convert no call count to call rate

    # Fit model
    f, p = fit_curve(r, n, c)
    g = lambda x: model(x, *p) - threshold
    cutoff = fsolve(g, 0.5)

    # Generate plot
    plot_data_and_model(r, c, f, cutoff, title)
    P.savefig('%s/%s.png' % (out_dir, out_name))

    if cutoff >= 1:
        print '%-40s: don\'t use at all' % (title, )
    else:
        print '%-40s: %.2f   mean %.3f' % (title, cutoff, 1 - np.mean(c))
    return r, n, c
示例#3
0
def focus_to_grating(x,y,z,xv,yv,zv,ga=ga,gb=gb,grating_r0=grating_r0,grating_z0=grating_z0,torus=torus,toroid_c=toroid_c):
    """
    Returns the time a vector must travel from the focal point to hit the grating
    Done by solving xfoc+xv*t = xg for all 3 positional arguments and the equation
    of the (spherical or toroidal) grating
    """

    if torus:
        def fz(t):
            return (toroid_c + toroid_pm2*sqrt( (x+xv*t)**2 + (z+zv*t-grating_z0+toroid_pm2*toroid_c)**2 ) )**2 + (y+yv*t)**2 - grating_r0**2
            #return  (z+zv*t) - sqrt( grating_r0**2 + toroid_c**2 - (x+xv*t)**2 - (y+yv*t)**2 - 2*sqrt( grating_r0**2*toroid_c**2 - toroid_c**2 * (y+yv*t)**2 ))
        t = fsolve(fz,1.0,warning=False)
        #import pdb; pdb.set_trace()

    else:
        term1 = (2*gb**2*x*xv + 2*ga**2*y*yv + 2*ga**2*gb**2*z*zv - 2*ga**2*gb**2*grating_z0*zv)
        term2 = -1.0* sqrt((-2*gb**2*x*xv - 2*ga**2*y*yv - 2*ga**2*gb**2*z*zv + 2*ga**2*gb**2*grating_z0*zv)**2 - 
          4*(ga**2*gb**2*grating_r0**2 - gb**2*x**2 - ga**2*y**2 - ga**2*gb**2*z**2 + 
             2*ga**2*gb**2*z*grating_z0 - ga**2*gb**2*grating_z0**2)*(-gb**2*xv**2 - ga**2*yv**2 - 
             ga**2*gb**2*zv**2))
        term3 = 1.0/(2*(-gb**2*xv**2 - ga**2*yv**2 - ga**2*gb**2*zv**2))
        #toroid_c = 0.0
        #def fz(t):
        #    return (toroid_c - sqrt( (x+xv*t)**2 + (z+zv*t-grating_z0)**2 ) )**2 + (y+yv*t)**2 - grating_r0**2
        #    #return  (z+zv*t) + sqrt( grating_r0**2 - (x+xv*t)**2 - (y+yv*t)**2 + 2*sqrt( grating_r0**2 * (y+yv*t)**2 ))

        if isnan(term1) or isnan(term2) or isnan(term3): pdb.set_trace()
        #t1 = fsolve(fz,1.88,warning=False)
        #t2 = newton(fz,1.88,tol=1e-35)
        t = (term1+term2)*term3
        #print t,t1,t2
        #import pdb; pdb.set_trace()

    return t
示例#4
0
 def fsolve_fn(s, t):
     rout.start()
     ##                rerr.start()
     res = minpack.fsolve(f, x0, args=(t,) + extrafargs, xtol=xtolval, maxfev=maxnumiter, fprime=fprime)
     rout.stop()
     ##                warns = rout.stop()
     ##                rerr.stop()
     return res
示例#5
0
 def fsolve_fn(s, t):
     with RedirectStdout(_logfile):
         res = minpack.fsolve(f,
                              x0,
                              args=(t, ) + extrafargs,
                              xtol=xtolval,
                              maxfev=maxnumiter,
                              fprime=fprime)
         return res
示例#6
0
 def fsolve_fn(s, t):
     rout.start()
     ##                rerr.start()
     res = minpack.fsolve(f,
                          x0,
                          args=(t, ) + extrafargs,
                          xtol=xtolval,
                          maxfev=maxnumiter,
                          fprime=fprime)
     rout.stop()
     ##                warns = rout.stop()
     ##                rerr.stop()
     return res
	def BEM(self):
		L = self.L
		R = self.R
		self.Ubem = np.zeros([L, 2])
		self.Ubem[0] = self.Uzero
		for j in np.arange(L-1):
			self.Winc = np.sum(self.dWj[:, R * (j) : R * (j + 1)], axis=1)
			self.Winc = self.Winc.reshape([2, 1])
			uj = self.Ubem[j,:].reshape([2, 1])
			increment = fsolve(self.ai, uj, args=(j)).reshape([2, 1])
			self.Ubem[j+1, :] = increment[:, 0]
		ubem = self.Ubem
		return ubem
示例#8
0
文件: calc.py 项目: luzpaz/pyoptools
def find_reference_sphere_radius(ip, pl):
    """Find the radius os the reference sphere that best fits the input data.
    
    This method assumes that the optical axis coincides with the z axis. This 
    means that the center of the sphere, has coordinates (0,0,r).
    
    Parameters
    ----------

    ip : list
        list of the points where the optical path is measured, that are being 
        fitted. Each point is (XYZ) tuple. It can be also an array with a shape 
        n,3 where n is the number of points.
    pl : list
        List of path lengths. pl[i] corresponds to the point ip[i].

    Returns
    -------
    float
        Reference sphere radius
    """

    ipa = array(ip)
    pla = array(pl)
    n, t = ipa.shape

    # Find the point closest to the center of the aperture.
    rm = sqrt(dot(ipa[0], ipa[0]))
    im = 0
    for i in range(n):
        if rm > sqrt(dot(ipa[i], ipa[i])):
            rm = sqrt(dot(ipa[i], ipa[i]))
            im = i

    #Make the OPL 0 at the center of the aperture
    pla = pla - pla[im]

    #Encontrar el radio de la esfera de mejor ajuste
    def F(z):
        dist = pla - (sqrt(ipa[:, 0]**2 + ipa[:, 1]**2 +
                           (ipa[:, 2] - z)**2) - z)
        u = sqrt((dist**2).sum())
        #print "*", u
        #u=dist[-1]
        #print u
        return u

    r = fsolve(F, -10.)

    return r
示例#9
0
def find_reference_sphere_radius(ip, pl):
    """Find the radius os the reference sphere that best fits the input data.
    
    This method asumes that the optical axis coincides with the z axis. This 
    means that the center of the sphere, has coordinates (0,0,r).
    
    Attributes:

    
    ip
        list of the points where the optical path is measured, that are being 
        fitted. Each point is (XYZ) tuple. It can be also an array with a shape 
        n,3 where n is the numbre of points.
    pl
        List of path lengths. pl[i] corresponds to the point ip[i].
    """
    
    ipa=array(ip)
    pla=array(pl)
    n, t=ipa.shape
    
    # Find the point closest to the center of the aperture.
    rm=sqrt(dot(ipa[0], ipa[0]))
    im=0
    for i in range (n):
        if rm>sqrt(dot(ipa[i], ipa[i])):
            rm=sqrt(dot(ipa[i], ipa[i]))
            im=i
    
    #Make the OPL 0 at the center of the aperture
    pla=pla-pla[im]
    
    #Encontrar el radio de la esfera de mejor ajuste
    def F(z):
        dist=pla-(sqrt(ipa[:, 0]**2+ipa[:, 1]**2+(ipa[:, 2]-z)**2)-z)
        u=sqrt((dist**2).sum())
        #print "*", u
        #u=dist[-1]
        #print u
        return  u
    
    
    r=fsolve(F, -10.)
    
    return r
示例#10
0
def find_steady_states(rates, sos_counts, ras, rasgap, rasgrp, guesses, output_dirname="output"):
    """
    Solve for steady states. We start with the guesses
    obtained from solving the ODE to plot it. We then bootstrap
    to get all the intermediate points.
    """
    print(guesses)
    last = None
    steady_states = []

    for sos_mol in sos_counts:
        sos = Sos(num_molecules=sos_mol)
        reactions = Reactions(rates, sos.num_molecules, ras.num_molecules, rasgap.num_molecules, rasgrp.num_molecules)

        try:
            guess = guesses[sos_mol]
        except KeyError:
            guess = last
        steady_state_y = fsolve(dy_dt, guess, args=(0, reactions))
        print("Steady Y: {}".format(steady_state_y))

        last = steady_state_y
        steady_states.append(steady_state_y)

    # Steady states by starting Sos molecules
    steady_states = np.array(steady_states)
    plt.figure(figsize=[10, 8])
    plt.plot(sos_counts, steady_states[:, 0], "o", label="SOS")
    plt.plot(sos_counts, steady_states[:, 1], "o", label="SOS-RasGTP")
    plt.plot(sos_counts, steady_states[:, 2], "o", label="RasGTP")
    plt.legend()
    plt.xlabel("Initial SOS Count")
    plt.ylabel("Steady State Count")

    title = "Das Minimal Model- Steady State RasGTP"
    dirname = os.path.join(output_dirname, "steady_states")
    if not os.path.exists(dirname):
        os.mkdir(dirname)
    plt.title(title)
    plt.savefig(os.path.join(dirname, title.replace(" ", "-") + ".png"))
    # plt.show()
    plt.close()

    return steady_states
示例#11
0
    def solve(self, graph):
        new_graph = deepcopy(graph)
        new_graph.ns_x_mesh.phi_old = deepcopy(graph.ns_x_mesh.phi)
        new_graph.ns_y_mesh.phi_old = deepcopy(graph.ns_y_mesh.phi)
        new_graph.pressure_mesh.phi_old = deepcopy(graph.pressure_mesh.phi)

        pressure_mesh = new_graph.pressure_mesh
        ns_x_mesh = new_graph.ns_x_mesh
        ns_y_mesh = new_graph.ns_y_mesh

        # Prepare initial guess
        X = _create_X(ns_x_mesh.phi, ns_y_mesh.phi, pressure_mesh.phi,
                      new_graph)

        if PLOT_JACOBIAN:
            from lid_driven_cavity_problem.nonlinear_solver._utils import _plot_jacobian
            _plot_jacobian(new_graph, X)
            assert False, "Finished plotting Jacobian matrix. Program will be terminated (This is expected behavior)"

        X_, infodict, ier, mesg = fsolve(self._residual_f,
                                         X,
                                         args=(new_graph, ),
                                         full_output=True)
        if SHOW_SOLVER_DETAILS:
            logger.info("Number of function calls=%s" % (infodict['nfev'], ))
            if ier == 1:
                logger.info("Converged")
            else:
                logger.info("Diverged")
                logger.info(mesg)

        if not IGNORE_DIVERGED:
            if not ier == 1:
                raise SolverDivergedException()

        U, V, P = _recover_X(X_, new_graph)
        new_graph.ns_x_mesh.phi = U
        new_graph.ns_y_mesh.phi = V
        new_graph.pressure_mesh.phi = P

        return new_graph
示例#12
0
def fit_data(file_name, usecols, title, out_name, threshold=0.99, out_dir=os.environ['OBER'] + '/doc/qc'):
    '''Fit a curve QC data and calculate a cutoff.'''

    # Load data
    data = np.loadtxt(file_name, skiprows=1, usecols=usecols, dtype=float)
    r, n, c = data[::2, 0], data[::2, 1], data[::2, 2]
    has_data = (n > 0)
    r, n, c = r[has_data], n[has_data], c[has_data]
    r = 1.0 - r / r[-1]  # Convert no call count to call rate

    # Fit model
    f, p = fit_curve(r, n, c)
    g = lambda x: model(x, *p) - threshold
    cutoff = fsolve(g, 0.5)
    
    # Generate plot
    plot_data_and_model(r, c, f, cutoff, title)
    P.savefig('%s/%s.png' % (out_dir, out_name))
    
    if cutoff >= 1:
        print '%-40s: don\'t use at all' % (title,)
    else:
        print '%-40s: %.2f   mean %.3f' % (title, cutoff, 1 - np.mean(c))
    return r, n, c

# Find fixed point of map
def fp_residual(ic):
    x0 = ic[0]
##    print "\nfp_residual: x0 = ", x0
    v = return_map({'x': x0})
    print v
    return v-ic[0]


print "Finding fixed point of return map as function of initial condition"

# Equally efficient alternatives to shoot for f.p. solution
x0_guess = map_ics['x']
sol_pdc = minpack.fsolve(fp_residual, array([x0_guess]), xtol=1e-6)
print "sol_pdc = ", sol_pdc


traj,pts=getTraj({'y':0,'x':sol_pdc}, t1=10,
        termFlag=False)

map.set(ics={'x':sol_pdc})

print "Initializing PyCont to follow y=0 crossing as parameter m varied:"

pc=ContClass(map)
pcargs=args(name='FPu', type='FP-C',
  freepars = ['m'],
  StepSize = 1e-1,
  MaxNumPoints = 30, # 40 causes IndexError in PyCont/BifPoint.py, line 149
示例#14
0

def fp_beta_newton(b, x0):
    SLIP_map.set(pars={'beta': b})
    x0['z'] = math.sin(b)
    x0['y'] = math.cos(b)
    x1 = pdc_map(x0)
    return x1['zdot'] - x0['zdot']  # Point


icdict_pert = copy(icdict)
icpt = Point({'coorddict': icdict_pert})
print("\nFinding fixed point of periodic map as a function of beta")

# Equally efficient alternatives to shoot for f.p. solution
beta_pdc = minpack.fsolve(fp_beta_fsolve, beta, args=(icpt, ), xtol=1e-4)
##beta_pdc = minpack.newton(fp_beta_newton, beta, args=(icpt,), tol=1e-4)
beta_pdc_known = 1.21482619378
print("beta_pdc = ", beta_pdc)
assert abs(beta_pdc -
           beta_pdc_known) < 1e-4, "beta_pdc was not found accurately"

# update i.c. for new beta
icdict_pert['z'] = math.sin(beta_pdc)
icdict_pert['y'] = math.cos(beta_pdc)
icdict_maps = copy(icdict_pert)
icpt = Point({'coorddict': icdict_maps})
print("\nCalculating approximation to periodic maps")
SLIP_map.set(pars={'beta': beta_pdc})
states = [icpt]
for i in range(5):
示例#15
0
def solwave_m1(c, n, d, M, dist = pi / 2., xtol = 1.e-12, verbose = False):
	"""
	Compute the collocation points and values for the general d-dimensional
	solitary wave equation with n > 1, and m=1

	Inputs: c - soliton parameter, 

	n - first nonlinearity, 

	d - dimension, 

	M - No. of points, 

	[dist = pi/2] - distance from the x axis to the nearest
	singularity in the complex plane, 

	[xtol = 1.e-12] - solver tolerance,

	[verbose=True/False]

	Outputs: r, f - collocation points and the soliton
	"""

	# Iterate in soliton parameter, if neccessary, to achieve a good
	# guess.  This may be replaced with another algorithm if a better
	# initial guess for the 1D soliton is available.
	if verbose:
		print " iterating in c"

	# Initial value for delta c.  This can be tuned as needed.
	delta_c = .5 * n / c

	# Loop will terminate if the delta c value gets too small, this may be
	# adjusted as needed
	delta_c_min = 1.e-6

	c0 = n
	d0 = 1.

	while c0 < c and delta_c > delta_c_min:

		c1 = min([c0 + delta_c, c])

		decay = sqrt(1. - n / c1)

		h = sqrt((pi * dist) / (decay * M))

		r1 = sinc_eo.points(M, h)

		D2 = sinc_eo.D2_e(M, h)
		D1 = sinc_eo.D1_eo(M, h)
		D1_r = sinc_eo.D1_x_e(M, h)
		IN1 = sinc_eo.IN1_oe(M, h)

		params = {'c': c1, 'n': n, 'd': d0, 
			  'D2': D2, 'D1': D1, 'D1_r': D1_r, 'IN': IN1}

		try:
#			uguess = spline(r0, u0, r1)
			uguess = sinc_eo.sincinterp_e(r0,u0,r1)
		except:
			uguess = 3. * (1. - n / c1) / cosh(.5 * decay * r1)**2

		if verbose:
			print ' computing with c = ', c1

		u1, infodict, ier, mesg = \
		    fsolve(lambda v: solwave_m1_eq(v,params), uguess, \
#			   fprime = lambda v:solwave_m1_eq_jac(v, params), \
			   xtol= xtol,
			   full_output=1)

		if ier == 1 and np.max(np.abs(u1)) > 1.e-10:

			c0 = c1
			u0 = u1
			r0 = r1

		else:
			if verbose:
				if np.max(np.abs(u1)) <= 1.e-8:
					print " converged to the zero solution, adjusteing delta_c"
				else:
					print " solver failed to converge, adjusting delta_c"
					print " solver err = ", ier

			delta_c = delta_c / 2.

	u = u0
	r = r0

	# Iterate in dimension, if neccessary
	if d > 1.:

		if verbose:
			print " iterating in d"

		delta_dim = (n - 1.) / 10.

		# Loop will terminate if the delta dim value gets too
		# small, this can be adjusted as desired 
		delta_dim_min = 1.e-6

		d0 = 1.

		u0 = u

		while d0 < d and delta_dim > delta_dim_min:

			d1 = min([d0 + delta_dim, d])

			params['d'] = d1

			if verbose:
				print ' computing with d = ', d1
		
			u1, infodict, ier, mesg = \
			    fsolve(lambda v: solwave_m1_eq(v, params), u0, \
#				   fprime = lambda v:solwave_m1_eq_jac(v, params),
				   xtol= xtol,
				   full_output=1)


			if ier == 1 and np.max(np.abs(u1)) > 1.e-8:

				d0 = d1
				u0 = u1

			else:
				if verbose:
					if np.max(np.abs(u1)) <= 1.e-8:
						print " converged to the zero solution, adjusteing delta_dim"
					else:
						print " solver failed to converge, adjusting delta_dim"
						print " solver err = ", ier

				delta_dim = delta_dim / 2.
				
		u = u0
		
	if d0 < d:
		print " Failed to converge to the soliton solution, last value of d =", d0
		f = 0.0
	else:
		f = 1. + u

	return r, f
示例#16
0
文件: utils.py 项目: LeiDai/pydstool
 def fsolve_fn(s, t):
     with RedirectStdout(_logfile):
         res = minpack.fsolve(f, x0, args=(t,)+extrafargs,
                             xtol=xtolval, maxfev=maxnumiter,
                             fprime=fprime)
         return res
示例#17
0
def solwave_mck(c, d, M, dist = pi / 2., xtol = 1.e-12, verbose = False):
	"""
	Compute the collocation points and values for the d-dimensional
	McKenzie solitary wave equation.  n=3, m=0.

	Inputs: c - soliton parameter, 

	d - dimension, 

	M - No. of points, 

	[dist = pi/2] - distance from the x axis to the nearest
	singularity in the complex plane, 

	[xtol = 1.e-12] - solver tolerance,

	[verbose=True/False]

	Outputs: r, f - collocation points and the soliton
	"""
		
	decay = sqrt(1. - 3. / c)

	h = sqrt((pi * dist) / (decay * M))
	
	r = sinc_eo.points(M, h)
	
	u0 = magma1d.solwave_mck(r, c) - 1.

	d0 = 1.
	
	D2 = sinc_eo.D2_e(M, h)
	D1 = sinc_eo.D1_eo(M, h)
	D1_r = sinc_eo.D1_x_e(M, h)
	IN1 = sinc_eo.IN1_oe(M, h)
	
	params = {'c': c, 'd': d0, 
		  'D2': D2, 'D1':D1, 'D1_r':D1_r, 'IN': IN1}

	if d < 2.:
		
		params['d'] = d

		u = fsolve(lambda v: solwave_mck_eq(v, params), u0, 
			   fprime = lambda v:solwave_mck_eq_jac(v, params), 
			   xtol= xtol)
	
	else:
		# Initial value for the delta dimension value.  
		# This can be tuned as needed
		delta_dim = (d - 1.)/10.

		# Loop will terminate if the delta dim value gets too
		# small, this may be tunded as needed
		delta_dim_min = 1.e-6

		d0 = 1.

		while d0 < d and delta_dim > delta_dim_min:

			d1 = min([d0 + delta_dim, d])
			params['d'] = d1

			if verbose:
				print ' computing with d = ', d1
		
			u1, infodict, ier, mesg = \
			    fsolve(lambda v:solwave_mck_eq(v,params), u0, \
				   fprime =lambda v:solwave_mck_eq_jac(v, params), \
				   xtol= xtol,
				   full_output=1)



			if ier == 1 and np.max(np.abs(u1)) > 1.e-8:

				d0 = d1
				u0 = u1

			else:
				if verbose:
					if np.max(np.abs(u1)) <= 1.e-8:
						print " converged to the zero solution, adjusteing delta_dim"
					else:
						print " solver failed to converge, adjusting delta_dim"
						print " solver err = ", ier

				delta_dim = delta_dim / 2.
			if verbose:
				jac = solwave_mck_eq_jac(u1, params)
				condnum = np.linalg.cond(jac)
				print " condition number = ", condnum

				
		u = u0

	if d0 < d:
		print " Failed to converge to the soliton solution, last value of d =", d0
		f = 0.0
	else:
		f = 1. + u

	return r, f
示例#18
0
m2 = 2150
delta_f2 = f0 * 1e9 / m2
L2 = 1e6 * c / (2 * n2 * delta_f2)

def VCCL_threshold_static(x):
    k = 2 * pi / x[0]
    g1 = x[1] / 20000
    g2 = g1 * L1 / L2
    y1 = r1 * r2 * cmath.exp(2 * g1 * L1 + 2 * 1j * k * n1 * L1)
    y2 = r1 * r2 * cmath.exp(2 * g2 * L2 + 2 * 1j * k * n2 * L2)
    yc = C11 * y1 + C22 * y2 - (C11 * C22 - C12 * C21) * y1 * y2 - 1
    yr = yc.real
    yi = yc.imag
    return [yr, yi]

X = fsolve(VCCL_threshold_static, [lambda0, gain0])

# Calculate the effective "reflectivity" of the second cavity as seen by the first cavity, and vice versa
wavelength = numpy.arange(1530, 1570, 0.0005)
k = 2000 * pi / wavelength
g1 = X[1] / 20000
g2 = g1 * L1 / L2
y2 = numpy.exp(2 * g2 * L2) * numpy.exp(2 * 1j * k * n2 * L2)
eta2 = C11 + C12 * C21 * r1 * r2 * y2 / (1 - C22 * r1 * r2 * y2);
ETA2 = (numpy.absolute(eta2)) ** 2;
y1 = numpy.exp(2 * g1 * L1) * numpy.exp(2 * 1j * k * n1 * L1);
eta1 = C22 + C12 * C21 * r1 * r2 * y1 / (1 - C11 * r1 * r2 * y1);
ETA1 = (numpy.absolute(eta1)) ** 2;

pyplot.figure()
pyplot.plot(wavelength, ETA1, ':k', label='ETA1')
示例#19
0
    plt.savefig(fname)


def error(f, x, y):
    return np.sum((f(x) - y)**2)


plot_models(x, y, None, os.path.join(CHART_DIR, "1400_01_01.png"))

fp1, res1, rank1, sv1, rcond1 = np.polyfit(x, y, 1, full=True)
print("Parámetros del modelo fp1: %s" % fp1)
print("Error del modelo fp1:", res1)
f1 = sp.poly1d(fp1)

fp2, res2, rank2, sv2, rcond2 = np.polyfit(x, y, 2, full=True)
print("Parámetros del modelo fp2: %s" % fp2)
print("Error del modelo fp2:", res2)
f2 = sp.poly1d(fp2)

funcion_definitiva = sp.poly1d(np.polyfit(x, y, 5))
funcion_definitiva1 = sp.poly1d(np.polyfit(x, y, 6))
funcion_definitiva2 = sp.poly1d(np.polyfit(x, y, 10))
funcion_definitiva3 = sp.poly1d(np.polyfit(x, y, 20))
funcion_definitiva4 = sp.poly1d(np.polyfit(x, y, 25))

plot_models(x, y, [funcion_definitiva, funcion_definitiva1],
            os.path.join(CHART_DIR, "1400_01_02.png"))

prediccion = fsolve(funcion_definitiva, x0=165)
print('Esperamos encontrar 0 casos diarios el dia: ', prediccion)
示例#20
0
    return [yr, yi]

I3 = numpy.arange(0, 0.8, 0.001)  # 波长转换区电流(A)
lambda1 = I3.copy()
for ii in range(0, I3.size):
    a = C
    b = B
    c1 = A
    d = -I3[ii] / e / V3
    D = [a, b, c1, d]
    NN3 = roots(D)
    for r in [0, 1, 2]:
        if (NN3[r].imag == 0) and (NN3[r] >= 0):
            N3 = NN3[r]
    delta_n3 = tau_p * dn_dN * N3  # the carrier-induced index change
 
    # Calculate threshold gains of various modes
    wl = numpy.arange(1, 10, 1)
    threshold_gain = numpy.arange(1, 10, 1)
    for m in range(m1 - 4, m1 + 5):
        lmd = 1e6 * c / (m * delta_f1)
        X1 = fsolve(VCCL_threshold_dynamic, [lmd, 0.95 * gain0])
        wl[m - m1 + 4] = X1[0] * 1000
        threshold_gain[m - m1 + 4] = X1[1]
    lambda1[ii] = wl[threshold_gain.argmin()]
pyplot.figure()
pyplot.plot(I3[0:I3.size-2], lambda1[0:I3.size-2], ':k+')
pyplot.xlabel('$Wavelength switching section current (A)$')
pyplot.ylabel('$laser wavelength (nm)$')
pyplot.show()
示例#21
0
def redise(p0, x, y):
    a, b = p0
    return (y - (a * x + b))


data = sp.genfromtxt("web_traffic.tsv", "\t")

y = data[:, 1]
x = data[:, 0]

x_clean = x[np.where(y > -1)]
y_clean = y[np.where(y > -1)]

rs1 = leastsq(redise, [0, 0], args=(x_clean, y_clean))
rs2 = polyfit(x_clean, y_clean, 2, full=True)
rs5 = polyfit(x_clean, y_clean, 25, full=True)

y_predit1 = rs1[0][0] * x_clean + rs1[0][1]
y_predit2 = sp.poly1d(rs2[0])
y_predit5 = sp.poly1d(rs5[0])

print y_predit2
result = fsolve(y_predit2 - 10000, 0)
print result
pt.plot(x_clean, y_clean, '.')
pt.plot(x_clean, y_predit1, '-', label="predit1")
pt.plot(x_clean, y_predit2(x_clean), '-', label="predit2")
pt.plot(x_clean, y_predit5(x_clean), '-', label='predit5')
pt.legend()
pt.show()
示例#22
0
def solwave_m1(c, n, d, M, dist = pi / 2., xtol = 1.e-12, verbose = False):
	"""
	Compute the collocation points and values for the general d-dimensional
	solitary wave equation with n > 1, and m=1

	Inputs: c - soliton parameter, 

	n - first nonlinearity, 

	d - dimension, 

	M - No. of points, 

	[dist = pi/2] - distance from the x axis to the nearest
	singularity in the complex plane, 

	[xtol = 1.e-12] - solver tolerance,

	[verbose=True/False]

	Outputs: r, f - collocation points and the soliton
	"""

	# Iterate in soliton parameter, if neccessary, to achieve a good
	# guess.  This may be replaced with another algorithm if a better
	# initial guess for the 1D soliton is available.
	if verbose:
		print " iterating in c"

	# Initial value for delta c.  This can be tuned as needed.
	delta_c = .5 * n / c

	# Loop will terminate if the delta c value gets too small, this may be
	# adjusted as needed
	delta_c_min = 1.e-6

	c0 = n
	d0 = 1.

	while c0 < c and delta_c > delta_c_min:

		c1 = min([c0 + delta_c, c])

		decay = sqrt(1. - n / c1)

		h = sqrt((pi * dist) / (decay * M))

		r1 = sinc_eo.points(M, h)

		D2 = sinc_eo.D2_e(M, h)
		D1 = sinc_eo.D1_eo(M, h)
		D1_r = sinc_eo.D1_x_e(M, h)
		IN1 = sinc_eo.IN1_oe(M, h)

		params = {'c': c1, 'n': n, 'd': d0, 
			  'D2': D2, 'D1': D1, 'D1_r': D1_r, 'IN': IN1}

		try:
#			uguess = spline(r0, u0, r1)
			uguess = sinc_eo.sincinterp_e(r0,u0,r1)
		except:
			uguess = 3. * (1. - n / c1) / cosh(.5 * decay * r1)**2

		if verbose:
			print ' computing with c = ', c1

		u1, infodict, ier, mesg = \
		    fsolve(lambda v: solwave_m1_eq(v,params), uguess, \
#			   fprime = lambda v:solwave_m1_eq_jac(v, params), \
			   xtol= xtol,
			   full_output=1)

		if ier == 1 and np.max(np.abs(u1)) > 1.e-10:

			c0 = c1
			u0 = u1
			r0 = r1

		else:
			if verbose:
				if np.max(np.abs(u1)) <= 1.e-8:
					print " converged to the zero solution, adjusteing delta_c"
				else:
					print " solver failed to converge, adjusting delta_c"
					print " solver err = ", ier

			delta_c = delta_c / 2.

	u = u0
	r = r0

	# Iterate in dimension, if neccessary
	if d > 1.:

		if verbose:
			print " iterating in d"

		delta_dim = (n - 1.) / 10.

		# Loop will terminate if the delta dim value gets too
		# small, this can be adjusted as desired 
		delta_dim_min = 1.e-6

		d0 = 1.

		u0 = u

		while d0 < d and delta_dim > delta_dim_min:

			d1 = min([d0 + delta_dim, d])

			params['d'] = d1

			if verbose:
				print ' computing with d = ', d1
		
			u1, infodict, ier, mesg = \
			    fsolve(lambda v: solwave_m1_eq(v, params), u0, \
#				   fprime = lambda v:solwave_m1_eq_jac(v, params),
				   xtol= xtol,
				   full_output=1)


			if ier == 1 and np.max(np.abs(u1)) > 1.e-8:

				d0 = d1
				u0 = u1

			else:
				if verbose:
					if np.max(np.abs(u1)) <= 1.e-8:
						print " converged to the zero solution, adjusteing delta_dim"
					else:
						print " solver failed to converge, adjusting delta_dim"
						print " solver err = ", ier

				delta_dim = delta_dim / 2.
				
		u = u0
		
	if d0 < d:
		print " Failed to converge to the soliton solution, last value of d =", d0
		f = 0.0
	else:
		f = 1. + u

	return r, f
示例#23
0
def solwave_mck(c, d, M, dist = pi / 2., xtol = 1.e-12, verbose = False):
	"""
	Compute the collocation points and values for the d-dimensional
	McKenzie solitary wave equation.  n=3, m=0.

	Inputs: c - soliton parameter, 

	d - dimension, 

	M - No. of points, 

	[dist = pi/2] - distance from the x axis to the nearest
	singularity in the complex plane, 

	[xtol = 1.e-12] - solver tolerance,

	[verbose=True/False]

	Outputs: r, f - collocation points and the soliton
	"""
		
	decay = sqrt(1. - 3. / c)

	h = sqrt((pi * dist) / (decay * M))
	
	r = sinc_eo.points(M, h)
	
	u0 = magma1d.solwave_mck(r, c) - 1.

	d0 = 1.
	
	D2 = sinc_eo.D2_e(M, h)
	D1 = sinc_eo.D1_eo(M, h)
	D1_r = sinc_eo.D1_x_e(M, h)
	IN1 = sinc_eo.IN1_oe(M, h)
	
	params = {'c': c, 'd': d0, 
		  'D2': D2, 'D1':D1, 'D1_r':D1_r, 'IN': IN1}

	if d < 2.:
		
		params['d'] = d

		u = fsolve(lambda v: solwave_mck_eq(v, params), u0, 
			   fprime = lambda v:solwave_mck_eq_jac(v, params), 
			   xtol= xtol)
	
	else:
		# Initial value for the delta dimension value.  
		# This can be tuned as needed
		delta_dim = (d - 1.)/10.

		# Loop will terminate if the delta dim value gets too
		# small, this may be tunded as needed
		delta_dim_min = 1.e-6

		d0 = 1.

		while d0 < d and delta_dim > delta_dim_min:

			d1 = min([d0 + delta_dim, d])
			params['d'] = d1

			if verbose:
				print ' computing with d = ', d1
		
			u1, infodict, ier, mesg = \
			    fsolve(lambda v:solwave_mck_eq(v,params), u0, \
				   fprime =lambda v:solwave_mck_eq_jac(v, params), \
				   xtol= xtol,
				   full_output=1)



			if ier == 1 and np.max(np.abs(u1)) > 1.e-8:

				d0 = d1
				u0 = u1

			else:
				if verbose:
					if np.max(np.abs(u1)) <= 1.e-8:
						print " converged to the zero solution, adjusteing delta_dim"
					else:
						print " solver failed to converge, adjusting delta_dim"
						print " solver err = ", ier

				delta_dim = delta_dim / 2.
			if verbose:
				jac = solwave_mck_eq_jac(u1, params)
				condnum = np.linalg.cond(jac)
				print " condition number = ", condnum

				
		u = u0

	if d0 < d:
		print " Failed to converge to the soliton solution, last value of d =", d0
		f = 0.0
	else:
		f = 1. + u

	return r, f
示例#24
0

def fp_beta_newton(b, x0):
    SLIP_map.set(pars={'beta': b})
    x0['z'] = math.sin(b)
    x0['y'] = math.cos(b)
    x1 = pdc_map(x0)
    return x1['zdot']-x0['zdot']  # Point


icdict_pert = copy(icdict)
icpt = Point({'coorddict': icdict_pert})
print "\nFinding fixed point of periodic map as a function of beta"

# Equally efficient alternatives to shoot for f.p. solution
beta_pdc = minpack.fsolve(fp_beta_fsolve, beta, args=(icpt,), xtol=1e-4)
##beta_pdc = minpack.newton(fp_beta_newton, beta, args=(icpt,), tol=1e-4)
beta_pdc_known = 1.21482619378
print "beta_pdc = ", beta_pdc
assert abs(beta_pdc-beta_pdc_known)<1e-4, "beta_pdc was not found accurately"

# update i.c. for new beta
icdict_pert['z'] = math.sin(beta_pdc)
icdict_pert['y'] = math.cos(beta_pdc)
icdict_maps = copy(icdict_pert)
icpt = Point({'coorddict': icdict_maps})
print "\nCalculating approximation to periodic maps"
SLIP_map.set(pars={'beta': beta_pdc})
states = [icpt]
for i in range(5):
    states.append(pdc_map(states[-1]))

# Find fixed point of map
def fp_residual(ic):
    x0 = ic[0]
    ##    print "\nfp_residual: x0 = ", x0
    v = return_map({'x': x0})
    print v
    return v - ic[0]


print "Finding fixed point of return map as function of initial condition"

# Equally efficient alternatives to shoot for f.p. solution
x0_guess = map_ics['x']
sol_pdc = minpack.fsolve(fp_residual, array([x0_guess]), xtol=1e-6)
print "sol_pdc = ", sol_pdc

traj, pts = getTraj({'y': 0, 'x': sol_pdc}, t1=10, termFlag=False)

map.set(ics={'x': sol_pdc})

print "Initializing PyCont to follow y=0 crossing as parameter m varied:"

pc = ContClass(map)
pcargs = args(
    name='FPu',
    type='FP-C',
    freepars=['m'],
    StepSize=1e-1,
    MaxNumPoints=30,  # 40 causes IndexError in PyCont/BifPoint.py, line 149