Exemplo n.º 1
0
    def setUp(self):
        np.random.seed(1)

        # generate data
        N = 400
        s_x = 0.05
        s_y = 0.1
        X = (sp.linspace(0, 2, N) + s_x * sp.randn(N))[:, sp.newaxis]
        Y = sp.sin(X) + s_y * sp.randn(N, 1)
        Y -= Y.mean(0)
        Y /= Y.std(0)

        Xstar = sp.linspace(0, 2, 1000)[:, sp.newaxis]

        # define mean term
        F = 1.0 * (sp.rand(N, 2) < 0.2)
        mean = lin_mean(Y, F)

        # define covariance matrices
        covar1 = SQExpCov(X, Xstar=Xstar)
        covar2 = FixedCov(sp.eye(N))
        covar = SumCov(covar1, covar2)

        # define gp
        self._gp = GP(covar=covar, mean=mean)
Exemplo n.º 2
0
    def __init__(self, R, a, B0, Ip, betat, length_unit="m", npts=257):
        # instantiate superclass, forcing time splining to false (no time variation
        # in equilibrium)
        super(CircSolovievEFIT, self).__init__(length_unit=length_unit, tspline=False, monotonic=False)

        self._defaultUnits = {}

        self._R = R
        self._defaultUnits["_R"] = length_unit
        self._a = a
        self._defaultUnits["_a"] = length_unit
        self._B0 = B0
        self._defaultUnits["_B0"] = "T"
        self._Ip = Ip
        self._defaultUnits["_Ip"] = "MA"
        self._betat = betat
        self._npts = npts

        self._currentSign = -1 if Ip > 0 else 1
        # Remember: Ip is in MA.
        self._qstar = (2.0 * scipy.pi * a ** 2 * B0) / (4.0 * scipy.pi * 1.0e-1 * R * Ip)

        # flux definitions
        self._psiLCFS = scipy.array([0.0])
        self._psi0 = -0.5 * self._B0 * self._a ** 2 / self._qstar
        self._psi0 = scipy.array([self._psi0])

        # RZ grid
        self._rGrid = scipy.linspace(R - 1.25 * a, R + 1.25 * a, self._npts)
        self._defaultUnits["_rGrid"] = length_unit
        self._zGrid = scipy.linspace(-1.25 * a, 1.25 * a, self._npts)
        self._defaultUnits["_zGrid"] = length_unit

        self._psiRZ = self.rz2psi_analytic(self._rGrid, self._zGrid, length_unit=length_unit, make_grid=True)
        self._psiRZ = scipy.reshape(self._psiRZ, (1, npts, npts))
Exemplo n.º 3
0
    def split(self, sagi, meri):
        """ utilizes geometry.grid to change the rectangle into a generalized surface,
        it is specified with a single set of basis vectors to describe the meridonial,
        normal, and sagittal planes."""
        ins = float((sagi - 1))/sagi
        inm = float((meri - 1))/meri
        stemp = self.sagi.s/sagi
        mtemp = self.meri.s/meri

        self.sagi.s,self.meri.s = scipy.meshgrid(scipy.linspace(-self.sagi.s*ins,
                                                                 self.sagi.s*ins,
                                                                 sagi),
                                                 scipy.linspace(-self.meri.s*inm,
                                                                 self.meri.s*inm,
                                                                 meri))

        x_hat = self + (self.sagi + self.meri) #creates a vector which includes all the centers of the subsurface
        self.sagi.s = stemp*sagi #returns values to previous numbers
        self.meri.s = mtemp*meri

        print(x_hat.x().shape)

        temp = Rect(x_hat,
                    self._origin,
                    [2*stemp,2*mtemp],
                    vec=[self.meri.copy(), self.norm.copy()],
                    flag=self.flag)
        #return temp

        return super(Rect, temp).split(temp._origin,
                                       [2*stemp,2*mtemp],
                                       vec=[temp.meri,temp.norm],
                                       flag=temp.flag,
                                       obj=type(temp))
Exemplo n.º 4
0
def test_quasi_newton_broyden_bad():
    op = p.OptimizationProblem(c.chebyquad)
    guess=linspace(0,1,4)
    cn  = p.QuasiNewtonBroydenBad(op)
    assert near(sol4,(cn.optimize(guess)))
    guess=linspace(0,1,8)
    assert near(sol8,(cn.optimize(guess)))
Exemplo n.º 5
0
    def split(self, sagi, meri):
        """ utilizes geometry.grid to change the rectangle into a generalized surface,
        it is specified with a single set of basis vectors to describe the meridonial,
        normal, and sagittal planes."""
        ins = float((sagi - 1))/sagi
        inm = float((meri - 1))/meri
        stemp = self.norm.s/sagi
        mtemp = self.meri.s/meri

        z,theta = scipy.meshgrid(scipy.linspace(-self.norm.s*ins,
                                                self.norm.s*ins,
                                                sagi),
                                 scipy.linspace(-self.meri.s*inm,
                                                self.meri.s*inm,
                                                meri))

        vecin =geometry.Vecr((self.sagi.s*scipy.ones(theta.shape),
                              theta+scipy.pi/2,
                              scipy.zeros(theta.shape))) #this produces an artificial
        # meri vector, which is in the 'y_hat' direction in the space of the cylinder
        # This is a definite patch over the larger problem, where norm is not normal
        # to the cylinder surface, but is instead the axis of rotation.  This was
        # done to match the Vecr input, which works better with norm in the z direction
               
        pt1 = geometry.Point(geometry.Vecr((scipy.zeros(theta.shape),
                                            theta,
                                            z)),
                             self)

        pt1.redefine(self._origin)

        vecin = vecin.split()

        x_hat = self + pt1 #creates a vector which includes all the centers of the subsurface

        out = []
        #this for loop makes me cringe super hard
        for i in xrange(meri):
            try:
                temp = []
                for j in xrange(sagi):
                    inp = self.rot(vecin[i][j])
                    temp += [Cyl(geometry.Vecx(x_hat.x()[:,i,j]),
                                 self._origin,
                                 [2*stemp,2*mtemp],
                                 self.sagi.s,
                                 vec=[inp, self.norm.copy()],
                                 flag=self.flag)]
                out += [temp]
            except IndexError:
                inp = self.rot(vecin[i])
                out += [Cyl(geometry.Vecx(x_hat.x()[:,i]),
                            self._origin,
                            [2*stemp,2*mtemp],
                            self.norm.s,
                            vec=[inp, self.norm.copy()],
                            flag=self.flag)]
                

        return out
Exemplo n.º 6
0
def extract_BAFheatmap(data, output_filename_base):
    BAF_counts_min = constants.BAF_COUNTS_MIN
    BAF_counts_max = constants.BAF_COUNTS_MAX    

    outheatmap_dir_name = output_filename_base + '.MixClone.heatmap'
    if os.path.exists(outheatmap_dir_name) == False:
        os.mkdir(outheatmap_dir_name)
        
    seg_num = data.seg_num
    
    for j in range(0, seg_num):
        BAF_counts_j = data.segments[j].BAF_counts
        seg_name_j = data.segments[j].name
        BAF_counts_sub = BAF_counts_j[BAF_counts_min:BAF_counts_max, BAF_counts_min:BAF_counts_max]
        color_max_j = BAF_counts_sub.max()
        
        print 'Plotting segment {0}...'.format(seg_name_j)
        sys.stdout.flush()
        
        plt.figure(figsize=(8,8), dpi = 150)
        plt.xlim((0, 100))
        plt.ylim((0, 100))
        plt.xticks(sp.linspace(0, 100, 11), sp.linspace(0, 1, 11))
        plt.yticks(sp.linspace(0, 100, 11), sp.linspace(0, 1, 11))
        plt.xlabel('Tumor sample B allele frequency')
        plt.ylabel('Normal sample B allele frequency')
        plt.imshow(BAF_counts_j, vmin = 0, vmax = max(1, color_max_j))
        cbar = plt.colorbar(ticks=[0, color_max_j], orientation='vertical', shrink=0.78)
        cbar.ax.set_yticklabels(['0', '>= ' + str(int(color_max_j))])
        plt.savefig('./' + outheatmap_dir_name + '/' + seg_name_j, bbox_inches='tight')
Exemplo n.º 7
0
def extract_seg_plot(data, output_filename_base):
    subclone_plot_file_name = output_filename_base + '.MixClone.segplot.png'
    
    subclone_prev_lst = []
    copynumber_lst = []
    seg_num = data.seg_num

    print "Extracting segments plot file..."
    sys.stdout.flush()

    for j in range(0, seg_num):
        if data.segments[j].baseline_label == True or data.segments[j].allele_type == 'PM':
            continue
        subclone_prev_lst.append(data.segments[j].subclone_prev)
        copynumber_lst.append(data.segments[j].copy_number)

    X = len(subclone_prev_lst)
    
    plt.figure(figsize=(8,8), dpi = 150)
    plt.plot(range(1, X+1), subclone_prev_lst, 'o')
    plt.xlim(0, X+1)
    plt.ylim(0, 1)
    plt.xlabel('Copy number')
    plt.ylabel('Subclonal cellular prevalence')
    plt.xticks(sp.linspace(1, X, X), copynumber_lst)
    plt.yticks(sp.linspace(0, 1, 11), ['0%', '10%', '20%', '30%', '40%', '50%', '60%', '70%', '80%', '90%', '100%'])
    plt.savefig(subclone_plot_file_name, bbox_inches='tight')
