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


Python FortranFile.close方法代码示例

本文整理汇总了Python中scipy.io.FortranFile.close方法的典型用法代码示例。如果您正苦于以下问题:Python FortranFile.close方法的具体用法?Python FortranFile.close怎么用?Python FortranFile.close使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在scipy.io.FortranFile的用法示例。


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

示例1: read_output

# 需要导入模块: from scipy.io import FortranFile [as 别名]
# 或者: from scipy.io.FortranFile import close [as 别名]
def read_output(path, header_only=True):
    f = FortranFile(path, 'r')
    ncpu = f.read_ints()
    dim = f.read_ints()
    nparts = f.read_ints()
    if header_only:
        f.close()
        return ncpu, dim, nparts
    f.read_ints()
    f.read_ints()
    f.read_ints()
    f.read_ints()
    f.read_ints()

    x = f.read_reals(dtype=np.float64)
    y = f.read_reals(dtype=np.float64)
    z = f.read_reals(dtype=np.float64)

    vx = f.read_reals(dtype=np.float64)
    vy = f.read_reals(dtype=np.float64)
    vz = f.read_reals(dtype=np.float64)

    m = f.read_reals(dtype=np.float64)

    part_ids = f.read_ints()

    birth = f.read_reals(dtype=np.float32)

    f.close()
    return ncpu, dim, nparts, x, y, z, part_ids
开发者ID:cphyc,项目名称:cosmo_z17to0,代码行数:32,代码来源:sort_galaxy.py

示例2: test_fortranfiles_write

# 需要导入模块: from scipy.io import FortranFile [as 别名]
# 或者: from scipy.io.FortranFile import close [as 别名]
def test_fortranfiles_write():
    for filename in iglob(path.join(DATA_PATH, "fortran-*-*x*x*.dat")):
        m = re.search("fortran-([^-]+)-(\d+)x(\d+)x(\d+).dat", filename, re.I)
        if not m:
            raise RuntimeError("Couldn't match %s filename to regex" % filename)
        dims = (int(m.group(2)), int(m.group(3)), int(m.group(4)))

        counter = 0
        data = np.zeros(dims, dtype=m.group(1).replace("s", "<"))
        for k in range(dims[2]):
            for j in range(dims[1]):
                for i in range(dims[0]):
                    data[i, j, k] = counter
                    counter += 1
        tmpdir = tempfile.mkdtemp()
        try:
            testFile = path.join(tmpdir, path.basename(filename))
            f = FortranFile(testFile, "w", "<u4")
            f.write_record(data)
            f.close()
            originalfile = open(filename, "rb")
            newfile = open(testFile, "rb")
            assert_equal(originalfile.read(), newfile.read(), err_msg=filename)
            originalfile.close()
            newfile.close()
        finally:
            shutil.rmtree(tmpdir)
开发者ID:haadkhan,项目名称:cerebri,代码行数:29,代码来源:test_fortran.py

示例3: tmp

