当前位置: 首页>>代码示例>>Python>>正文


Python numpy.savetxt函数代码示例

本文整理汇总了Python中numpy.savetxt函数的典型用法代码示例。如果您正苦于以下问题:Python savetxt函数的具体用法?Python savetxt怎么用?Python savetxt使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了savetxt函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: create_mat_file

def create_mat_file(data, model_name, outputModelFilesDirectory):

    """
    create the .mat file
    """

    dimx = None
    dimy = None
    if len(data.shape) == 1:
        dimy = 1
        dimx = data.shape[0]
    else:
        dimx, dimy = data.shape

    ppstring = "/PPheights"

    for i in range(0, dimy):

        ppstring += "\t" + "%1.5e" % (1.0)

    ppstring += "\n"

    f = open(os.path.join(outputModelFilesDirectory, model_name + ".mat"), "w")

    print >> f, "/NumWaves\t%d" % dimy
    print >> f, "/NumPoints\t%d" % dimx
    print >> f, ppstring

    print >> f, "/Matrix"
    np.savetxt(f, data, fmt="%1.5e", delimiter="\t")

    f.close()
开发者ID:RanjitK,项目名称:C-PAC,代码行数:32,代码来源:create_fsl_model.py

示例2: _ascii

 def _ascii(self):
   """write ascii file(s) w/ data contained in plot"""
   if not os.path.exists(self.name): os.makedirs(self.name)
   for k, v in self.dataSets.iteritems():
     np.savetxt(
       self.name + '/' + self._prettify(k) + '.dat', v, fmt='%.4e'
     )
开发者ID:johuck,项目名称:ccsgp,代码行数:7,代码来源:myplot.py

示例3: to_file

 def to_file(self, path, fmt='%.18e', delimiter=' ', newline='\n', header='', footer='', comments='# '):
     """
     Save self to a text file. See :func:`np.savetext` for the description of the variables
     """
     data = zip(self.mesh, self.values)
     np.savetxt(path, data, fmt=fmt, delimiter=delimiter, newline=newline,
                header=header, footer=footer, comments=comments)
开发者ID:srirampr,项目名称:abipy,代码行数:7,代码来源:func1d.py

示例4: normalize_input

def normalize_input(params):
    if pc_id == 0:
        print 'normalize_input'
        dt = params['dt_rate'] # [ms] time step for the non-homogenous Poisson process 
        L_input = np.zeros((params['n_exc'], params['t_stimulus']/dt))

        v_max = params['v_max']
        if params['log_scale']==1:
            v_rho = np.linspace(v_max/params['N_V'], v_max, num=params['N_V'], endpoint=True)
        else:
            v_rho = np.logspace(np.log(v_max/params['N_V'])/np.log(params['log_scale']),
                            np.log(v_max)/np.log(params['log_scale']), num=params['N_V'],
                            endpoint=True, base=params['log_scale'])
        v_theta = np.linspace(0, 2*np.pi, params['N_theta'], endpoint=False)
        index = 0
        for i_RF in xrange(params['N_RF_X']*params['N_RF_Y']):
            index_start = index
            for i_v_rho, rho in enumerate(v_rho):
                for i_theta, theta in enumerate(v_theta):
                    fn = params['input_rate_fn_base'] + str(index) + '.dat'
                    L_input[index, :] = np.loadtxt(fn)
                    print 'debug', fn
                    index += 1
            index_stop = index
            print 'before', i_RF, L_input[index_start:index_stop, :].sum()
            if (L_input[index_start:index_stop, :].sum() > 1):
                L_input[index_start:index_stop, :] /= L_input[index_start:index_stop, :].sum()
            print 'after', i_RF, L_input[index_start:index_stop, :].sum()

        for i in xrange(params['n_exc']):
            output_fn = params['input_rate_fn_base'] + str(i) + '.dat'
            print 'output_fn:', output_fn
            np.savetxt(output_fn, L_input[i, :])
    if comm != None:
        comm.barrier()