Exemplo n.º 8
0
def draw_cubic_bezier(p0,p1,p2,p3):
	global curr_pos, curr_vel, time, fig, ax, time_per_unit, meters_per_second, time_between
	t0 = sp.linspace(0,0,1)
	t1 = sp.linspace(1,1,1)

	# draw cubic bezier curve
	
	#Setup the parameterisation
	seg_length = bezier_cubic_length(p0, p1, p2, p3)
	num_points = int(seg_length*meters_per_unit*pts_per_meter)
	if num_points < min_pts: num_points = min_pts
	T_max = 1.0
	t = sp.linspace(0,1,num_points)

	#Use the Cubic Bezier formula

	# add the position (Bx,By)
	Bx, By, Bz = bezier_cubic(p0, p1, p2, p3, t)

	# add the velocity (Bdx,Bdy)
	Bdx, Bdy, Bdz = bezier_cubic_dt(p0, p1, p2, p3, t)

	dxi, dyi, dzi = bezier_cubic_dt(p0, p1, p2, p3, t0)
	dxf, dyf, dzf = bezier_cubic_dt(p0, p1, p2, p3, t1)

	continuous = is_continuous(p0, [dxi[0], dyi[0], dzi[0]], [dxf[0], dyf[0], dzf[0]])

	#Plot the Bezier curve
	ax.plot(Bx, By, "k")
	

	# Add to trajectory msg
	P = np.array([Bx,By,Bz])
	V = np.array([Bdx,Bdy,Bdz])

	# find the duration of the curent segment at constant velocity
	duration = seg_length*meters_per_unit/meters_per_second

	times = []

	# allow time to stop if not continuous path
	if not continuous:			
		P = np.insert(P,0,P[:,0],axis=1)
		V = np.insert(V,0,[0.0,0.0,0.0],axis=1)
		time += time_between/2.0
		times.append(time)
		time += time_between/2.0

	# find the duration of a piece of the segment at constant velocity
	seconds_per_unit = meters_per_unit/meters_per_second
	for curr_t in t:
		dt = bezier_cubic_length(p0, p1, p2, p3, ti=0.0, tf=curr_t)*seconds_per_unit
		times.append(time + dt)

	# ax.plot(times, Bx, "r")
	# ax.plot(times, By, "g")
	# ax.plot(times, Bz, "b")

	add_to_plane_traj_msg(P,V,times)
	time += duration
def uvToELz_grid(ulinspace,vlinspace,R=1.,t=-4.,pot='bar',beta=0.,
            potparams=(0.9,0.01,25.*_degtorad,.8,None)):
    """
    NAME:
       uvToELz_grid
    PURPOSE:
       calculate uvToLz on a grid in (u,v)
    INPUT:
       ulinspace, vlinspace - build the grid using scipy's linspace with
                              these arguments
       R - Galactocentric Radius
       t - time to integrate backwards for 
           (interpretation depends on potential)
       pot - type of non-axisymmetric, time-dependent potential
       beta - power-law index of rotation curve
       potparams - parameters for this potential
    OUTPUT:
       final (E,Lz) on grid [nus,nvs,2]
       E=E/vo^2; Lz= Lz/Ro/vo
    HISTORY:
       2010-03-01 - Written - Bovy (NYU)
    """
    us= sc.linspace(*ulinspace)
    vs= sc.linspace(*vlinspace)
    nus= len(us)
    nvs= len(vs)
    out= sc.zeros((nus,nvs,2))
    for ii in range(nus):
        for jj in range(nvs):
            tmp_out= uvToELz(UV=(us[ii],vs[jj]),R=R,t=t,pot=pot,beta=beta,potparams=potparams)
            out[ii,jj,0]= tmp_out[0]
            out[ii,jj,1]= tmp_out[1]
    return out
def plotDecisionBoundary(data, X, theta):
    """
    Plots the data points X and y into a new figure with the
    decision boundary defined by theta
    """
    plotData(data)
    if X.shape[1] <= 3:
        plot_x = sp.array([min(X[:, 1]), max(X[:, 1])])
        plot_y = (-1.0 / theta[2]) * (theta[1] * plot_x + theta[0])
        plt.plot(plot_x, plot_y)
        plt.axis([30, 100, 30, 100])
    else:
        u = sp.linspace(-1, 1.5, 50)
        v = sp.linspace(-1, 1.5, 50)
        z = sp.zeros((len(u), len(v)))

        for i in range(0, len(u)):
            for j in range(0, len(v)):
                z[i, j] = (mapFeature(sp.array([u[i]]), sp.array([v[j]]))).dot(theta)

        z = z.T # important to transpose z before calling contour

        u, v = sp.meshgrid(u, v)

        plt.contour(u, v, z, [0.0, 0.0])
Exemplo n.º 11
0
 def loadImageAsGreyScale(self, subscriber=0):
     im = Image.open(self.paramFilename.value)
     if im.mode == "I;16":
         im = im.convert("I")
         data = scipy.misc.fromimage(im).astype("int16")
     else:
         data = scipy.misc.fromimage(im, flatten=True)
     Ny, Nx = data.shape
     xUnit = Quantity(self.paramXScale.value.encode("utf-8"))
     xAxis = DataContainer.FieldContainer(
         scipy.linspace(0.0, xUnit.value, Nx, True), xUnit / xUnit.value, longname="x-coordinate", shortname="x"
     )
     if self.paramYScale.value == "link2X":
         yUnit = xUnit * float(Ny) / Nx
     else:
         yUnit = Quantity(self.paramYScale.value.encode("utf-8"))
     yAxis = DataContainer.FieldContainer(
         scipy.linspace(0.0, yUnit.value, Ny, True), yUnit / yUnit.value, longname="y-coordinate", shortname="y"
     )
     try:
         FieldUnit = Quantity(self.paramFieldUnit.value.encode("utf-8"))
     except AttributeError:
         FieldUnit = self.paramFieldUnit.value
     result = DataContainer.FieldContainer(
         data, FieldUnit, longname="Image", shortname="I", dimensions=[yAxis, xAxis]
     )
     result.seal()
     return result
Exemplo n.º 12
0
def create_grid(r_in, r_out, nshell, space = 'powerlaw1', end = True):
    # function to create grid
    if space == 'log10':
        from scipy import log10, logspace
        # get the exponent of the start- and
        # stop-radius in input units
        start = [log10(r_in), 0][r_in == 0]
        stop = log10(r_out)
        radii = logspace(start, stop, num=nshell, endpoint=end)
    elif space == "powerlaw1":
        from scipy import arange
        radii = r_in * (r_out/r_in)**(arange(nshell)/(nshell - 1.0))
    elif space == 'linear':
        from scipy import linspace
        # linearly spaced grid
        radii = linspace(r_in, r_out, num=nshell, endpoint=end)
    elif space == 'powerlaw2':
        from scipy import linspace
        # first check if coefficients to the power-law was given
        #~ if 'exp' in kwargs:
            #~ p_exp = kwargs['exp']
        #~ else: # if not, set it to 2, i.e. r^2
            #~ p_exp = 2
        radii = r_in + (r_out - r_in)*(linspace(r_in, r_out, num=nshell, endpoint=end)/(r_out))**2
        #pr_int('Not implemented yet.')
        #raise ParError(spaced)
    else:
        raise Exception(space)
    return radii
Exemplo n.º 13
0
def getImageDescriptor(model, im, conf):
	im = standardizeImage(im)
	height, width = im.shape[:2]
	numWords = model.vocab.shape[1]
	frames, descrs = getPhowFeatures(im, conf.phowOpts)
	# quantize appearance
	if model.quantizer == 'vq':
		binsa, _ = vq(descrs.T, model.vocab.T)
	elif model.quantizer == 'kdtree':
		raise ValueError('quantizer kdtree not implemented')
	else:
		raise ValueError('quantizer {0} not known or understood'.format(model.quantizer))
	hist = []
	for n_spatial_bins_x, n_spatial_bins_y in zip(model.numSpatialX, model.numSpatialX):
		binsx, distsx = vq(frames[0, :], linspace(0, width, n_spatial_bins_x))
		binsy, distsy = vq(frames[1, :], linspace(0, height, n_spatial_bins_y))
		# binsx and binsy list to what spatial bin each feature point belongs to
		if (numpy.any(distsx < 0)) | (numpy.any(distsx > (width/n_spatial_bins_x+0.5))):
			print ("something went wrong")
			import pdb; pdb.set_trace()
		if (numpy.any(distsy < 0)) | (numpy.any(distsy > (height/n_spatial_bins_y+0.5))):
			print ("something went wrong")
			import pdb; pdb.set_trace()
		# combined quantization
		number_of_bins = n_spatial_bins_x * n_spatial_bins_y * numWords
		temp = arange(number_of_bins)
		# update using this: http://stackoverflow.com/questions/15230179/how-to-get-the-linear-index-for-a-numpy-array-sub2ind
		temp = temp.reshape([n_spatial_bins_x, n_spatial_bins_y, numWords])
		bin_comb = temp[binsx, binsy, binsa]
		hist_temp, _ = histogram(bin_comb, bins=range(number_of_bins+1), density=True)
		hist.append(hist_temp)
	
	hist = hstack(hist)
	hist = array(hist, 'float32') / sum(hist)
	return hist
Exemplo n.º 14
0
 def loadImageAsGreyScale(self, subscriber=0):
     im = PIL.Image.open(self.paramFilename.value)
     if im.mode == "I;16":
         im = im.convert("I")
         data = scipy.misc.fromimage(im).astype("int16")
     else:
         data = scipy.misc.fromimage(im, flatten=True)
     Ny, Nx = data.shape
     xUnit = parseFCUnit(self.paramXScale.value)
     xAxis = DataContainer.FieldContainer(
         scipy.linspace(0.0, self._getScalar(xUnit), Nx, True),
         xUnit / self._getScalar(xUnit),
         longname="x-coordinate",
         shortname="x",
     )
     if self.paramYScale.value == "link2X":
         yUnit = xUnit * float(Ny) / Nx
     else:
         yUnit = parseFCUnit(self.paramYScale.value)
     yAxis = DataContainer.FieldContainer(
         scipy.linspace(0.0, self._getScalar(yUnit), Ny, True),
         yUnit / self._getScalar(yUnit),
         longname="y-coordinate",
         shortname="y",
     )
     fieldUnit = parseFCUnit(self.paramFieldUnit.value)
     result = DataContainer.FieldContainer(
         data, fieldUnit, longname="Image", shortname="I", dimensions=[yAxis, xAxis]
     )
     result.seal()
     return result