# 需要导入模块: from scipy.io import FortranFile [as 别名]
# 或者: from scipy.io.FortranFile import close [as 别名]
    def tmp():
        ff = FortranFile(filename)
        h = {}
        h["nbodies"] = ff.read_ints()
        h["massp"] = ff.read_ints()
        h["aexp"] = ff.read_reals(dtype=np.int32)
        h["omega_t"] = ff.read_reals(dtype=np.int32)
        h["age_univ"] = ff.read_reals(dtype=np.int32)
        h["n_halos"], h["n_subhalos"] = ff.read_ints()

        for i in tqdm(range(h["n_halos"] + h["n_subhalos"])):
            infos = {
                "header": h
            }
            infos["nparts"] = ff.read_ints()
            infos["members"] = ff.read_ints()
            infos["idh"] = ff.read_ints()
            infos["timestep"] = ff.read_ints()
            infos["hlevel"], infos["hosthalo"], infos["hostsub"], infos["nbsub"], infos["nextsub"] = ff.read_ints()

            infos["mhalo"] = ff.read_reals(dtype=np.int32)
            infos["pos"] = ff.read_reals(dtype=np.int32)
            infos["speed"] = ff.read_reals(dtype=np.int32)
            infos["L"] = ff.read_reals(dtype=np.int32)
            infos["r"], infos["a"], infos["b"], infos["c"] = ff.read_reals(dtype=np.int32)
            infos["ek"], infos["ep"], infos["et"] = ff.read_reals(dtype=np.int32)
            infos["spin"] = ff.read_reals(dtype=np.int32)
            if not dm_type:
                ff.read_reals()
            infos["rvir"],infos["mvir"], infos["tvir"], infos["cvel"] = ff.read_reals(dtype=np.int32)
            ff.read_reals()
            if not dm_type:
                infos["npoints"] = ff.read_ints()
                infos["rdum"] = ff.read_reals(dtype=np.int32)
                infos["density"] = ff.read_reals(dtype=np.int32)

            if low_mem != None:
                try:
                    keys = list(low_mem)
                except:
                    keys = ['nparts', 'members']

                tmp = {}
                for key in keys:
                    try:
                        tmp[key] = infos[key]
                    except KeyError:
                        print('Invalid key {}, can be any of', infos['keys'])
                yield tmp
            else:
                yield infos
        ff.close()
开发者ID:cphyc,项目名称:cosmo_z17to0,代码行数:54,代码来源:tools.py

示例4: read_fbin

# 需要导入模块: from scipy.io import FortranFile [as 别名]
# 或者: from scipy.io.FortranFile import close [as 别名]
def read_fbin(filename):
    ''' this reads each written binary instance itteratively'''
    f = FortranFile(filename, 'r')
    array = []
    while True:
        try:
            array.append(f.read_reals(dtype=np.float_))
        except TypeError:
            break
    #array = np.reshape(array, (nspecs,-1))

    f.close()
    return array
开发者ID:wolfiex,项目名称:DSMACC-testing,代码行数:15,代码来源:begin.py

示例5: particles_in_halo

# 需要导入模块: from scipy.io import FortranFile [as 别名]
# 或者: from scipy.io.FortranFile import close [as 别名]
def particles_in_halo(tree_brick, start=0, end=None, fun_filter=lambda x: True):
    ''' Open a tree bricks file and associate to each halo the corresponding particles.
    '''
    # Open file
    f = FortranFile(tree_brick, 'r')

    # Give a value to end, by default start + 1
    if end == None:
        end = start + 1

    # Read headers
    nbodies = f.read_ints()[0]
    f.read_reals(dtype=np.float32)
    aexp = f.read_reals(dtype=np.float32)
    f.read_reals(dtype=np.float32)
    age = f.read_reals(dtype=np.float32)
    nhalo, nsubhalo = f.read_ints()
    halo_tot = nhalo + nsubhalo

    halos = {}
    for i in tqdm(range(halo_tot)):
        parts = f.read_ints()[0]
        members = f.read_ints()
        this_id = f.read_ints()[0]
        if (start <= this_id and this_id < end and fun_filter(this_id)):
            for dm_particle_id in members:
                if not halos.has_key(this_id):
                    halos[this_id] = []

                halos[this_id].append(dm_particle_id)
        elif this_id >= end:
            break
        f.read_ints()

        # Irrelevant
        level, hosthalo, hostsub, nbsub, nextsub = f.read_ints()
        mstar = 1e11 * f.read_reals(dtype=np.float32)
        px, py, pz = f.read_reals(dtype=np.float32)
        f.read_reals(dtype=np.float32)
        f.read_reals(dtype=np.float32)
        rad = f.read_reals(dtype=np.float32)[0]
        f.read_reals(dtype=np.float32)
        f.read_reals(dtype=np.float32)
        rvir, mvir, tvir, cvel = f.read_reals(dtype=np.float32)
        f.read_reals(dtype=np.float32)

    f.close()
    return halos
开发者ID:cphyc,项目名称:cosmo_z17to0,代码行数:50,代码来源:sort_galaxy.py

示例6: test_fortranfiles_read