开发者ID:MinaKh,项目名称:bcpnn-mt,代码行数:35,代码来源:abstract_learning.py

示例5: _write_dig_points

def _write_dig_points(fname, dig_points):
    """Write points to file

    Parameters
    ----------
    fname : str
        Path to the file to write. The kind of file to write is determined
        based on the extension: '.txt' for tab separated text file.
    dig_points : numpy.ndarray, shape (n_points, 3)
        Points.
    """
    _, ext = op.splitext(fname)
    dig_points = np.asarray(dig_points)
    if (dig_points.ndim != 2) or (dig_points.shape[1] != 3):
        err = ("Points must be of shape (n_points, 3), "
               "not %s" % (dig_points.shape,))
        raise ValueError(err)

    if ext == '.txt':
        with open(fname, 'wb') as fid:
            version = __version__
            now = dt.now().strftime("%I:%M%p on %B %d, %Y")
            fid.write(b("% Ascii 3D points file created by mne-python version "
                        "{version} at {now}\n".format(version=version,
                                                      now=now)))
            fid.write(b("% {N} 3D points, "
                        "x y z per line\n".format(N=len(dig_points))))
            np.savetxt(fid, dig_points, delimiter='\t', newline='\n')
    else:
        msg = "Unrecognized extension: %r. Need '.txt'." % ext
        raise ValueError(msg)
开发者ID:YoheiOseki,项目名称:mne-python,代码行数:31,代码来源:meas_info.py

示例6: write_connectivity_zip

    def write_connectivity_zip(self, conn_dir, weigths, tracts, cortical, region_names, centers, areas, orientations, atlas):
        tmpdir = tempfile.TemporaryDirectory()

        file_weigths = os.path.join(tmpdir.name, 'weights.txt')
        file_tracts = os.path.join(tmpdir.name, 'tract_lengths.txt')
        file_cortical = os.path.join(tmpdir.name, 'cortical.txt')
        file_centers = os.path.join(tmpdir.name, 'centers.txt')
        file_areas = os.path.join(tmpdir.name, 'areas.txt')
        file_orientations = os.path.join(tmpdir.name, 'average_orientations.txt')

        numpy.savetxt(file_weigths, weigths, fmt='%d')
        numpy.savetxt(file_tracts, tracts, fmt='%.3f')
        numpy.savetxt(file_cortical, cortical, fmt='%d')

        with open(str(file_centers), "w") as f:
            for idx, (val_x, val_y, val_z) in enumerate(centers):
                f.write("%s %.2f %.2f %.2f\n" % (region_names[idx], val_x, val_y, val_z))

        numpy.savetxt(file_areas, areas, fmt='%.2f')
        numpy.savetxt(file_orientations, orientations, fmt='%.2f %.2f %.2f')

        filename = os.path.join(conn_dir, OutputConvFiles.CONNECTIVITY_ZIP.value.replace("%s", atlas))
        with ZipFile(filename, 'w') as zip_file:
            zip_file.write(file_weigths, os.path.basename(file_weigths))
            zip_file.write(file_tracts, os.path.basename(file_tracts))
            zip_file.write(file_cortical, os.path.basename(file_cortical))
            zip_file.write(file_centers, os.path.basename(file_centers))
            zip_file.write(file_areas, os.path.basename(file_areas))
            zip_file.write(file_orientations, os.path.basename(file_orientations))
开发者ID:maedoc,项目名称:tvb-virtualizer,代码行数:29,代码来源:generic.py

示例7: main

def main(simulations, outname, edgeorevent, plot, savedata):
	mysimulations=open(simulations, 'r').readlines()
	truescores=[]
	fpscores=[]
	type=0