Exemplo n.º 15
0
def volweight(numsplit=(3,3), factor=1, fact2=None, eq='/home/ian/python/g1120824019.01400'):

    b =  TRIPPy.Tokamak(eqtools.EqdskReader(gfile=eq))
    
    rgrid = b.eq.getRGrid()
    zgrid = b.eq.getZGrid()
    rgrid = scipy.linspace(rgrid[0],rgrid[-1],len(rgrid)*factor)
    zgrid = scipy.linspace(zgrid[0],zgrid[-1],len(zgrid)*factor)
    
    twopi2 = twopi(b)
    
    surfs = twopi2[0].split(numsplit[0],numsplit[1])

    out = scipy.zeros((len(rgrid)-1,len(zgrid)-1))

    for i in surfs:
        for j in i:
            surf2 = j
            if fact2 is None:
                surf2 = j
            else:
                surf2 = j.split(fact2,fact2)

            beam = TRIPPy.beam.multiBeam(surf2,twopi2[1])
            b.trace(beam)
            #TRIPPy.plot.mayaplot.plotLine(beam)
            out += TRIPPy.beam.volWeightBeam(beam,rgrid,zgrid)

    
    return out
Exemplo n.º 16
0
 def make_voltage_list(self,start,stop,number_points,bowtie=False):
      """ Makes a voltage sweep list given stop,start,number_of_points
      and a boolen that determines if all sweeps begin and end on zero"""
      if not bowtie:
         try:
             if (type(start)!=float or type(stop)!=float or type(number_points)!=float):
                 [start,stop,number_points]=map(lambda x: float(x),[start,stop,number_points])
             voltage_array=linspace(start,stop,number_points)
             voltage_list=voltage_array.tolist()
             return voltage_list
         except:
             print "make_voltage_list failed"
      elif bowtie:
         try:
             if (type(start)!=float or type(stop)!=float or type(number_points)!=float):
                 [start,stop,number_points]=map(lambda x: float(x),[start,stop,number_points])
             array_1=linspace(float(0),start,number_points)
             list_1=array_1.tolist()
             array_2=linspace(float(0),stop,number_points)
             list_2=array_2.tolist()
             voltage_list=array_1.tolist()
             list_1.reverse()
             voltage_list=voltage_list+list_1
             voltage_list=voltage_list+list_2
             list_2.reverse()
             voltage_list=voltage_list+list_2
             return voltage_list 
         except:
             raise
             print "make_voltage_list failed"    
Exemplo n.º 17
0
def add_intron_patch2(ax, start, stop, cnt, color='green'):
    ### compute a quadratic function through the three points

    ### we set the first root to 0 and shift only the plotting ...
    x2 = ((stop - start) / 2.0)
    x3 = float(stop - start)

    ### compute coefficients
    #z = float((x1*x1*x2 + x1*x3*x3 + x2*x2*x3) - (x3*x3*x2 + x2*x2*x1 + x1*x1*x3))
    z = float((x2*x2*x3) - (x3*x3*x2))
    if z == 0:
        return

    #a = float(cnt) * (x3 - x1) / z
    #b = float(cnt) * ((x1*x1) - (x3*x3)) / z
    #c = float(cnt) * ((x1*x3*x3) - (x1*x1*x3)) / z
    a = float(cnt) * x3 / z
    b = float(cnt) * (-1*(x3*x3)) / z

    ### get points
    #x = sp.linspace(start, stop, 100)
    x = sp.linspace(0, stop-start, 100)
    #y = (a*x*x) + (b*x) + c
    y = (a*x*x) + (b*x)
    ax.plot(sp.linspace(start, stop, 100), y, '-', color=color)
def grid(x, y, z, resX=100, resY=100):
    "Convert 3 column data to matplotlib grid"
    xi = sp.linspace(min(x), max(x), resX)
    yi = sp.linspace(min(y), max(y), resY)
    Z = griddata(x, y, z, xi, yi, interp='linear')
    X, Y = sp.meshgrid(xi, yi)
    return X, Y, Z
Exemplo n.º 19
0
def plot_median_errors(RefinementLevels):
        for i in RefinementLevels[0].cases:
            x =[];
            y =[];
            print "Analyzing median error on: ", i ;
            for r in RefinementLevels:                
                x.append(r.LUT.D_dim*r.LUT.P_dim)
                r.get_REL_ERR_SU2(i)
                y.append(r.SU2[i].median_ERR*100)
            
            x = sp.array(x)
            y = sp.array(y)            
            y = y[sp.argsort(x)]
            x = x[sp.argsort(x)]
                                    
            LHM = sp.ones((len(x),2))
            RHS = sp.ones((len(x),1))            
            LHM[:,1] = sp.log10(x)
            RHS[:,0] = sp.log10(y)

            sols = sp.linalg.lstsq(LHM,RHS)
            b = -sols[0][1]
            plt.loglog(x,y, label='%s, %s'%(i,r'$O(\frac{1}{N})^{%s}$'%str(sp.around(b,2))), basex=10, basey=10, \
                       subsy=sp.linspace(10**(-5), 10**(-2),20),\
                       subsx=sp.linspace(10**(2), 10**(5),50))
            
            #for r in RefinementLevels:                
               # x.append(r.LUT.D_dim*r.LUT.P_dim)
              #  r.get_REL_ERR_SciPy(i)
             #   y.append(r.SciPy[i].median_ERR*100)
            #plt.plot(x,y, label='SciPy: %s'%i)
        plt.grid(which='both')
        plt.xlabel('Grid Nodes (N)')
        plt.ylabel('Median relative error [%]')
        return;
Exemplo n.º 20
0
    def generateNodesAdaptive(self):
        innerDomainSize = self.innerDomainSize
        innerMeshSize   = self.innerMeshSize
        numberElementsInnerDomain = innerDomainSize/innerMeshSize
	assert(numberElementsInnerDomain < self.numberElements)
        domainCenter = (self.domainStart+self.domainEnd)/2
        nodes0 = np.linspace(domainCenter,innerDomainSize/2.0,(numberElementsInnerDomain/2.0)+1.0)
        nodes0 = np.delete(nodes0,-1)
        numberOuterIntervalsFromDomainCenter = (self.numberElements - numberElementsInnerDomain)/2.0
        const = np.log2(innerDomainSize/2.0)/0.5
        exp = np.linspace(const,np.log2(self.domainEnd*self.domainEnd),numberOuterIntervalsFromDomainCenter+1)
        nodes1 = np.power(np.sqrt(2),exp)
        nodesp = np.concatenate((nodes0,nodes1))
        nodesn = -nodesp[::-1]
        nodesn = np.delete(nodesn,-1)
        linNodalCoordinates = np.concatenate((nodesn,nodesp))
        nodalCoordinates = 0

        #Introduce higher order nodes
        if self.elementType == "quadratic" or self.elementType == "cubic":
           if self.elementType == "quadratic":
              numberNodesPerElement = 3 
           elif self.elementType == "cubic":
              numberNodesPerElement = 4

           for i in range(0,len(linNodalCoordinates)-1):
              newnodes = np.linspace(linNodalCoordinates[i],linNodalCoordinates[i+1],numberNodesPerElement)
              nodalCoordinates = np.delete(nodalCoordinates,-1)
              nodalCoordinates = np.concatenate((nodalCoordinates,newnodes))

        else:
           nodalCoordinates = linNodalCoordinates
    
        return nodalCoordinates
Exemplo n.º 21
0
def genBG(img, mask):
    x=[]
    y=[]
    z=[]
    w=[]
    
    #while len(x)<500:
    #    i=random.randrange(img.shape[0])
    #    j=random.randrange(img.shape[1])
     
    for i in linspace(0, img.shape[0]-1, 20): 
      for j in linspace(0, img.shape[1]-1, 20): 
        i=int(i)
        j=int(j)
        
        if mask!=None and mask[i, j]==0.0:
            continue
        a=img[max(0, i-10):i+10, max(0, j-10):j+10]
        #print sqrt(a.sum()), a.std()
        
        x.append(1.0*i)
        y.append(1.0*j)
        z.append(img[i, j])
        w.append(1.0/a.std())
        
    
    
    s=scipy.interpolate.bisplrep(x, y, z, w=w, xb=0,  xe=img.shape[0], yb=0, ye=img.shape[1], s=1e3)
    BG=scipy.interpolate.bisplev(arange(img.shape[0]), arange(img.shape[1]), s)
    
    return BG
def plot_disc_norm():
    x = sp.linspace(-3,3,100);
    y = st.norm.pdf(x,0,1);
    fig, ax = plt.subplots()
    fig.canvas.draw()
    
    ax.plot(x,y)
    
    fill1_x = sp.linspace(-2,-1.5,100)
    fill1_y = st.norm.pdf(fill1_x,0,1)
    fill2_x = sp.linspace(-1.5,-1,100)
    fill2_y = st.norm.pdf(fill2_x,0,1)
    ax.fill_between(fill1_x,0,fill1_y,facecolor = 'blue', edgecolor = 'k',alpha = 0.75)
    ax.fill_between(fill2_x,0,fill2_y,facecolor = 'blue', edgecolor = 'k',alpha = 0.75)
    for label in ax.get_yticklabels():
        label.set_visible(False)
    for tick in ax.get_xticklines():
        tick.set_visible(False)
    for tick in ax.get_yticklines():
        tick.set_visible(False)
    
    plt.rc("font", size = 16)
    plt.xticks([-2,-1.5,-1])
    labels = [item.get_text() for item in ax.get_xticklabels()]
    labels[0] = r"$v_k$"
    labels[1] = r"$\varepsilon_k$"
    labels[2] = r"$v_{k+1}$"
    ax.set_xticklabels(labels)
    plt.ylim([0, .45])

    
    plt.savefig('discnorm.pdf')
