本文整理汇总了Python中numpy.array2string函数的典型用法代码示例。如果您正苦于以下问题:Python array2string函数的具体用法?Python array2string怎么用?Python array2string使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了array2string函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __repr__
def __repr__(self):
import flowvb.core._flow_vb_str
# Add data dimensions to data dictionary
opt = self.options.copy()
opt.update({'num_obs': self.data.shape[0],
'num_features': self.data.shape[1]})
# Build summary string
str_summary = flowvb.core._flow_vb_str.str_summary_data
str_summary += flowvb.core._flow_vb_str.str_summary_options_init_all
if self.options['init_mean'] is not None:
str_summary += flowvb.core._flow_vb_str.str_summary_init_mean
opt['init_mean'] = np.array2string(opt['init_mean'])
if self.options['init_covar'] is not None:
str_summary += flowvb.core._flow_vb_str.str_summary_init_covar
opt['init_covar'] = np.array2string(opt['init_covar'])
if self.options['init_mixweights'] is not None:
str_summary += flowvb.core._flow_vb_str.str_summary_init_mixweights
opt['init_mixweights'] = np.array2string(opt['init_mixweights'])
str_summary += flowvb.core._flow_vb_str.str_summary_optim_display
return str_summary % opt
示例2: sampleNextInternal
def sampleNextInternal(self, variables):
#TODO : comment
smplARp = variables[self.samplerEngine.I_NOISE_ARP]
InvAutoCorrNoise = smplARp.InvAutoCorrNoise
smplHRF = variables[self.samplerEngine.I_HRF]
varXh = smplHRF.varXh
smplDrift = variables[self.samplerEngine.I_DRIFT]
varMBYPl = smplDrift.varMBYPl
smplNRL = variables[self.samplerEngine.I_NRLS]
varNRLs = smplNRL.currentValue
self.computeVarYTilde(varNRLs, varXh, varMBYPl)
# self.varYtilde = variables[self.samplerEngine.I_NRLS].varYtilde
for i in xrange(self.nbVox):
varYtildeTdelta = np.dot(self.varYTilde[:,i],InvAutoCorrNoise[:,:,i])
self.beta[i] = 0.5*np.dot(varYtildeTdelta,self.varYTilde[:,i])
pyhrf.verbose(6,'betas apost :')
pyhrf.verbose(6,np.array2string(self.beta,precision=3))
pyhrf.verbose(6,'sigma2 ~betas/Ga(%1.3f,1)'
%(0.5*(self.ny + 1)))
gammaSamples = np.random.gamma(0.5*(self.ny + 1), 1, self.nbVox)
self.currentValue = np.divide(self.beta, gammaSamples)
pyhrf.verbose(6, 'All noise vars :')
pyhrf.verbose(6,
np.array2string(self.currentValue,precision=3))
pyhrf.verbose(4, 'noise vars = %1.3f(%1.3f)'
%(self.currentValue.mean(), self.currentValue.std()))
示例3: write_ascii_gz
def write_ascii_gz(self, out_file):
"""
Works only in serial mode!
"""
if self.mpi_size != 1:
print("Error: only serial calculation supported.")
return False
np.set_printoptions(threshold=np.inf)
with gzip.open(out_file, 'wt') as f_out:
f_out.write("%d %d %d %d %d\n" % (self.natom, self.nspin, self.nao, self.nset_max, self.nshell_max))
f_out.write(np.array2string(self.nset_info) + "\n")
f_out.write(np.array2string(self.nshell_info) + "\n")
f_out.write(np.array2string(self.nso_info) + "\n")
for ispin in range(self.nspin):
if self.nspin == 1:
n_el = 2*(self.i_homo_loc[ispin]+1)
else:
n_el = self.i_homo_loc[ispin]+1
f_out.write("%d %d %d %d\n" % (len(self.coef_array[ispin]), self.i_homo_cp2k[ispin], self.lfomo[ispin], n_el))
evals_occs = np.hstack([self.evals_sel[ispin], self.occs_sel[ispin]])
f_out.write(np.array2string(evals_occs) + "\n")
for imo in range(len(self.coef_array[ispin])):
f_out.write(np.array2string(self.coef_array[ispin][imo]) + "\n")
示例4: __str__
def __str__(self):
numpy.set_printoptions(precision=4, threshold=6)
x = self.x
if self.x is not None:
x = numpy.array2string(self.x)
y = self.y
if self.y is not None:
y = numpy.array2string(self.y)
return (('x = %s\n' +
'y = %s\n' +
'min = %s\n' +
'max = %s\n' +
'nloop = %s\n' +
'delv = %s\n' +
'fac = %s\n' +
'log = %s') %
(x,
y,
self.min,
self.max,
self.nloop,
self.delv,
self.fac,
self.log))
示例5: distmat_to_txt
def distmat_to_txt( pdblist , distmat, filedir , name):
#write out distmat in phylip compatible format
outstr =' ' + str(len(pdblist)) + '\n'
for i,pdb in enumerate(pdblist):
if len(pdb)>10:
namestr= pdb[0:10]
if len(pdb)<10:
namestr = pdb
for pad in range(10 -len(pdb)):
namestr += ' '
outstr += namestr+ ' ' + np.array2string( distmat[i,:], formatter={'float_kind':lambda x: "%.2f" % x}).replace('[', '').replace(']', '') + ' \n'
print( outstr)
handle = open(filedir + name + 'phylipmat.txt' , 'w')
handle.write(outstr)
handle.close()
outstr = str(len(pdblist)) + '\n'
for i,pdb in enumerate(pdblist):
namestr = pdb.replace('.','').replace('_','')[0:20]
outstr += namestr+ ' ' + np.array2string( distmat[i,:], formatter={'float_kind':lambda x: "%.2f" % x}).replace('[', '').replace(']', '').replace('\n', '') + '\n'
print( outstr)
handle = open(filedir + name + 'fastmemat.txt' , 'w')
handle.write(outstr)
handle.close()
return filedir + name + 'fastmemat.txt'
示例6: __repr__
def __repr__(self):
prefixstr = ' '
if self._values.shape == ():
v = [tuple([self._values[nm] for nm in self._values.dtype.names])]
v = np.array(v, dtype=self._values.dtype)
else:
v = self._values
names = self._values.dtype.names
precision = np.get_printoptions()['precision']
fstyle = functools.partial(_fstyle, precision)
format_val = lambda val: np.array2string(val, style=fstyle)
formatter = {
'numpystr': lambda x: '({0})'.format(
', '.join(format_val(x[name]) for name in names))
}
if NUMPY_LT_1P7:
arrstr = np.array2string(v, separator=', ',
prefix=prefixstr)
else:
arrstr = np.array2string(v, formatter=formatter,
separator=', ',
prefix=prefixstr)
if self._values.shape == ():
arrstr = arrstr[1:-1]
unitstr = ('in ' + self._unitstr) if self._unitstr else '[dimensionless]'
return '<{0} ({1}) {2:s}\n{3}{4}>'.format(
self.__class__.__name__, ', '.join(self.components),
unitstr, prefixstr, arrstr)
示例7: test_structure_format
def test_structure_format(self):
dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
x = np.array([('Sarah', (8.0, 7.0)), ('John', (6.0, 7.0))], dtype=dt)
assert_equal(np.array2string(x),
"[('Sarah', [ 8., 7.]) ('John', [ 6., 7.])]")
# for issue #5692
A = np.zeros(shape=10, dtype=[("A", "M8[s]")])
A[5:].fill(np.datetime64('NaT'))
assert_equal(np.array2string(A),
"[('1970-01-01T00:00:00',) ('1970-01-01T00:00:00',) " +
"('1970-01-01T00:00:00',)\n ('1970-01-01T00:00:00',) " +
"('1970-01-01T00:00:00',) ('NaT',) ('NaT',)\n " +
"('NaT',) ('NaT',) ('NaT',)]")
# See #8160
struct_int = np.array([([1, -1],), ([123, 1],)], dtype=[('B', 'i4', 2)])
assert_equal(np.array2string(struct_int),
"[([ 1, -1],) ([123, 1],)]")
struct_2dint = np.array([([[0, 1], [2, 3]],), ([[12, 0], [0, 0]],)],
dtype=[('B', 'i4', (2, 2))])
assert_equal(np.array2string(struct_2dint),
"[([[ 0, 1], [ 2, 3]],) ([[12, 0], [ 0, 0]],)]")
# See #8172
array_scalar = np.array(
(1., 2.1234567890123456789, 3.), dtype=('f8,f8,f8'))
assert_equal(np.array2string(array_scalar), "( 1., 2.12345679, 3.)")
示例8: export_collada
def export_collada(mesh, file_obj=None):
'''
Export a mesh as collada, to filename
'''
import os, inspect
from string import Template
MODULE_PATH = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
template = Template(open(os.path.join(MODULE_PATH,
'templates',
'collada_template.dae'), 'rb').read())
# we bother setting this because np.array2string uses these printoptions
np.set_printoptions(threshold=np.inf, precision=5, linewidth=np.inf)
replacement = dict()
replacement['VERTEX'] = np.array2string(mesh.vertices.reshape(-1))[1:-1]
replacement['FACES'] = np.array2string(mesh.faces.reshape(-1))[1:-1]
replacement['NORMALS'] = np.array2string(mesh.vertex_normals.reshape(-1))[1:-1]
replacement['VCOUNT'] = str(len(mesh.vertices))
replacement['VCOUNTX3'] = str(len(mesh.vertices) * 3)
replacement['FCOUNT'] = str(len(mesh.faces))
export = template.substitute(replacement)
return _write_export(export, file_obj)
示例9: plot
def plot(arr,max_arr=None):
if max_arr == None: max_arr = arr
max_val = max(abs(np.max(max_arr)),abs(np.min(max_arr)))
print np.array2string(arr,
formatter={'float_kind': lambda x: visual(x,max_val)},
max_line_width = 5000
)
示例10: __str__
def __str__(self):
numpy.set_printoptions(precision=4, threshold=6)
samples = self.samples
if self.samples is not None:
samples = numpy.array2string(self.samples)
stats = self.stats
if self.stats is not None:
stats = numpy.array2string(self.stats)
ratios = self.ratios
if self.ratios is not None:
ratios = numpy.array2string(self.ratios)
output = '\n'.join([
'samples = %s' % samples,
'stats = %s' % stats,
'ratios = %s' % ratios,
'null = %s' % repr(self.null),
'alt = %s' % repr(self.alt),
'lr = %s' % repr(self.lr),
'ppp = %s' % repr(self.ppp)
])
return output
示例11: main
def main(argv):
file_loc = os.path.dirname(os.path.relpath(__file__))
with open(file_loc + '/../constants_runspec.json') as constants_file:
constants = json.load(constants_file)
data_file = open(file_loc + '/../data/' + argv[0])
data = read_file(data_file, constants)
time = range(0, constants['NUM_DAYS'])
fig = plt.figure(1)
for n in xrange(constants['NUM_RUNS']):
plt.plot(time, data[n, :, constants['ADULT_SUSC']], 'r', time, data[n, :, constants['ADULT_SICK']], 'g', time, data[n, :, constants['ADULT_IMMUNE']], 'b', time, data[n, :, constants['ADULT_CARRIERS']], 'k')
plt.legend(['Susceptible adults', 'Sick adults', 'Immune adults', 'Adult carriers'])
stats_array = np.zeros((constants['NUM_RUNS'], 3), dtype=np.float_)
np.seterr(divide = 'ignore')
for n in xrange(constants['NUM_RUNS']):
pop_sum = np.sum(data[n, :, :],1)
rate_carriers = np.nanmean(np.divide(data[n, :, constants['ADULT_CARRIERS']], pop_sum))
ccr = np.nanmean(np.divide(data[n, :, constants['ADULT_SICK']], data[n, :, constants['ADULT_CARRIERS']]))
max_sick = np.max(data[n,:,constants['ADULT_SICK']])
stats_array[n,:] = [rate_carriers, ccr, max_sick]
print '{0:22}|| {1:18} || {2:18} ||'.format(' Rate of carriers', 'Case-Carrier ratio', 'Top notation of sick')
print np.array2string(stats_array, separator= '||', formatter={'float_kind':lambda x: "%20f" % x})
fig = plt.figure(2)
top_sick = np.sort(stats_array[:,2])
plt.plot(top_sick)
plt.show()
示例12: evaluate
def evaluate(self, raster_plot_time_idx, fire_rate_time_idx):
""" Displays output of the simulation.
Calculates the firing rate of each population,
creates a spike raster plot and a box plot of the
firing rates.
"""
if nest.Rank() == 0:
print(
'Interval to compute firing rates: %s ms'
% np.array2string(fire_rate_time_idx)
)
fire_rate(
self.data_path, 'spike_detector',
fire_rate_time_idx[0], fire_rate_time_idx[1]
)
print(
'Interval to plot spikes: %s ms'
% np.array2string(raster_plot_time_idx)
)
plot_raster(
self.data_path, 'spike_detector',
raster_plot_time_idx[0], raster_plot_time_idx[1]
)
boxplot(self.net_dict, self.data_path)
示例13: __repr__
def __repr__(self):
prefixstr = " "
if self._values.shape == ():
v = [tuple([self._values[nm] for nm in self._values.dtype.names])]
v = np.array(v, dtype=self._values.dtype)
else:
v = self._values
names = self._values.dtype.names
precision = np.get_printoptions()["precision"]
fstyle = functools.partial(_fstyle, precision)
format_val = lambda val: np.array2string(val, style=fstyle)
formatter = {"numpystr": lambda x: "({0})".format(", ".join(format_val(x[name]) for name in names))}
if NUMPY_LT_1P7:
arrstr = np.array2string(v, separator=", ", prefix=prefixstr)
else:
arrstr = np.array2string(v, formatter=formatter, separator=", ", prefix=prefixstr)
if self._values.shape == ():
arrstr = arrstr[1:-1]
unitstr = ("in " + self._unitstr) if self._unitstr else "[dimensionless]"
return "<{0} ({1}) {2:s}\n{3}{4}>".format(
self.__class__.__name__, ", ".join(self.components), unitstr, prefixstr, arrstr
)
示例14: sampleNextInternal
def sampleNextInternal(self, variables):
# TODO : comment
smplARp = variables[self.samplerEngine.I_NOISE_ARP]
InvAutoCorrNoise = smplARp.InvAutoCorrNoise
smplHRF = self.get_variable('hrf')
varXh = smplHRF.varXh
smplDrift = self.get_variable('drift')
varMBYPl = smplDrift.varMBYPl
smplNRL = self.get_variable('nrl')
varNRLs = smplNRL.currentValue
self.computeVarYTilde(varNRLs, varXh, varMBYPl)
for i in xrange(self.nbVox):
varYtildeTdelta = np.dot(
self.varYTilde[:, i], InvAutoCorrNoise[:, :, i])
self.beta[i] = 0.5 * np.dot(varYtildeTdelta, self.varYTilde[:, i])
logger.debug('betas apost :')
logger.debug(np.array2string(self.beta, precision=3))
logger.debug('sigma2 ~betas/Ga(%1.3f,1)', 0.5 * (self.ny + 1))
gammaSamples = np.random.gamma(0.5 * (self.ny + 1), 1, self.nbVox)
self.currentValue = np.divide(self.beta, gammaSamples)
logger.debug('All noise vars :')
logger.debug(np.array2string(self.currentValue, precision=3))
logger.info('noise vars = %1.3f(%1.3f)', self.currentValue.mean(),
self.currentValue.std())
示例15: write_output
def write_output(self):
""" Write output file. """
text = ["# Input file for profit.py"]
text.append("a) {0} # Input table".format(self.table))
text.append("b) {0} # PSF type".format(self.psffunct))
text.append("c) {0} # PSF parameters".format(
np.array2string(self.psf, precision=3)[1:-1]))
text.append("c1) {0} # PSF parameters err".format(
np.array2string(self.psferr, precision=3)[1:-1]))
text.append("d) {0} # Convolution box".format(self.conv_box))
text.append("e) {0} # Weights for fitting".format(
self.header["e"]))
self.pfit = self.pfit.astype(np.float64)
self.perr = self.perr.astype(np.float64)
for idx, comp, comment in zip(self.idx, self.complist, \
self.complist_comments):
text.append("1) {0} @ {1} # Component type".format(comp, comment))
for j, i in enumerate(idx):
text.append("{0}) {1:.7f} {2} +/- {3:.5f} # {4}".format(
j+2, self.pfit[i], self.pfix[i], self.perr[i],
self.models[comp].comments[j]))
text.append("\n")
with open(self.outfile, "w") as f:
f.write("\n".join(text))
return