#	(min_count, max_count) = (5,12)
	(min_count, max_count) = (0,500)
	for i in xrange(len(mysimulations)): 
		line=mysimulations[i]
		if len(line.strip().split('\t')) ==3: 
			(dir, blocks, events)=line.strip().split('\t')
		else: 
			(dir, simid, blocks, events)=line.strip().split('\t')
		statsfile=os.path.join(dir, "%s.stats" % edgeorevent)
		data=SimData(statsfile)
		truecount=data.TP[type] + data.FN[type]
		if truecount >= min_count and truecount <= max_count:
			sys.stderr.write("truecount is %d\n" % (truecount))
			datfile=os.path.join(dir, "%s.dat" % edgeorevent)
			add_scores(datfile, truescores, fpscores)
	if savedata: 
		np.savetxt("%s.tp.txt" % outname, np.array(truescores))
		np.savetxt("%s.fp.txt" % outname, np.array(fpscores))
	if plot: 
		title=edgeorevent
		sys.stderr.write("making plot...\n")
		make_histograms(truescores, fpscores, title) 	
		plt.savefig(outname+".png")	
开发者ID:TracyBallinger,项目名称:cnavgpost,代码行数:28,代码来源:matplot_sim_score_histograms.py

示例8: save_fxye

 def save_fxye(self,filename):
     f=open(filename,'w')
     newx=self.data[:,0]*100
     newdata=np.column_stack((newx,self.data[:,1],self.data[:,2]))
     f.writelines(['Automatically generated file {} from PDViPeR \n'.format(splitext(basename(filename))[0]),
                  'BANK\t1\t{0}\t{1}\tCONS\t{2}\t{3} 0 0 FXYE \n'.format(len(newx),len(self.data[:,1]),newx[0],newx[1]-newx[0])])
     savetxt(filename, newdata, fmt='%1.6f')
开发者ID:AustralianSynchrotron,项目名称:pdviper,代码行数:7,代码来源:xye.py

示例9: saveTheta

 def saveTheta(self,fileName):
     '''
     Records theta under numpy format
     
     Input:    -fileName: name of the file where theta will be recorded
     '''
     np.savetxt(fileName, self.theta)
开发者ID:osigaud,项目名称:ArmModelPython,代码行数:7,代码来源:RBFN.py

示例10: populate_price_array

	def populate_price_array(self):
		
		a = random.Random()
		b = random.Random()
		
		price = self.price_start
		
		for i in range(0,self.max_periods):
			#if (i % 6) == 0:
			
			ra = a.random()
			for j in range(0,self.random_walk_probabilities.shape[0]):
				if ra <= self.random_walk_probabilities[j,3]:
					price_increase = self.random_walk_probabilities[j,0]*0.01
					break
			
			rb = b.random()
			if rb < 0.35:
				price_increase = -1.0*price_increase
			
			price = price + self.multiplier*price_increase
			self.price_array[i] = price
			
		np.savetxt('/Users/james/development/code_personal/nz-houses/data/math/capital_gains_array.txt',self.price_array)
		
		print 'maximum price = ' + str(max(self.price_array))
开发者ID:statX,项目名称:nz-houses,代码行数:26,代码来源:mortgage_main.py

示例11: _exportDataToText

    def _exportDataToText(self, file):
        """Saves textual data to a file

        """
        Nt = self.data.shape[0]
        N = self.data.shape[1]
        # all elements [real] + (all elements - diagonal) [imaginary] + time
        Na = N + 1 + N*(N-1) 

        out = numpy.zeros((Nt, Na), dtype=numpy.float64)   
        
        for i in range(Nt):
            #print("%%%%")
            # time
            out[i,0] = self.TimeAxis.data[i]
            #print(0)
            # populations
            for j in range(N):
               out[i,j+1] = numpy.real(self.data[i,j,j])
               #print(j+1)
            # coherences
            l = 0
            for j in range(N):
                for k in range(j+1,N):
                    out[i,N+1+l] = numpy.real(self.data[i,j,k])
                    #print(N+1+l)
                    l += 1
                    out[i,N+1+l] = numpy.imag(self.data[i,j,k])
                    #print(N+1+l)
                    l += 1
                    
        numpy.savetxt(file, out)
开发者ID:tmancal74,项目名称:quantarhei,代码行数:32,代码来源:dmevolution.py