Exemplo n.º 23
0
def test_interpolateArray():
	grid_x = scipy.linspace(1, 5, 20)
	grid_y = scipy.linspace(-1, 1, 10)
	def fn(x):
		return scipy.sin(x[0] + x[1])
	((xlist, ylist), f) = applyGrid([grid_x, grid_y], fn)
	fig = plt.figure()
	ax = Axes3D(fig)	
	ax.scatter(xlist, ylist, f.ravel())
	
	grid2_x = scipy.linspace(1, 5, 40)
	grid2_y = scipy.linspace(-1, 1, 20)
	f2 = interpolateArray([grid_x, grid_y], [grid2_x, grid2_y], f)
	xy_list = itertools.product(grid2_x, grid2_y)
	(xlist2, ylist2) = zip(*xy_list)	
	fig = plt.figure()	
	ax = Axes3D(fig)
	ax.scatter(xlist2, ylist2, f2.ravel())
	
	grid3_x = grid_x
	grid3_y = grid_y
	f3 = interpolateArray([grid2_x, grid2_y], [grid3_x, grid3_y], f2)
	xy_list = itertools.product(grid3_x, grid3_y)
	(xlist3, ylist3) = zip(*xy_list)	
	fig = plt.figure()	
	ax = Axes3D(fig)	
	ax.scatter(xlist3, ylist3, f3.ravel())	
	
	
	
	
	
	
	
Exemplo n.º 24
0
	def draw_plot(self):
		self.axes.clear()
		self.histax.clear()
		global mode
		if mode == 'hsv':
			self.axes.set_xlabel('Hue')
			self.axes.set_ylabel('Saturation')
			self.axes.set_zlabel('Value')
			tubepixels = np.array(list(self.hsv[greenloc[0], greenloc[1]] for greenloc in coloredpixels(self.mask, (0,255,0))))
			nontubepixels = np.array(list(self.hsv[redloc[0], redloc[1]] for redloc in coloredpixels(self.mask, (0,0,255))))
		else:
			self.axes.set_xlabel('Blue')
			self.axes.set_ylabel('Green')
			self.axes.set_zlabel('Red')
			tubepixels = np.array(list(self.smallimg[greenloc[0], greenloc[1]] for greenloc in coloredpixels(self.mask, (0,255,0))))
			nontubepixels = np.array(list(self.smallimg[redloc[0], redloc[1]] for redloc in coloredpixels(self.mask, (0,0,255))))
		onehundredtube = [int(x) for x in scipy.linspace(0,len(tubepixels)-1, 500)]
		onehundrednon = [int(x) for x in scipy.linspace(0,len(nontubepixels)-1, 500)]
		if len(tubepixels):
			self.axes.scatter(tubepixels[onehundredtube,0], tubepixels[onehundredtube,1], tubepixels[onehundredtube,2], c='g')
			self.histax.hist(tubepixels[onehundredtube, 1], 100, normed=1, facecolor='green')
		if len(nontubepixels):
			self.axes.scatter(nontubepixels[onehundrednon,0], nontubepixels[onehundrednon,1], nontubepixels[onehundrednon,2], c='r')
			self.histax.hist(nontubepixels[onehundrednon, 1], 100, normed=1, facecolor='red')
		self.figure.canvas.draw()
		self.histfig.canvas.draw()
Exemplo n.º 25
0
    def testSnrFuncs(self):
        """test for signal to noise ratio functions"""

        # trivial
        data_triv = sp.ones((3, 10))
        snr_triv_test = sp.ones(3)
        assert_equal(
            snr_peak(data_triv, 1.0),
            snr_triv_test)
        assert_equal(
            snr_power(data_triv, 1.0),
            snr_triv_test)
        assert_equal(
            snr_maha(data_triv, sp.eye(data_triv.shape[1])),
            snr_triv_test)

        # application
        data = sp.array([
            sp.sin(sp.linspace(0.0, 2 * sp.pi, 100)),
            sp.sin(sp.linspace(0.0, 2 * sp.pi, 100)) * 2,
            sp.sin(sp.linspace(0.0, 2 * sp.pi, 100)) * 5,
        ])
        assert_equal(
            snr_peak(data, 1.0),
            sp.absolute(data).max(axis=1))
        assert_equal(
            snr_power(data, 1.0),
            sp.sqrt((data * data).sum(axis=1) / data.shape[1]))
        assert_almost_equal(
            snr_maha(data, sp.eye(data.shape[1])),
            sp.sqrt((data * data).sum(axis=1) / data.shape[1]))
Exemplo n.º 26
0
def test_classic_newton():
    op = p.OptimizationProblem(c.chebyquad)
    guess=linspace(0,1,4)
    cn  = p.ClassicNewton(op)
    assert near(sol4,(cn.optimize(guess)))
    guess=linspace(0,1,8)
    assert near(sol8,(cn.optimize(guess)))
Exemplo n.º 27
0
def test_newton_exact_line_search():
    op = p.OptimizationProblem(c.chebyquad)
    guess=linspace(0,1,4)
    cn  = p.NewtonExactLine(op)
    assert near(sol4,(cn.optimize(guess)))
    guess=linspace(0,1,8)
    assert near(sol8,(cn.optimize(guess)))
Exemplo n.º 28
0
def subdivide(g, rmin, rmax, m):
    """
    Subdivide the given interval by equal integrals of g.

    **example**
     >>> g = lambda r : r**2
     >>> rmin = 0.0
     >>> rmax = 1.0
     >>> m = 2
     >>> r = subdivide(g, rmin, rmax, m)
     >>> abs(r - array([0.0, .5**(1./3.), 1.0])).sum() <= 1e-4
     True
    """
    r = sp.linspace(rmin, rmax, m+1)

    # total integral value
    tot = quad(g, rmin, rmax)[0]
    cuts = sp.linspace(0.0, tot, m+1)[1:-1]
    
    # define intervals r_n to r_n+1 to give equal area under g(r)
    r[1:-1] = [brentq((lambda r_: quad(g, rmin, r_)[0]-cut), rmin, rmax,
                      xtol=1.0e-4)
                for cut in cuts]
    # return the sequence of subinterval boundaries
    return r
Exemplo n.º 29
0
 def get_znodes(self):
     " Compute a nodes for a log-lower and linear-upper grid. "
     zlower = sp.exp(sp.linspace(sp.log(self.zmin), sp.log(self.zmid), self.Nlo))
     zupper = sp.linspace(self.zmid, self.zmax, self.Nhi)
     znodes = sp.concatenate([zlower, 
                              zupper[1:]])
     return znodes
Exemplo n.º 30
0
def joint(dataA, dataB, g, minLimitA, maxLimitA, minLimitB, maxLimitB, alpha=2):
    '''Calculates a joint PDF based on the DEFT algorithm.

    Keyword arguments:
    dataA           data variable A NxP
                        N = elements
                        P = population
    dataB           data variable B NxP
                        N = elements
                        P = population
    minLimitA       Minimal possible value for variable A
    maxLimitA       Maximal possible value for variable A
    minLimitB       Minimal possible value for variable B
    maxLimitB       Maximal possible value for variable B
    g               Number of bins on which to compute the estimated density
    alpha           The smoothness parameter, specifying which derivative of the filed is constrained by the prior. May be any integer >= 1.
    Returns:    
                    pdf NxB
                        N = elements
                        BA = Bin A
                        BB = Bin B
    '''
    assert alpha >= 1, "Alpha must be greater or equal than 1"
    assert g >= 1, "Number of bins must be greater or equal than 1"
    result = np.zeros((dataA.shape[0], g, g))
    bbox = [minLimitA, maxLimitA, minLimitB, maxLimitB]
    xgridA = sp.linspace(bbox[0], bbox[1], g)
    xgridB = sp.linspace(bbox[2], bbox[3], g)

    for i in xrange(dataA.shape[0]):
        if len(dataA[i,:]) > 1 and len(dataB[i,:]) > 1:
            da = deft_2d(dataA[i,:], dataB[i,:], bbox, G=g, alpha=alpha)(xgridA, xgridB)
            result[i, :, :] = da

    return result
    denominator = math.factorial(k) * math.factorial(N - k)
    combo_count = numerator / denominator

    return combo_prob * combo_count


outcome_probs = [find_probability(30, i, .39, .61) for i in outcome_counts]

## 6. Simplifying the computation ##

import scipy
from scipy import linspace
from scipy.stats import binom

# Create a range of numbers from 0 to 30, with 31 elements (each number has one entry).
outcome_counts = linspace(0, 30, 31)
outcome_probs = binom.pmf(outcome_counts, 30, 0.39)
plt.bar(outcome_counts, outcome_probs)
plt.show()

## 8. Computing the mean of a probability distribution ##

dist_mean = 30 * .39

## 9. Computing the standard deviation ##

import math
dist_stdev = math.sqrt(30 * .39 * .61)

## 10. A different plot ##
Exemplo n.º 32
0
    def dict_value(self, dictionary):
        return dictionary.values()[0]

    def dict_key(self, dictionary):
        return dictionary.keys()[0]


if __name__ == "__main__":

    #from scipy import rand
    app = QApplication(sys.argv)

    # make x data
    num = 100
    x = S.linspace(-10, 10, num=num)
    distancePerLag = x[1] - x[0]

    # make two gaussians, with different means
    offset = 2.0
    y1 = S.exp(-x**2 / 8.0)
    y2 = S.exp(-(x - offset)**2 / 1.0)

    #ydict = {'y2':y2, 'y3':y3}
    #ydict = {'y2':y2, 'y3':y3, 'y4':y4, 'y5':y5, 'y6':y6,'y7':y7, 'y8':y8}
    totaldict = {'x': x, 'y1': y1, 'y2': y2}

    shell = pyQTShell(varDict=totaldict)
    #plot = pyQTShell(varDict = totaldict)
    #plot = pyQTShell()
    shell.show()
Exemplo n.º 33
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 24 11:09:26 2019