# 需要导入模块: from scipy.io import FortranFile [as 别名]
# 或者: from scipy.io.FortranFile import close [as 别名]
def test_fortranfiles_read():
    for filename in iglob(path.join(DATA_PATH, "fortran-*-*x*x*.dat")):
        m = re.search(r'fortran-([^-]+)-(\d+)x(\d+)x(\d+).dat', filename, re.I)
        if not m:
            raise RuntimeError("Couldn't match %s filename to regex" % filename)

        dims = (int(m.group(2)), int(m.group(3)), int(m.group(4)))

        dtype = m.group(1).replace('s', '<')

        f = FortranFile(filename, 'r', '<u4')
        data = f.read_record(dtype=dtype).reshape(dims, order='F')
        f.close()

        expected = np.arange(np.prod(dims)).reshape(dims).astype(dtype)
        assert_equal(data, expected)
开发者ID:BranYang,项目名称:scipy,代码行数:18,代码来源:test_fortran.py

示例7: readfun

# 需要导入模块: from scipy.io import FortranFile [as 别名]
# 或者: from scipy.io.FortranFile import close [as 别名]
        def readfun(filename):
            '''
            reads unformatted fortran files 
            ''' 
            f = FortranFile('Outputs/'+filename, 'r')
            names = ''.join(f.read_reals('c'))
            data = []
            while True:
                    try:
                        data.append(f.read_reals(dtype=np.float_))
                    except TypeError:
                        break
                #array = np.reshape(array, (nspecs,-1))

            f.close()
            return [names.replace(' ',''),np.array(data)]
开发者ID:wolfiex,项目名称:DSMACC-testing,代码行数:18,代码来源:zserialout.py

示例8: test_fortranfiles_read

# 需要导入模块: from scipy.io import FortranFile [as 别名]
# 或者: from scipy.io.FortranFile import close [as 别名]
def test_fortranfiles_read():
    for filename in iglob(path.join(DATA_PATH, "fortran-*-*x*x*.dat")):
        m = re.search('fortran-([^-]+)-(\d+)x(\d+)x(\d+).dat', filename, re.I)
        if not m:
            raise RuntimeError("Couldn't match %s filename to regex" % filename)
        dims = (int(m.group(2)), int(m.group(3)), int(m.group(4)))

        f = FortranFile(filename, 'r', '<u4')
        data = f.read_record(dtype=m.group(1)).reshape(dims)
        f.close()

        counter = 0
        for k in range(dims[2]):
            for j in range(dims[1]):
                for i in range(dims[0]):
                    assert_equal(counter, data[i,j,k])
                    counter += 1
开发者ID:NeedAName,项目名称:scipy,代码行数:19,代码来源:test_fortran.py

示例9: export_FFT_field

