本文整理汇总了Python中numpy.array2string函数的典型用法代码示例。如果您正苦于以下问题:Python array2string函数的具体用法?Python array2string怎么用?Python array2string使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了array2string函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
开发者ID:hannes-brt,项目名称:FlowVB,代码行数:25,代码来源:flow_vb.py
示例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()))
开发者ID:Solvi,项目名称:pyhrf,代码行数:28,代码来源:noise.py
示例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")
开发者ID:eimrek,项目名称:atomistic_tools,代码行数:31,代码来源:cp2k_wfn_file.py
示例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))
开发者ID:brefsdal,项目名称:sherpa,代码行数:27,代码来源:__init__.py
示例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'
开发者ID:cactuskid,项目名称:structures_to_MSA,代码行数:25,代码来源:StrucutureToMSA.py
示例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)
开发者ID:BTY2684,项目名称:astropy,代码行数:34,代码来源:representation.py
示例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.)")
开发者ID:endolith,项目名称:numpy,代码行数:28,代码来源:test_arrayprint.py
示例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)
开发者ID:MiaoLi,项目名称:trimesh,代码行数:25,代码来源:export.py
示例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
)
开发者ID:jeffiar,项目名称:theano-learn,代码行数:7,代码来源:hinton.py
示例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
开发者ID:anetasie,项目名称:sherpa-old,代码行数:26,代码来源:simulate.py
示例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()
开发者ID:Chuzzle,项目名称:masters_thesis,代码行数:28,代码来源:plot.py
示例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)
开发者ID:OpenSourceBrain,项目名称:PotjansDiesmann2014,代码行数:26,代码来源:network.py
示例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
)
开发者ID:n0d,项目名称:astropy,代码行数:28,代码来源:representation.py
示例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())
开发者ID:ainafp,项目名称:pyhrf,代码行数:26,代码来源:noise.py
示例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
开发者ID:kadubarbosa,项目名称:profit,代码行数:25,代码来源:profit.py
示例16: test_0d_arrays
def test_0d_arrays(self):
unicode = type(u'')
assert_equal(unicode(np.array(u'café', np.unicode_)), u'café')
if sys.version_info[0] >= 3:
assert_equal(repr(np.array('café', np.unicode_)),
"array('café', dtype='<U4')")
else:
assert_equal(repr(np.array(u'café', np.unicode_)),
"array(u'caf\\xe9', dtype='<U4')")
assert_equal(str(np.array('test', np.str_)), 'test')
a = np.zeros(1, dtype=[('a', '<i4', (3,))])
assert_equal(str(a[0]), '([0, 0, 0],)')
assert_equal(repr(np.datetime64('2005-02-25')[...]),
"array('2005-02-25', dtype='datetime64[D]')")
assert_equal(repr(np.timedelta64('10', 'Y')[...]),
"array(10, dtype='timedelta64[Y]')")
# repr of 0d arrays is affected by printoptions
x = np.array(1)
np.set_printoptions(formatter={'all':lambda x: "test"})
assert_equal(repr(x), "array(test)")
# str is unaffected
assert_equal(str(x), "1")
# check `style` arg raises
assert_warns(DeprecationWarning, np.array2string,
np.array(1.), style=repr)
# but not in legacy mode
np.array2string(np.array(1.), style=repr, legacy='1.13')
开发者ID:madsbk,项目名称:numpy,代码行数:33,代码来源:test_arrayprint.py
示例17: test_unexpected_kwarg
def test_unexpected_kwarg(self):
# ensure than an appropriate TypeError
# is raised when array2string receives
# an unexpected kwarg
with assert_raises_regex(TypeError, 'nonsense'):
np.array2string(np.array([1, 2, 3]),
nonsense=None)
开发者ID:imshenny,项目名称:numpy,代码行数:8,代码来源:test_arrayprint.py
示例18: test_array2string
def test_array2string():
"""Basic test of array2string."""
a = np.arange(3)
assert_(np.array2string(a) == '[0 1 2]')
assert_(np.array2string(a, max_line_width=4) == '[0 1\n 2]')
stylestr = np.array2string(np.array(1.5),
style=lambda x: "Value in 0-D array: " + str(x))
assert_(stylestr == 'Value in 0-D array: 1.5')
开发者ID:ilustreous,项目名称:numpy,代码行数:8,代码来源:test_arrayprint.py
示例19: assert_frames_close
def assert_frames_close(actual, expected, **kwargs):
"""
Compare DataFrame items by column and
raise AssertionError if any column is not equal.
Ordering of columns is unimportant, items are compared only by label.
NaN and infinite values are supported.
Parameters
----------
actual: pandas.DataFrame
expected: pandas.DataFrame
kwargs:
Examples
--------
>>> assert_frames_close(pd.DataFrame(100, index=range(5), columns=range(3)),
... pd.DataFrame(100, index=range(5), columns=range(3)))
>>> assert_frames_close(pd.DataFrame(100, index=range(5), columns=range(3)),
... pd.DataFrame(110, index=range(5), columns=range(3)),
... rtol=.2)
>>> assert_frames_close(pd.DataFrame(100, index=range(5), columns=range(3)),
... pd.DataFrame(150, index=range(5), columns=range(3)),
... rtol=.2) # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
AssertionError:
...
References
----------
Derived from: http://nbviewer.jupyter.org/gist/jiffyclub/ac2e7506428d5e1d587b
"""
assert (isinstance(actual, pd.DataFrame) and
isinstance(expected, pd.DataFrame)), \
'Inputs must both be pandas DataFrames.'
assert set(expected.columns) == set(actual.columns), \
'test set columns must be equal to those in actual/observed set.'
assert np.all(np.equal(expected.index.values, actual.index.values)), \
'test set and actual set must share a common index' \
'instead found' + expected.index.values + 'vs' + actual.index.values
for col in expected.columns:
try:
assert_allclose(expected[col].values,
actual[col].values,
**kwargs)
except AssertionError as e:
assertion_details = 'Expected values: ' + np.array2string(expected[col].values, precision=2, separator=', ') + \
'\nActual values: ' + np.array2string(actual[col].values, precision=2, separator=',', suppress_small=True)
raise AssertionError('Column: ' + str(col) + ' is not close.\n' + assertion_details)
开发者ID:JamesPHoughton,项目名称:pysd,代码行数:56,代码来源:test_utils.py
示例20: test_wide_element
def test_wide_element(self):
a = np.array(['xxxxx'])
assert_equal(
np.array2string(a, max_line_width=5),
"['xxxxx']"
)
assert_equal(
np.array2string(a, max_line_width=5, legacy='1.13'),
"[ 'xxxxx']"
)
开发者ID:madsbk,项目名称:numpy,代码行数:10,代码来源:test_arrayprint.py
注:本文中的numpy.array2string函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论