@author: arianafm
"""
#Figura 2:

import matplotlib.pyplot as plt
import scipy as sp

plt.figure(2)
#linspace : divide el eje
ejeX = sp.linspace(10, 50, 20)

g = sp.sin(ejeX)

plt.plot(ejeX, g, 'r--')

plt.show()
Exemplo n.º 34
0
#if you want to include the natural population growths and deaths
#the natual population increase each year
#zeta = .0179
#gamma = .0035

# Initial condition
S0 = 5832710
I0 = 58
R0 = 15

Y0 = [S0, I0, R0]

tMax = 2

# Time vector for solution
T = scipy.linspace(0, tMax, 10)


# This defines a function that is the right-hand side of the ODEs
# Warning!  Whitespace at the begining of a line is significant!
def rhs(Y, t, alpha, beta, delta):
    '''
    SIR model.
    
    This function gives the right-hand sides of the ODEs.
    '''

    # Convert vector to meaningful component vectors
    # Note: Indices start with index 0, not 1!
    S = Y[0]
    I = Y[1]
Exemplo n.º 35
0
    C = pops[1]
    dRdt = r * R - a * R * C
    dCdt = -z * C + e * a * R * C
    return sc.array([dRdt, dCdt])


print(type(dCR_dt))

# assign some parameter values
r = 1.
a = 0.1
z = 1.5
e = 0.75

# define the time vector
t = sc.linspace(0, 15, 1000)

# set the inital conditions for the two populations
R0 = 10
C0 = 5
RC0 = sc.array([R0, C0])

# now, numerically integrate this system forwards from these conditions
pops, infodict = intergrate.odeint(dCR_dt, RC0, t, full_output=True)
print(pops)
print(infodict.keys())

# plot it
import matplotlib.pylab as p

f1 = p.figure()
Exemplo n.º 36
0
# -*- coding: utf-8 -*-
#

import scipy
import scipy.stats
import matplotlib.pyplot as plt

from pandas import Series

x = scipy.linspace(0, 10, 11)

ex1 = scipy.stats.binom.pmf(x, n=10, p=0.5)
ex2 = scipy.stats.binom.pmf(x, n=10, p=0.1)

fig, axes = plt.subplots(2, 1, figsize=(8, 10))

# bar parameters : http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.bar
data1 = Series(ex1, index=x)
data1.plot(kind="bar",
           ax=axes[0],
           title="binomial distribution B(10,0.5)",
           width=1)

data2 = Series(ex2, index=x)
data2.plot(kind="bar",
           ax=axes[1],
           title="binomial distribution B(10,0.1)",
           width=1)

plt.show()
Exemplo n.º 37
0
# ----------------------------------------------------------------------
#   Module Tests
# ----------------------------------------------------------------------
# this will run from command line, put simple tests for your code here
if __name__ == '__main__':

    #imports
    import pylab as plt
    import matplotlib
    matplotlib.interactive(True)
    import scipy as sp
    import SUAVE
    from SUAVE.Core import Units

    #define array of sweep and deflection
    sweep_vec = sp.linspace(-10,30,20) * Units.deg
    deflection_vec = sp.linspace(0,50,6)* Units.deg

    dcl_slat = sp.zeros((len(sweep_vec),len(deflection_vec)))
    legend = ''

    for i in range(len(sweep_vec)):
        for j in range(len(deflection_vec)):
            sweep = sweep_vec[i]
            deflection = deflection_vec[j]
            dcl_slat[i,j] = compute_slat_lift(deflection,sweep)

    # ------------------------------------------------------------------
    #   Plotting Delta CL due to Slat vs Sweep angle
    # ------------------------------------------------------------------
    title = "Delta dCL_slat vs Wing sweep"
Exemplo n.º 38
0
def matrixPolyDecay(N, p, R=10):
    diagels = sp.zeros(N)
    diagels[0:R] = 1.
    diagels[R::] = (sp.linspace(2, N - R + 1, N - R))**(-p)
    A = sp.diag(diagels)
    return A
Exemplo n.º 39
0
def V25Vc(fname=fwind):
    fig = plt.figure(1, figsize=(8, 8))
    gs = gridspec.GridSpec(2, 1, height_ratios=[4, 1])
    ax1 = plt.subplot(gs[0])
    ax2 = plt.subplot(gs[1])
    if (FFORMAT == "OLD"):
        mvir, rvir, vinit, v25 = ioformat.rcol(fname, [1, 2, 3, 4],
                                               linestart=1)
    else:
        mvir, rvir, vinit, v25, rreturn = ioformat.rcol(fname, [1, 2, 3, 4, 5],
                                                        linestart=1)
    if (HALOMASS_CORRECTION == True):
        mvir = array(mvir) - log10(8.0)
        rvir = array(rvir) / 2.0
    vc = sqrt(pc.G * 10.**array(mvir) * ac.msolar /
              (array(rvir) * ac.kpc)) / 1.e5
    print "Mvir Range: ", min(mvir), max(mvir)
    print "Vc Range: ", min(vc), max(vc)
    # ax1.plot(vc[::100], v25[::100], "b.")
    # ax1.plot(vc2, v252, ".", color="teal")
    if (FFORMAT == "NEW"):
        # Rreturn < 0.25 Rvir!
        for i in range(len(v25)):
            if (0.0 < rreturn[i] < 0.25 * rvir[i]):
                v25[i] = -1
    plotmedian(vc, v25, "blue", nbins=15, ax=ax1, xmin=XMIN, xmax=XMAX)
    plotmedian(vc, vinit, "red", nbins=15, ax=ax1, xmin=XMIN, xmax=XMAX)
    xbins = logspace(log10(XMIN), log10(XMAX), XBINS)
    ybins = logspace(log10(YMIN), log10(YMAX), YBINS)
    xgrid, ygrid = meshgrid(xbins, ybins)
    z, edx, edy = histogram2d(vc, v25, bins=[xbins, ybins])
    z = z + 0.1
    z = z.T
    zf = ndimage.gaussian_filter(z, sigma=0.3, order=0)
    # cont = ax1.contour(xbins[1:], ybins[1:], zf, 10, colors="black")
    # cont = ax1.contourf(xbins[1:], ybins[1:], zf, CONTLEVELS, cmap=plt.cm.Purples, norm=LogNorm(vmin=z.min(), vmax=z.max()))
    # cont = ax1.contour(xbins[1:], ybins[1:], zf, CONTLEVELS, cmap=plt.cm.Reds, norm=LogNorm(vmin=z.min(), vmax=z.max()))
    # cont = ax1.contourf(xbins[1:], ybins[1:], zf, 6, cmap=plt.cm.Purples, vmin=z.min(), vmax=z.max())
    # ax1.plot(vc[::200], v25[::200], "k.", markersize=2)
    ax1.pcolor(xbins[1:],
               ybins[1:],
               zf,
               cmap=plt.cm.Purples,
               norm=LogNorm(vmin=z.min(), vmax=z.max()))
    xline = linspace(XMIN, XMAX, 100)
    y50line = 0.854 * xline**1.12
    y95line = 1.85 * xline**1.10
    ax1.plot(xline, y50line, "k-")
    ax1.plot(xline, y95line, "k--")
    ax2.set_xlabel(r"$V_c [km/s]$")
    ax1.set_ylabel(r"$V_{25} [km/s]$")
    ax1.set_xlim(XMIN, XMAX)
    ax1.set_ylim(YMIN, YMAX)
    # ax1.set_ylim(9.,12.)
    ax1.set_title(simname + ", Z = " + str(REDSHIFT))
    ax1.set_xscale("log")
    ax1.set_yscale("log")
    ax1.legend([r"$V_{25}$", r"$V_{init}$"], fontsize=16)
    fig.subplots_adjust(hspace=0)
    setp(ax1.get_xticklabels(), visible=False)
    # Count the fraction that makes NOT to R25
    FRAC_STEP = 25.
    frac = [0.] * int(XMAX / FRAC_STEP)
    Ncount = [0.] * int(XMAX / FRAC_STEP)
    x = linspace(10., XMAX, int(XMAX / FRAC_STEP)) - 5.
    for i in range(len(vc)):
        idx = int(vc[i] / FRAC_STEP)
        if (idx > int(XMAX / FRAC_STEP) - 1):
            idx = int(XMAX / FRAC_STEP) - 1
        Ncount[idx] += 1.
        if (v25[i] != -1):
            frac[idx] += 1.
        # if(FFORMAT == "NEW"):
        #     if(0. < rreturn[i] < 0.25 * rvir[i]):
        #         frac[idx] -= 1. # Rreturn < 0.25 Rvir!
    Ntot = sum(Ncount)
    for i in range(len(frac)):
        if (Ncount[i] > 0.):
            frac[i] = frac[i] / Ncount[i]
    ax2.plot(x, frac, "k.-")
    # ax2.plot(x, array(Ncount)/Ntot, "-", color="teal")
    Ncount_Norm = 2. * max(Ncount) / Ntot
    ax2.bar(x, (array(Ncount) / Ntot) / Ncount_Norm,
            align="center",
            width=0.8 * (x[1] - x[0]),
            color="grey")
    ax2.set_xlim(XMIN, XMAX)
    ax2.set_ylim(0., 1.1)
    ax2.set_xscale("log")
    ax2.xaxis.set_ticks([XMIN, 50., 100., 200., XMAX])
    ax2.xaxis.set_ticklabels([str(XMIN), "50", "100", "200", str(XMAX)])
    ax2.yaxis.set_ticks([0., 0.2, 0.4, 0.6, 0.8])
    ax2.set_ylabel(r"$f(R_{25} < R_{return})$")
    # plt.savefig("/home/shuiyao/161123V25VC.pdf")
    plt.show()
Exemplo n.º 40
0
def matrixExpDecay(N, q, R=10):
    diagels = sp.zeros(N)
    diagels[0:R] = 1.
    diagels[R::] = 10.**(-sp.linspace(1, N - R, N - R) * q)
    A = sp.diag(diagels)
    return A
button_rysuj.bind("<Button-1>", rysuj_on_click)
button_rysuj.pack(fill=X)

window.mainloop()

# warunki początkowe
nx = 5000  # number of points
nx_ghost = 2  # ghost cells

v = 1  # velocity
CFL = 0.95  # CFL number
CFL2 = CFL * CFL
nx = nx + nx_ghost

# generate space
x = sp.linspace(-2., 2., nx)
q = sp.linspace(0, 0, nx)

qnm1 = sp.linspace(0, 0, nx)
qn = sp.linspace(0, 0, nx)

dx = (max(x) - min(x)) / nx
dt = CFL * dx.min() / abs(v)


# schematy numeryczne
def ftcs():
    for i in range(nx_ghost, len(x) - nx_ghost):
        q[i] = q[i] + CFL * (q[i - 1] - q[i + 1]) / 2

Exemplo n.º 42
0
def euler_beam_frf(xin=0.22, xout=0.32, fmin=0.0, fmax=1000.0, zeta=0.02,
                   bctype=2, npoints=2001,
                   beamparams=np.array([7.31e10, 1 / 12 * 0.03 * .015 ** 3,
                                        2747.0, .015 * 0.03, 0.4])):
    """Frequency response function fo Euler-Bernoulli beam.

    Parameters
    ----------
    xin: float
        location of applied force
    xout: float
        location of displacement sensor
    fmin: float
        lowest frequency of interest
    fmax: float
        highest frequency of interest
    zeta: float
        damping ratio
    bctype: int
        bctype = 1 free-free
        bctype = 2 clamped-free
        bctype = 3 clamped-pinned
        bctype = 4 clamped-sliding
        bctype = 5 clamped-clamped
        bctype = 6 pinned-pinned
    beamparams: numpy array
        E, I, rho, A, L,
        Young's modulus, second moment of area, density, cross section area,
        length of beam
    npoints: int
        number of points for returned mode shape array

    Returns
    -------
    fout: numpy array
        array of driving frequencies (Hz)
    H: numpy array
        Frequency Response Function

    Examples
    --------
    >>> import matplotlib.pyplot as plt
    >>> import vibration_toolbox as vtb
    >>> _, _ = vtb.euler_beam_frf()

    """

    E = beamparams[0]
    I = beamparams[1]
    rho = beamparams[2]
    A = beamparams[3]
    L = beamparams[4]
    npoints = 2001
    i = 0
    w = sp.linspace(fmin, fmax, 2001) * 2 * sp.pi
    if min([xin, xout]) < 0 or max([xin, xout]) > L:
        print('One or both locations are not on the beam')
        return
    wn = sp.array((0, 0))
    # The number 100 is arbitrarily large and unjustified.
    a = sp.empty([npoints, 100], dtype=complex)
    f = sp.empty(100)

    while wn[-1] < 1.3 * (fmax * 2 * sp.pi):
        i = i + 1
        wn, xx, U = euler_beam_modes(n=i, bctype=bctype,
                                     beamparams=beamparams, npoints=5000)
        spl = UnivariateSpline(xx, U[:, i - 1])
        Uin = spl(xin)
        Uout = spl(xout)
        a[:, i - 1] = rho * A * Uin * Uout / \
            (wn[-1] ** 2 - w ** 2 + 2 * zeta * wn[-1] * w * sp.sqrt(-1))
        f[i] = wn[-1] / 2 / sp.pi
    a = a[:, 0:i]
    plt.figure()
    plt.subplot(211)
    plt.plot(w / 2 / sp.pi, 20 * sp.log10(sp.absolute(sp.sum(a, axis=1))), '-')
    # plt.hold('on')
    plt.plot(w / 2 / sp.pi, 20 * sp.log10(sp.absolute(a)), '-')
    plt.grid('on')
    plt.xlabel('Frequency (Hz)')
    plt.ylabel('FRF (dB)')
    axlim = plt.axis()

    plt.axis(axlim + sp.array([0, 0, -0.1 * (axlim[3] - axlim[2]),
                               0.1 * (axlim[3] - axlim[2])]))

    plt.subplot(212)
    plt.plot(w / 2 / sp.pi, sp.unwrap(sp.angle(sp.sum(a, axis=1))) /
             sp.pi * 180, '-')
    plt.plot(w / 2 / sp.pi, sp.unwrap(sp.angle(a)) / sp.pi * 180, '-')
    plt.grid('on')
    plt.xlabel('Frequency (Hz)')
    plt.ylabel('Phase (deg)')
    axlim = plt.axis()
    plt.axis(axlim + sp.array([0, 0, -0.1 * (axlim[3] - axlim[2]),
                               0.1 * (axlim[3] - axlim[2])]))
    plt.show()

    fout = w / 2 / sp.pi
    H = a
    return fout, H
ub = 3.0
f1 = lambda x: sc.sin(x)
f2 = lambda x: sc.cos(3 * x)
globres = 1000  #Resoltion of global discretisations
dnres = 5  # Resolution of the dir/neu alg discretisations
"""
Discretisation params
"""
dirDisc = "FDM"  # FDM,FEM,FVM
neuDisc = "FVM"  # FDM,FEM,FVM

#############################  PROGRAM ##############################
"""
Generate an approximation using global discretisation
"""
gx1 = sc.linspace(xa, xg, globres)
gx2 = sc.linspace(xg, xb, globres)
gsol = dn.efemfem.exactFEMFEM(gx1, gx2, ua, ub, lmd1, lmd2, f1, f2)
"""
Generate an approximation using the dir/neu algorithm 
"""

if (dirDisc == "FDM"):
    discdir = dn.fdm.FDM
elif (dirDisc == "FEM"):
    discdir = dn.fem.FEM
elif (dirDisc == "FVM"):
    discdir = dn.fvm.FVM
else:
    raise RuntimeError("Discretisations have to be FDM,FEM,FVM")
Exemplo n.º 44
0
#    return 1/sqrt(2*pi) * exp(-x**2/2)

#def cdf(x):
#    return (1 + erf(x/sqrt(2))) / 2

def skew(x,e=0,w=1,a=0):
    t = (x-e) / w
    #return 2 / w * pdf(t) * cdf(a*t)
    # You can of course use the scipy.stats.norm versions
    return 2 * norm.pdf(t) * norm.cdf(a*t)

if __name__ == '__main__':
    n = 2**10

    e = 1.0 # location
    w = 2.0 # scale

    x = linspace(-10,10,n) 

    for a in range(-3,4):
        p = skew(x,e,w,a)
        plot(x,p)

    fzz = skew(x,e,w,a) + norm.rvs(0,0.04,size=n) # fuzzy data

    def optm(l,x):
        return skew(x,l[0],l[1],l[2]) - fzz

    print leastsq(optm,[0.5,0.5,0.5],(x,))

    show()
Exemplo n.º 45
0
x = x[~sp.isnan(y)]  #只选择有效值
y = y[~sp.isnan(y)]
wuxiaozhi = sp.sum(sp.isnan(y))  #无效值
print(wuxiaozhi)


def error(f, x, y):
    return sp.sum((f(x) - y)**2)  #计算误差


fp1, residuals, rank, sv, rcond = sp.polyfit(x, y, 1, full=True)
print("Model parameters:%s" % fp1)  #系数
print(residuals)  #残差
f1 = sp.poly1d(fp1)
print(f1)  #创建方程式
print(error(f1, x, y))  #这个要重点理解

import matplotlib.pyplot as plt
fx = sp.linspace(0, x[-1], 1000)
plt.plot(fx, f1(fx), linewidth=4)  #线形图
plt.legend(["d=%i" % f1.order], loc="upper left")

plt.scatter(x, y)  #散点图
plt.title("这是一个测试")
plt.xlabel("Time")
plt.ylabel("Hits/Hour")
plt.xticks([w * 7 * 24 for w in range(10)],
           ["week %i" % w for w in range(10)])  #显示每个星期
plt.autoscale(tight=True)
plt.grid()
plt.show()
Exemplo n.º 46
0
    # Volumetric heat power (W/m3)
    q = 100

    kt = sp.zeros(n)
    Told = sp.ones(n) * (T_A + T_B) / 2
    # Iterative loop
    max_loops = 1000
    for k in range(max_loops):
        # Update kt
        for kk in range(n):
            kt[kk] = PropsSI('conductivity', 'P', 1e5, 'T', Told[kk] + 273.15,
                             'Air')
        # Solve linear system
        T, dx = solver(n, kt, Ac, L, T_A, T_B, q)
        # Check for convergence
        if sp.absolute((T - Told)).max() < 0.001:
            print("Converged after", k + 1, "iterations")
            break
        Told = T

    # Check if loop terminated
    if k == max_loops - 1:
        print("WARNING! Maximum number of iterations reached!")

    # Plot numerical  solution
    plt.plot(sp.linspace(dx / 2, L - dx / 2, n), T, "k--o", label="numerical")
    plt.legend()
    plt.xlim(0, L)

    print("END")
def _plotHistogram(analysis,
                   prop,
                   unit,
                   savePlotsDir,
                   useLog,
                   yMin,
                   yMax,
                   yList,
                   numCells,
                   typeList,
                   cellNames,
                   histogramSameYAxis=False,
                   plotLegend=True):

    # add 1.0, because need an extra axis for the legend
    extraSubplot = float(plotLegend)
    numHistRows = floor(sqrt(numCells + extraSubplot))
    numHistCols = int(ceil((numCells + extraSubplot) / numHistRows))
    numHistRows = int(numHistRows)
    if savePlotsDir:
        fig = pyplot.gcf()
        fig.clf()
    else:
        fig = pyplot.figure()
    histYMin = float('inf')
    histYMax = -histYMin

    # plot histograms
    for n, (cellType, props) in enumerate(
            zip(analysis['cellTypes'], analysis['properties'])):
        color = _colors[typeList.index(cellType)]
        yList = props[prop]
        axes = fig.add_subplot(numHistRows, numHistCols, n + 1)
        numBins = max(10, min(100, int(sqrt(len(yList)))))
        if useLog:
            bins = logspace(log10(min(yList)), log10(max(yList)), numBins)
        else:
            bins = linspace(min(yList), max(yList), numBins)
        axes.hist(yList, color=color, bins=bins, normed=True, edgecolor='none')

        if useLog:
            axes.set_xscale('log')
        # Note, this is NOT an error, because the histogram moves the box plot's
        # y-axis onto the x-axis:
        pyplot.xlim([yMin, yMax])
        yBot, yTop = pyplot.ylim()
        histYMin = min(histYMin, yBot)
        histYMax = max(histYMax, yTop)
        pyplot.title(cellNames[n])
        if unit:
            pyplot.xlabel(prop + ' (' + unit + ')')
        else:
            pyplot.xlabel(prop)
        axes.set_yticklabels([])

    if histogramSameYAxis:
        # set ylimits to be the same for all histograms
        for n in range(numCells):
            fig.add_subplot(numHistRows, numHistCols, n + 1)
            pyplot.ylim(histYMin, histYMax)

    pyplot.suptitle('Histogram of %s' % prop)
    if plotLegend:
        axes = fig.add_subplot(numHistRows, numHistCols, numCells + 1)
        axes.set_xticklabels([])
        axes.set_yticklabels([])
        axes.axis('off')
        fakeLines = []
        for color, cellType in zip(_colors, typeList):
            fakeLines += axes.plot([0, 0],
                                   color + '-',
                                   label=cellType,
                                   linewidth=4)
        pyplot.legend(loc='best')
        for fakeLine in fakeLines:
            fakeLine.set_visible(False)

    pyplot.tight_layout()
    pyplot.subplots_adjust(top=0.9)
    if savePlotsDir:
        # save the figure
        _saveCurrentFig(savePlotsDir, prop + ' Histogram')
Exemplo n.º 48
0
if os.path.isdir(cwd + '/result') == True:
    shutil.rmtree(cwd + '/result')

os.mkdir(cwd + '/result')

tempo = 1001
nodes = 1000
u = sp.zeros((tempo, nodes))

# with open('flowResult.csv', 'r') as csvfile:
#     plots = csv.reader(csvfile, delimiter=',')
#     for row in plots:

matriz = sp.loadtxt('flow-T.csv', delimiter=',')

x = sp.linspace(0, 1, len(matriz[-1]))
plt.figure(1)
plt.plot(matriz[0], matriz[-1])
plt.show()

exit()


# --------------------------------------------------
# Plot function
def defPlot(_xp, _yp, _n, _u, _yf, L, t):
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)
    # ax2 = fig.add_subplot(1,2,2)
    for i in range(_n):
        ax.scatter(_xp[i], _yp[i])
Exemplo n.º 49
0
    zp[1] = z[3]
    v = z[2:4]
    v[0] = v[0] - V
    vnorm = sp.sqrt(sp.dot(v, v))
    FD = (-CD * sp.dot(v, v) * v) / (vnorm)
    zp[2] = FD[0] / m
    zp[3] = (FD[1] / m) - g

    return zp


plt.figure(1)

for V in V:
    # Vector de tiempo
    t = sp.linspace(0, 5.6, 1001)

    # Parte en el origen
    vi = 100 * 1000 / 3600.
    z0 = sp.array([0, 0, vi, vi])

    sol = odeint(bala, z0, t)

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

    plt.plot(x, y)

plt.title("Trayectoria para distintos vientos")
plt.ylabel("Y (m)")
plt.xlabel("X (m)")
Exemplo n.º 50
0

# transpose for plotting
nlnm_vel_x,nlnm_vel_y = np.array(nlnm_vel).T
nhnm_vel_x,nhnm_vel_y = np.array(nhnm_vel).T
nlnm_accel_x,nlnm_accel_y = np.array(nlnm_accel).T
nhnm_accel_x,nhnm_accel_y = np.array(nhnm_accel).T

# convert table from period to frequency 
nlnm_vel_x = 1.0/nlnm_vel_x
nhnm_vel_x = 1.0/nhnm_vel_x
nlnm_accel_x = 1.0/nlnm_accel_x
nhnm_accel_x = 1.0/nhnm_accel_x

# Create time data for x axis based on ch_low length
x = sy.linspace(1/fs, len(ch_low)/fs, num=len(ch_low))

# scale Yuma output to (m/s)^2/Hz
ch_low = ch_low * 1.87e-9	# 1.87nm/s/count

# get the velocity PSD first
psd_vel, f_vel = plt.mlab.psd(ch_low, Fs=fs, detrend=mlb.detrend_mean, NFFT=32*1024)

# convert velocity to acceleration by multiplying point by point with frequencies
# (multiplication by j omega in freq domain is differentiation, PSD is squared)
psd_accel = psd_vel * pow((2 * np.pi * f_vel), 2)
inoise_accel_y = inoise_y * (2 * np.pi * inoise_f)

# convert to log scale
psd_vel = 10 * np.log10(psd_vel)
psd_accel = 10 * np.log10(psd_accel)
    print("START")
    # Number of control volumes
    ns = [5,50]
    # Lenght (m)
    L = 1
    # Boundary temperatures (C)
    T_B   = 100
    # Enviroment temperature
    T_inf = 20
    # Fin paramter (1/m2)
    n2 = 25
    
    T  = []
    dx = []
    for k, n in enumerate(ns):
        Ti, dxi = fin(L, T_B, T_inf, n2, n)
        T.append(Ti)
        dx.append(dxi)

    # Exact solution
    x = sp.linspace(0,L)
    T_exact = T_inf + (T_B-T_inf)*sp.cosh(n2**0.5*(L-x))/sp.cosh(n2**0.5*L) 
    
    #  Plot numerical and exact solution
    plt.plot(x, T_exact, "k", label="exact")
    plt.plot(sp.linspace(dx[1]/2,L-dx[1]/2,ns[1]), T[1], "d", label="n="+str(ns[1]))    
    plt.plot(sp.linspace(dx[0]/2,L-dx[0]/2,ns[0]), T[0], "o", label="n="+str(ns[0]))
    plt.legend()
    plt.xlim(0,L)
    print("END")
Exemplo n.º 52
0
# get_ipython().magic('matplotlib inline')

(Frequency, array) = read('mimii_dummy.wav')

len(array)

plt.plot(array)
plt.title('Original Signal Spectrum')
plt.xlabel('Frequency(Hz)')
plt.ylabel('Amplitude')
# plt.show()

FourierTransformation = sp.fft(array)
# array = sp.fft(array)

scale = sp.linspace(0, Frequency, len(array))

plt.stem(scale[0:5000], np.abs(FourierTransformation[0:5000]), 'r')
# array = FourierTransformation

filteredSignal = signal.wiener(array)
plt.plot(filteredSignal)  # plotting the signal.
plt.title('wiener filter plot')
plt.xlabel('Frequency(Hz)')
plt.ylabel('Amplitude')
plt.show()

# c,d = signal.ellip(array,) # ButterWorth low-filter
newfilteredSignal = signal.wiener(
    filteredSignal)  # Applying the filter to the signal
plt.plot(newfilteredSignal)  # plotting the signal.
Exemplo n.º 53
0
    """ Fit a bunch of points and return an evaluation vector """
    assert len(ptx) == len(pty)
    if t is None:
        return UnivariateSpline(x=ptx, y=pty, s=s, k=k)(ptx_eval)
    else:
        return LSQUnivariateSpline(x=ptx, y=pty, t=t, k=k)(ptx_eval)


""" Better with center size = 7 and gamma = .25 """
#Figure 3c
_DEFAULT_TILTEFFECT_DEGPERPIX = .25  # <OToole77>
_DEFAULT_TILTEFFECT_SIZE = 51  #101
_DEFAULT_TILTEFFECT_CSIZE = iround(2. / _DEFAULT_TILTEFFECT_DEGPERPIX)
_DEFAULT_TILTEFFECT_SSIZE = iround(8. / _DEFAULT_TILTEFFECT_DEGPERPIX)
_DEFAULT_TILTEFFECT_CVAL = .5
_DEFAULT_TILTEFFECT_SVALS = sp.linspace(0.0, 0.5, 10)
_DEFAULT_TILTEFFECT_SCALES = {'ow77': 0.40, 'ms79': 0.60}  #0.45
_DEFAULT_TILTEFFECT_NPOINTS = 25  #100
_DEFAULT_TILTEFFECT_CIRCULAR = True
_DEFAULT_TILTEFFECT_DECODER_TYPE = 'circular_vote'
_DEFAULT_TILTEFFECT_CSV = {
    'ow77': os.path.join(DATADIR, 'OW_fig4_Black.csv'),
    'ms79': os.path.join(DATADIR, 'MS1979.csv'),
}

_DEFAULT_VALUE_BW3DS_SIZE = 31
_DEFAULT_VALUE_BW3DS_CSIZE = 8
_DEFAULT_VALUE_BW3DS_CVAL = .5
_DEFAULT_VALUE_BW3DS_NSCALES = 49  #49
_DEFAULT_VALUE_BW3DS_SVALS = sp.linspace(0.0, 0.5, 11)
_DEFAULT_VALUE_BW3DS_BWS = sp.linspace(
Exemplo n.º 54
0
def run(hps=None):
    defaults = PaperDefaults()

    #David's globals
    size = 101
    mpp = 0.35 # 0.76 # 1.11
    scale = 0.12 # 0.23 # 0.22
    csv_file_x = os.path.join(defaults._DATADIR, 'WL1987_corrected_X.csv')
    csv_file_y = os.path.join(defaults._DATADIR, 'WL1987_corrected_Y.csv')

    # experiment parameters
    dd = (-150., 150.) # in seconds of arc
    sec2u = lambda s: (s - dd[0]) / (dd[1] - dd[0])
    u2sec = lambda u: u * (dd[1] - dd[0]) + dd[0]
    min2pix = lambda m: iround(m/float(mpp))
    npoints = 50
    ndists = 13
    dists = sp.linspace(0.0, 12., ndists)
    lh, lw = .25, 4.
    ph, pw = 1., 1.
    center_disp = 0.0
    flanker_disp = -33.3
    mp0 = size//2

    # Need to scale up the ecrfs 
    defaults._DEFAULT_PARAMETERS['srf'] = defaults._DEFAULT_PARAMETERS['srf'] * 2 - 1
    defaults._DEFAULT_PARAMETERS['ssn'] = defaults._DEFAULT_PARAMETERS['ssn'] * 2 - 1
    defaults._DEFAULT_PARAMETERS['ssf'] = defaults._DEFAULT_PARAMETERS['ssf'] * 2 - 1

    # simulate populations
    im = get_wl87_stim(size=size, dists=min2pix(dists),
        cval=sec2u(center_disp), sval=sec2u(flanker_disp),
        ch=min2pix(lh), cw=min2pix(lw), sh=min2pix(ph), sw=min2pix(pw))

    # Get ground truth data
    paper_data_x = sp.genfromtxt(csv_file_x, delimiter=',')
    paper_data_y = sp.genfromtxt(csv_file_y, delimiter=',') * -1
    paper_fit_y = sfit(sp.linspace(dists.min(), dists.max(), 100), paper_data_x,
        sp.nanmean(paper_data_y, axis=0), k=2, t=[5.])

    extra_vars = {}
    extra_vars['scale'] = scale
    extra_vars['kind'] = 'gaussian'
    extra_vars['decoder'] = 'circular_vote'
    extra_vars['npoints'] = npoints
    extra_vars['cval'] = sec2u(center_disp)
    extra_vars['sval'] = sec2u(flanker_disp)
    extra_vars['figure_name'] = 'f5'
    extra_vars['u2sec'] = u2sec
    extra_vars['min2pix'] = min2pix
    extra_vars['dists'] = dists
    extra_vars['flanker_disp'] = flanker_disp
    extra_vars['mp0'] = mp0
    extra_vars['lh'] = lh
    extra_vars['pw'] = pw
    extra_vars['size'] = size
    extra_vars['gt_x'] = paper_data_x
    extra_vars['return_var'] = 'I'

    defaults = adjust_parameters(defaults,hps)
    optimize_model(im,paper_fit_y,extra_vars,defaults)
Exemplo n.º 55
0
def setGlobalParams(init=True, **kwargs):
	vars = {}
	
	# use default values
	if (init):
		for (name, value) in g_default.iteritems():
			vars[name] = value
			
	# set specified parameters
	for (name, value) in kwargs.iteritems():
		if (name not in g_names):
			print("setGlobalParams: unknown parameter", (name, value))
		vars[name] = value
	setGlobalsFromDict(vars)
	
	# these variables should have been set by setGlobalsFromDict
	init_z_shock(zLow, zHigh, pHigh)

	# state space grid
	# variables: M_t (cash reserve), N_t (population), D_t (liabilities)
	# gridM, gridD are triples containing (min, max, size)
	(gridmin_M, gridmax_M, gridsize_M) = M_grid
	(gridmin_D, gridmax_D, gridsize_D) = D_grid
	grid_M = linspace(gridmin_M, gridmax_M, gridsize_M);
	grid_D = linspace(gridmin_D, gridmax_D, gridsize_D);
	(mesh_M, mesh_D) = meshgrid(grid_M, grid_D)
	meshlist_M = mesh_M.ravel()
	meshlist_D = mesh_D.ravel()
	gridshape = (gridsize_M, gridsize_D);

	# controls: d_t (dividends), r_t (interest rate offered).
	# d_t is on same grid as M.
	# r_t is between 1 and 2.  Does it need a grid?  we're going to argmax it... yes	
	(gridmin_r, gridmax_r, gridsize_r) = r_grid
	grid_r = linspace(gridmin_r, gridmax_r, gridsize_r)
	(mesh_M2, mesh_r) = meshgrid(grid_M, grid_r)
	meshlist_M2 = mesh_M2.ravel()
	meshlist_r = mesh_r.ravel()
	vars = {
		'gridmin_M': gridmin_M, 
		'gridmax_M': gridmax_M, 
		'gridsize_M': gridsize_M,
		'gridmin_D': gridmin_D,
		'gridmax_D': gridmax_D,
		'gridsize_D': gridsize_D,
		'grid_M': grid_M,
		'grid_D': grid_D,
		'mesh_M': mesh_M,
		'mesh_D': mesh_D,
		'meshlist_M': meshlist_M,
		'meshlist_D': meshlist_D,
		'gridshape': gridshape,		
		'grid_r': grid_r,
		'mesh_M2': mesh_M2,
		'mesh_r': mesh_r,
		'meshlist_M2': meshlist_M2,
		'meshlist_r': meshlist_r,
	}
	setGlobalsFromDict(vars)
	
	# init c library
	p3_fns.setGlobalParams(theta, beta, gamma, "linear", grid_M, grid_D, array(z_space), array(z_probs), depositorSlope, bankruptcyPenalty, [grid_M, grid_D])
Exemplo n.º 56
0
plt.close('all')

scipy.random.seed(21)

beta = 5.
gamma = 1.
p_dist = 1.  # how are the initial and final p's distributed: p_0, p_N ~ N(0, p_dist/beta)

M = 100  # number of ensemble members
N = 10000  # number of time steps
assert N % 2 == 0  # to have a neat midpoint
# assert not N%4 == 0 # to avoind odd-even decoupling???

T = 100.  # end time
tau = T / N  # time step
ts = scipy.linspace(0, T, N + 1)
ou1 = scipy.exp(-gamma * tau)
ou2 = scipy.sqrt((1 - scipy.exp(-2 * gamma * tau)) / beta)

gL = +1
qL = gL

t0 = 0.
q0 = scipy.ones((M, )) * qL
p0 = p_dist / beta * scipy.random.normal(size=(M, ))
q0[:] = p0

q_space = scipy.linspace(-4, 4, 100)

qs = scipy.zeros((N + 1, M))
ps = scipy.zeros((N + 1, M))
abestfituncRs = puncRs[0]
bbestfitvalRs = poptRs[1]
bbestfituncRs = puncRs[1]
print "abestRs= %5.3f +/- %5.3f" % (abestfitvalRs, abestfituncRs)
print "bbestRs= %5.3f +/- %5.3f" % (bbestfitvalRs, bbestfituncRs)

(poptRp, puncRp, rcRp, dRp) = curve_fit_custom(Rp, xaxis, yobservedcorrectedRp,
                                               pguess)
abestfitvalRp = poptRp[0]
abestfituncRp = puncRp[0]
bbestfitvalRp = poptRp[1]
bbestfituncRp = puncRp[1]
print "abestRp= %5.3f +/- %5.3f" % (abestfitvalRp, abestfituncRp)
print "bbestRp= %5.3f +/- %5.3f" % (bbestfitvalRp, bbestfituncRp)

xdense = sp.linspace(0, 92, 1000)

ymodelpointsRs = Rs(xaxis, poptRs[0], poptRs[1])
ymodelsmoothRs = Rs(xdense, poptRs[0], poptRs[1])
ymodelpointsRp = Rp(xaxis, poptRp[0], poptRp[1])
ymodelsmoothRp = Rp(xdense, poptRp[0], poptRp[1])

residualsRs = ymodelpointsRs - yobservedRs
residualsRp = ymodelpointsRp - yobservedRp

smoothcurveRs = Rs(xdense)
smoothcurveRp = Rp(xdense)

#plt.plot(xsamples,residuals,'bo')
plt.plot(xaxis, yobservedcorrectedRs, 'go')
plt.plot(xaxis, yobservedcorrectedRp, 'yo')
Exemplo n.º 58
0
def f(x):
    return exp(-x[0]**2 - x[1]**2)


def neg_f(x):
    return -f(x)


x0 = random.randn(2)
x_min = fmin(neg_f, x0)

from mpl_toolkits.mplot3d import Axes3D

delta = 3
x_knots = linspace(x_min[0] - delta, x_min[0] + delta, 41)
y_knots = linspace(x_min[1] - delta, x_min[1] + delta, 41)
X, Y = meshgrid(x_knots, y_knots)
Z = zeros(X.shape)
for i in range(Z.shape[0]):
    for j in range(Z.shape[1]):
        Z[i][j] = f([X[i, j], Y[i, j]])

ax = Axes3D(figure(figsize=(8, 5)))
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm, linewidth=0.4)
ax.plot([x0[0]], [x0[1]], [f(x0)],
        color='g',
        marker='o',
        markersize=5,
        label='initial')
ax.plot([x_min[0]], [x_min[1]], [f(x_min)],
### Clustering

a = np.random.multivariate_normal([10, 0], [[3, 1], [1, 4]], size=[100,])
b = np.random.multivariate_normal([0, 20], [[3, 1], [1, 4]], size=[50,])
X = np.concatenate((a,b),)
Num_of_clusters = 2;
Centre,Var = spcv.kmeans(X, Num_of_clusters )
id,dist = spcv.vq(X,Centre)

print id, dist

#Sample data creation

#number of points
n = 50
t = linspace(-5, 5, n)
#parameters
a = 0.8
b = -4
x = nppp.polyval(t,[a, b])
#add some noise
xn= x+randn(n)
(ar,br) = nppp.polyfit(t,xn,1)
xr = nppp.polyval(t,[ar,br])

#compute the mean square error
err = sqrt(sum((xr-xn)**2)/n)
print('Linear regression using polyfit')
print('parameters: a=%.2f b=%.2f \nregression: a=%.2f b=%.2f, ms error= %.3f' % (a,b,ar,br,err))
print('-----------------------------------------------------')
Exemplo n.º 60
0
    z = 1.5
    e = 0.75
elif len(sys.argv) == 2:
    r = float(sys.argv[1])
    a = 0.1
    z = 1.5
    e = 0.75
else:
    # Define parameters:
    r = 1.  # Resource growth rate
    a = 0.1  # Consumer search rate (determines consumption rate)
    z = 1.5  # Consumer mortality rate
    e = 0.75  # Consumer production efficiency

# Now define time -- integrate from 0 to 15, using 1000 points:
t = sc.linspace(0, 15, 15)
K = 100
x0 = 10
y0 = 5
z0 = sc.array([x0, y0
               ])  # initials conditions: 10 prey and 5 predators per unit area
pops = sc.array([[x0, y0]])
x = z0[0]
y = z0[1]
n = len(t)  # get length of t

for i in t[1:n]:  # initial conditions already included in pops

    new = dR_dt(x, y, i)  # 2*1 array
    if new[0, 0] < 0:  # doesn't allow density to drop below 0
        new[0, 0] = 0