# 需要导入模块: from scipy.io import FortranFile [as 别名]
# 或者: from scipy.io.FortranFile import close [as 别名]
def export_FFT_field(phi,outfile):
    """
    export_FFT_field(phi,outfile)

    outfile: string
    phi[:,:,:] : np.array, rank 3

    This function takes in a 3-D field, of dimension
    Ngrid x Ngrid x Ngrid, and exports a half-field
    Ngrid/2+1 x Ngrid x Ngrid in unformatted
    Fortran record. Equivalent to a write(field) statement.
    """
    f=FortranFile(outfile,'w')
    n=phi.shape[2]
    f.write_record(np.array([n],dtype=np.int32)) # write integer record
    f.write_record(phi[:n//2+1].ravel(order='F')) # write half-field
    f.close()
开发者ID:rspeare,项目名称:window-function-convolution,代码行数:19,代码来源:util.py

示例10: reorder_uXu

# 需要导入模块: from scipy.io import FortranFile [as 别名]
# 或者: from scipy.io.FortranFile import close [as 别名]
def reorder_uXu(ext,formatted=False):
  try:
    print "----------\n  {0}  \n----------".format(ext)
    
    if formatted:
	f_uXu_in = open(seedname+"."+ext, 'r')
	f_uXu_out = open(seednameGW+"."+ext, 'w')
	header=f_uXu_in.readline()
	f_uXu_out.write(header)
	nbnd,NK,nnb=np.array(f_uXu_in.readline().split(),dtype=int)
	f_uXu_out.write("  ".join(str(x) for x in [NBND,NK,nnb])+"\n")
    else:
	f_uXu_in = FortranFile(seedname+"."+ext, 'r')
	f_uXu_out = FortranFile(seednameGW+"."+ext, 'w')
	header=f_uXu_in.read_record(dtype='c')
        f_uXu_out.write_record(header)
	nbnd,NK,nnb=np.array(f_uXu_in.read_record(dtype=np.int32))
	f_uXu_out.write_record(np.array([NBND,NK,nnb],dtype=np.int32))
    
    assert nbnd==nbndDFT
    print nbnd,NK,nnb
    
    if formatted:
	uXu=np.loadtxt(f_uXu_in).reshape(-1)
	start=0
	length=nbnd*nbnd

    for ik in xrange(NKPT):
	for ib2 in xrange(nnb):
	    for ib1 in xrange(nnb):
		if formatted:
		    A=uXu[start:start+length]
		    start+=length
		else:
		    A=f_uXu_in.read_record(dtype=np.complex)
		A=(A.reshape(nbnd,nbnd,order='F')[BANDSORT[KPNB[ik][ib2]],:][:,BANDSORT[KPNB[ik][ib1]]]+
			np.einsum('ln,lm,l->nm',MMN[ik][ib2].conj(),MMN[ik][ib1],eigenDE[ik]) ).reshape(-1,order='F')
		if formatted:
		    f_uXu_out.write("".join("{0:26.16e}  {1:26.16f}\n".format(x.real,x.imag) for x in A))
		else:
	    	    f_uXu_out.write_record(A)
    f_uXu_out.close()
    f_uXu_in.close()
    print "----------\n {0} OK  \n----------\n".format(ext)
  except IOError as err:
    print "WARNING: {0}.{1} not written : ".format(seednameGW,ext),err 
开发者ID:wannier-developers,项目名称:wannier90,代码行数:48,代码来源:gw2wannier90.py

示例11: export_unk

# 需要导入模块: from scipy.io import FortranFile [as 别名]
# 或者: from scipy.io.FortranFile import close [as 别名]
 def export_unk(self, grid = [50,50,50]):
     '''
     Export the periodic part of BF in a real space grid for plotting with wannier90
     '''    
     
     from scipy.io import FortranFile
     grids_coor, weights = periodic_grid(self.cell, grid, order = 'F')        
     
     for k_id in range(self.num_kpts_loc):
         spin = '.1'
         if self.spin_up != None and self.spin_up == False : spin = '.2'
         kpt = self.cell.get_abs_kpts(self.kpt_latt_loc[k_id])    
         ao = numint.eval_ao(self.cell, grids_coor, kpt = kpt)
         u_ao = np.einsum('x,xi->xi', np.exp(-1j*np.dot(grids_coor, kpt)), ao, optimize = True)
         unk_file = FortranFile('UNK' + "%05d" % (k_id + 1) + spin, 'w')
         unk_file.write_record(np.asarray([grid[0], grid[1], grid[2], k_id + 1, self.num_bands_loc], dtype = np.int32))    
         mo_included = self.mo_coeff_kpts[k_id][:,self.band_included_list]        
         u_mo = np.einsum('xi,in->xn', u_ao, mo_included, optimize = True)
         for band in range(len(self.band_included_list)):    
             unk_file.write_record(np.asarray(u_mo[:,band], dtype = np.complex128))                    
         unk_file.close()
开发者ID:chrinide,项目名称:pyscf,代码行数:23,代码来源:pywannier90.py

示例12: read_fbin

# 需要导入模块: from scipy.io import FortranFile [as 别名]
# 或者: from scipy.io.FortranFile import close [as 别名]
def read_fbin(filename):
    ''' this reads each written binary instance itteratively'''
    f = FortranFile(filename, 'r')
    array = []
    while True:
        try:
            array.append(f.read_reals(dtype=np.float_))
        except TypeError:
            break
    #array = np.reshape(array, (nspecs,-1))

    f.close()
    
    
    #newdata = np.array(array)[:,selected_index]
    
    #indices = xrange(0,len(array)-sets_of,sets_of)
    
    
    #newdata = newdata[indices,:]
    #return newdata
    return array
开发者ID:wolfiex,项目名称:DSMACC-testing,代码行数:24,代码来源:learn.py

示例13: test_fortranfiles_write

# 需要导入模块: from scipy.io import FortranFile [as 别名]
# 或者: from scipy.io.FortranFile import close [as 别名]
def test_fortranfiles_write():
    for filename in iglob(path.join(DATA_PATH, "fortran-*-*x*x*.dat")):
        m = re.search(r'fortran-([^-]+)-(\d+)x(\d+)x(\d+).dat', filename, re.I)
        if not m:
            raise RuntimeError("Couldn't match %s filename to regex" % filename)
        dims = (int(m.group(2)), int(m.group(3)), int(m.group(4)))

        dtype = m.group(1).replace('s', '<')
        data = np.arange(np.prod(dims)).reshape(dims).astype(dtype)

        tmpdir = tempfile.mkdtemp()
        try:
            testFile = path.join(tmpdir,path.basename(filename))
            f = FortranFile(testFile, 'w','<u4')
            f.write_record(data.T)
            f.close()
            originalfile = open(filename, 'rb')
            newfile = open(testFile, 'rb')
            assert_equal(originalfile.read(), newfile.read(),
                         err_msg=filename)
            originalfile.close()
            newfile.close()
        finally:
            shutil.rmtree(tmpdir)
开发者ID:BranYang,项目名称:scipy,代码行数:26,代码来源:test_fortran.py

示例14: FortranFile

# 需要导入模块: from scipy.io import FortranFile [as 别名]
# 或者: from scipy.io.FortranFile import close [as 别名]
WuResMeanValid = np.zeros((nlat * nlon,))
WuResMeanValid[~mask] = WuResMean
WuResMeanValid = WuResMeanValid.reshape(nlat, nlon)
tau = np.tile(np.expand_dims(WuResMeanValid, 0), (T, 1, 1)) * ampMean
dtaudx = np.empty(tau.shape)
dtaudx[:, :, 1:-1] = (tau[:, :, 2:] - tau[:, :, :-2]) / dX3Center
dtaudx[:, :, 0] = (tau[:, :, 1] - tau[:, :, 0]) / dX3Left
dtaudx[:, :, -1] = (tau[:, :, -1] - tau[:, :, -2]) / dX3Right
dtaudy = np.empty(tau.shape)
dtaudy[:, 1:-1] = (tau[:, 2:] - tau[:, :-2]) / dY3Center
dtaudy[:, 0] = (tau[:, 1] - tau[:, 0]) / dY3Left
dtaudy[:, -1] = (tau[:, -1] - tau[:, -2]) / dY3Right
f = FortranFile('%s/tau_mean_ampMean%02d%s.bin' % (initDir, int(ampMean * 10), postfix), 'w')
for t in np.arange(T):
    f.write_record(tau[t])
f.close()
f = FortranFile('%s/dtaudx_mean_ampMean%02d%s.bin' % (initDir, int(ampMean * 10), postfix), 'w')
for t in np.arange(T):
    f.write_record(dtaudx[t])
f.close()
f = FortranFile('%s/dtaudy_mean_ampMean%02d%s.bin' % (initDir, int(ampMean * 10), postfix), 'w')
for t in np.arange(T):
    f.write_record(dtaudy[t])
f.close()

# Write tau with variations
for k in np.arange(nEOF):
    print 'Writing tau with %d eofs...' % (k+1,)
    eof = np.zeros((nlat*nlon,))
    eof[~mask] = v[:, k]
    eof = eof.reshape(nlat, nlon)
开发者ID:atantet,项目名称:transferCZ,代码行数:33,代码来源:get_tau_norm.py

示例15: read

# 需要导入模块: from scipy.io import FortranFile [as 别名]
# 或者: from scipy.io.FortranFile import close [as 别名]
    def read(self, datadir='data', proc=-1, quiet=False,
             trim=False):
        """
        Read the grid data from the pencil code simulation.
        If proc < 0, then load all data and assemble.
        Otherwise, load grid from specified processor.

        call signature:

        read(self, file_name='time_series.dat', datadir='data',
             double=0, quiet=0, comment_char='#')

        Keyword arguments:

        *datadir*:
          Directory where the data is stored.

        *proc*
          Processor to be read. If proc is -1, then read the 'global'
          grid. If proc is >=0, then read the grid.dat in the
          corresponding processor directory.

        *quiet*
          Flag for switching of output.

        *trim*
          Cuts off the ghost points.
        """

        import numpy as np
        import os
        from scipy.io import FortranFile
        import pencilnew.read as read

        datadir = os.path.expanduser(datadir)
        dim = read.dim(datadir, proc)
        if dim.precision == 'D':
            precision = 'd'
        else:
            precision = 'f'

        if proc < 0:
            proc_dirs = list(filter(lambda string: string.startswith('proc'), os.listdir(datadir)))
        else:
            proc_dirs = ['proc' + str(proc)]

        # Define the global arrays.
        x = np.zeros(dim.mx, dtype=precision)
        y = np.zeros(dim.my, dtype=precision)
        z = np.zeros(dim.mz, dtype=precision)
        dx_1 = np.zeros(dim.mx, dtype=precision)
        dy_1 = np.zeros(dim.my, dtype=precision)
        dz_1 = np.zeros(dim.mz, dtype=precision)
        dx_tilde = np.zeros(dim.mx, dtype=precision)
        dy_tilde = np.zeros(dim.my, dtype=precision)
        dz_tilde = np.zeros(dim.mz, dtype=precision)

        for directory in proc_dirs:
            proc = int(directory[4:])
            procdim = read.dim(datadir, proc)
            if not quiet:
                print("reading grid data from processor {0} of {1} ...".format(proc, len(proc_dirs)))

            mxloc = procdim.mx
            myloc = procdim.my
            mzloc = procdim.mz

            # Read the grid data.
            file_name = os.path.join(datadir, directory, 'grid.dat')
            infile = FortranFile(file_name, 'r')
            grid_raw = infile.read_record(dtype=precision)
            dx, dy, dz = tuple(infile.read_record(dtype=precision))
            Lx, Ly, Lz = tuple(infile.read_record(dtype=precision))
            dx_1_raw = infile.read_record(dtype=precision)
            dx_tilde_raw = infile.read_record(dtype=precision)
            infile.close()

            # Reshape the arrays.
            t = grid_raw[0]
            x_loc = grid_raw[1:mxloc+1]
            y_loc = grid_raw[mxloc+1:mxloc+myloc+1]
            z_loc = grid_raw[mxloc+myloc+1:mxloc+myloc+mzloc+1]
            dx_1_loc = dx_1_raw[0:mxloc]
            dy_1_loc = dx_1_raw[mxloc:mxloc+myloc]
            dz_1_loc = dx_1_raw[mxloc+myloc:mxloc+myloc+mzloc]
            dx_tilde_loc = dx_tilde_raw[0:mxloc]
            dy_tilde_loc = dx_tilde_raw[mxloc:mxloc+myloc]
            dz_tilde_loc = dx_tilde_raw[mxloc+myloc:mxloc+myloc+mzloc]

            if len(proc_dirs) > 1:
                if procdim.ipx == 0:
                    i0x = 0
                    i1x = i0x + procdim.mx
                    i0x_loc = 0
                    i1x_loc = procdim.mx
                else:
                    i0x = procdim.ipx*procdim.nx + procdim.nghostx
                    i1x = i0x + procdim.mx - procdim.nghostx
                    i0x_loc = procdim.nghostx
                    i1x_loc = procdim.mx
#.........这里部分代码省略.........
开发者ID:pencil-code,项目名称:pencil-code,代码行数:103,代码来源:grid.py


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