本文整理汇总了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
示例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)
示例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()
示例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
示例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
示例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)
示例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)]
示例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
示例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()
示例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
示例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()
示例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
示例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)
示例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)
示例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
#.........这里部分代码省略.........