示例12: populate_rate_array

	def populate_rate_array(self):
		
		a = random.Random()
		b = random.Random()
		
		rate = 0.08
		
		for i in range(self.fixed_period,self.max_periods):
			
			# determine a rate increase for this time-step
			for j in range(0,self.random_walk_probabilities.shape[0]):
				if a.random() <= self.random_walk_probabilities[j,3]:
					rate_increase = self.random_walk_probabilities[j,0]*0.01
					break
			
			# determine whether the step is positive or negative
			if b.random() < 0.3:
				rate_increase = -1.0*rate_increase
			
			
			# increment the interest rate and store the result
			rate += rate_increase
			self.rate_array[i] = rate
			
		np.savetxt('/Users/james/development/code_personal/nz-houses/data/math/interest_rate_array.txt',self.rate_array)
开发者ID:statX,项目名称:nz-houses,代码行数:25,代码来源:mortgage_main.py

示例13: exportData

 def exportData(self, fn):
     hdr = " ;".join([" %s" % s.strip() for s in self.dat[0]])
     sel = self.getSelected()
     try:
         x, y = self.toolbar.roi.get_xy()
         w = self.toolbar.roi.get_width()
         h = self.toolbar.roi.get_height()
         hdr += "\n"
         hdr += " ROI (um): X=%.2f  Y=%.2f  W=%.2f  H=%.2f    Points=%d   Concentration=%g" % (
             x,
             y,
             w,
             h,
             sel.shape[1],
             sum(sel[2]) / (w * h),
         )
     except AttributeError:
         # No roi
         pass
     if sel is None:
         wx.MessageBox(
             "Nothing to save yet. Make some selection before trying to export data.", "Nothing to export!"
         )
     else:
         d = array(sel)
         # Shift exported data to the origin
         d[0] -= min(d[0])
         d[1] -= min(d[1])
         np.savetxt(fn, d.T, fmt="%.3f", delimiter=" ", newline="\n", header=hdr, footer="", comments="#")
开发者ID:jochym,项目名称:pointsel,代码行数:29,代码来源:pointsel.py

示例14: create_grp_file

def create_grp_file(data, model_name, gp_var, outputModelFilesDirectory):

    """
    create the grp file
    """

    dimx = None
    dimy = None
    if len(data.shape) == 1:
        dimy = 1
        dimx = data.shape[0]
    else:
        dimx, dimy = data.shape
    data = np.ones(dimx)

    if not (gp_var == None):
        i = 1
        for key in sorted(gp_var.keys()):

            for index in gp_var[key]:
                data[index] = i

            i += 1

    f = open(os.path.join(outputModelFilesDirectory, model_name + ".grp"), "w")

    print >> f, "/NumWaves\t1"
    print >> f, "/NumPoints\t%d\n" % dimx
    print >> f, "/Matrix"
    np.savetxt(f, data, fmt="%d", delimiter="\t")

    f.close()
开发者ID:RanjitK,项目名称:C-PAC,代码行数:32,代码来源:create_fsl_model.py

示例15: write_ft_input

	def write_ft_input(self, filename='workmodl000'):
		"""
		Output atmosphere model in the format required by the fortran
		adding/doubling code.
		"""
		data_array = np.zeros([self.nlayers, 5])		
		
		for x in range(self.nlayers):
			layer = getattr(self, self.layer_names[x])
			data_array[x,:] = [layer.pi0bl, layer.tau, layer.p, 
							   layer.rp, layer.pi0uv]
			#NOTE order difference with writetxt()
			#print data_array[x,:] #debug
			
		#open file
		
		f = open(filename, 'w')
		
		f.write('{:12}{:12}{:12.5f}\n'.format(self.nlayers,
											  self.ablayer, self.abfactor))
		
		np.savetxt(f, data_array, fmt='%10.5f', delimiter='  ')
		
		f.close()
		logging.info("Model written out for RT input.")
开发者ID:davidchoi,项目名称:radtranpy,代码行数:25,代码来源:model.py


注:本文中的numpy.savetxt函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。