def export_collada(mesh):
'''
Export a mesh as a COLLADA file.
'''
from ..templates import get_template
from string import Template
template_string = get_template('collada.dae.template')
template = Template(template_string)
# 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 export
python类array2string()的实例源码
def var_label(var, precision=3):
"""Return label of variable node."""
if var.name is not None:
return var.name
elif isinstance(var, gof.Constant):
h = np.asarray(var.data)
is_const = False
if h.ndim == 0:
is_const = True
h = np.array([h])
dstr = np.array2string(h, precision=precision)
if '\n' in dstr:
dstr = dstr[:dstr.index('\n')]
if is_const:
dstr = dstr.replace('[', '').replace(']', '')
return dstr
else:
return type_to_str(var.type)
def _format_items(items):
formatter = lambda x: '%.3e' % x
last_large_output = None
for key, value in items:
value = np.asarray(value)
large_output = value.ndim >= 1
# If there was a previous output, print a separator.
if last_large_output is not None:
yield '\n' if large_output or last_large_output else ' '
format_string = '%s:\n%s' if large_output else '%s: %s'
yield format_string % (key,
np.array2string(value, style=formatter,
formatter={'float_kind': formatter}))
last_large_output = large_output
def _format_items(items):
formatter = lambda x: '%.3e' % x
last_large_output = None
for key, value in items:
value = np.asarray(value)
large_output = value.ndim >= 1
# If there was a previous output, print a separator.
if last_large_output is not None:
yield '\n' if large_output or last_large_output else ' '
format_string = '%s:\n%s' if large_output else '%s: %s'
yield format_string % (key,
np.array2string(value, style=formatter,
formatter={'float_kind': formatter}))
last_large_output = large_output
def test_basic(self):
"""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]')
def test_style_keyword(self):
"""This should only apply to 0-D arrays. See #1218."""
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')
def test_format_function(self):
"""Test custom format function for each element in array."""
def _format_function(x):
if np.abs(x) < 1:
return '.'
elif np.abs(x) < 2:
return 'o'
else:
return 'O'
x = np.arange(3)
if sys.version_info[0] >= 3:
x_hex = "[0x0 0x1 0x2]"
x_oct = "[0o0 0o1 0o2]"
else:
x_hex = "[0x0L 0x1L 0x2L]"
x_oct = "[0L 01L 02L]"
assert_(np.array2string(x, formatter={'all':_format_function}) ==
"[. o O]")
assert_(np.array2string(x, formatter={'int_kind':_format_function}) ==
"[. o O]")
assert_(np.array2string(x, formatter={'all':lambda x: "%.4f" % x}) ==
"[0.0000 1.0000 2.0000]")
assert_equal(np.array2string(x, formatter={'int':lambda x: hex(x)}),
x_hex)
assert_equal(np.array2string(x, formatter={'int':lambda x: oct(x)}),
x_oct)
x = np.arange(3.)
assert_(np.array2string(x, formatter={'float_kind':lambda x: "%.2f" % x}) ==
"[0.00 1.00 2.00]")
assert_(np.array2string(x, formatter={'float':lambda x: "%.2f" % x}) ==
"[0.00 1.00 2.00]")
s = np.array(['abc', 'def'])
assert_(np.array2string(s, formatter={'numpystr':lambda s: s*2}) ==
'[abcabc defdef]')
def test_datetime_array_str(self):
a = np.array(['2011-03-16', '1920-01-01', '2013-05-19'], dtype='M')
assert_equal(str(a), "['2011-03-16' '1920-01-01' '2013-05-19']")
a = np.array(['2011-03-16T13:55', '1920-01-01T03:12'], dtype='M')
assert_equal(np.array2string(a, separator=', ',
formatter={'datetime': lambda x:
"'%s'" % np.datetime_as_string(x, timezone='UTC')}),
"['2011-03-16T13:55Z', '1920-01-01T03:12Z']")
# Check that one NaT doesn't corrupt subsequent entries
a = np.array(['2010', 'NaT', '2030']).astype('M')
assert_equal(str(a), "['2010' 'NaT' '2030']")
def arr2str(a):
return np.array2string(a, max_line_width=np.inf, separator=',',
precision=None, suppress_small=None).replace('\n', '')
def periodicDataDump(filename,d):
"""
dump a ndarray to disk. If first time, just dump it.
Else, load current ary and cat d to it before dumping.
"""
old=True
if len(d)!=0:
if os.path.exists(filename):
if old:
d0 = np.load(filename)
np.save(filename,np.concatenate((d0,d)))
else:
with open(filename,'a') as outfile:
for i in range(0,d.shape[0]):
outstr = ''
for val in d[i]:
outstr+='%.14g ' % (val)
outstr += '\n'
outfile.write(outstr)#nparyTolistStr(d[i],brackets=False,dmtr=' ')+'\n')
#outfile.write(re.sub("\n ","\n",re.sub("[\\[\\]]","",np.array2string(d,precision=16))))
else:
if old:
np.save(filename,d)
else:
with open(filename,'w') as outfile:
for i in range(0,d.shape[0]):
outstr = ''
for val in d[i]:
outstr+='%.14g ' % (val)
outstr += '\n'
outfile.write(outstr)#nparyTolistStr(d[i],brackets=False,dmtr=' '))
#outfile.write(re.sub("\n ","\n",re.sub("[\\[\\]]","",np.array2string(d))))
#print nparyTolistStr(d[i],brackets=False,dmtr=' ')
#raise IOError('\n\n'+s)
def test_basic(self):
"""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]')
def test_style_keyword(self):
"""This should only apply to 0-D arrays. See #1218."""
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')
def test_format_function(self):
"""Test custom format function for each element in array."""
def _format_function(x):
if np.abs(x) < 1:
return '.'
elif np.abs(x) < 2:
return 'o'
else:
return 'O'
x = np.arange(3)
if sys.version_info[0] >= 3:
x_hex = "[0x0 0x1 0x2]"
x_oct = "[0o0 0o1 0o2]"
else:
x_hex = "[0x0L 0x1L 0x2L]"
x_oct = "[0L 01L 02L]"
assert_(np.array2string(x, formatter={'all':_format_function}) ==
"[. o O]")
assert_(np.array2string(x, formatter={'int_kind':_format_function}) ==
"[. o O]")
assert_(np.array2string(x, formatter={'all':lambda x: "%.4f" % x}) ==
"[0.0000 1.0000 2.0000]")
assert_equal(np.array2string(x, formatter={'int':lambda x: hex(x)}),
x_hex)
assert_equal(np.array2string(x, formatter={'int':lambda x: oct(x)}),
x_oct)
x = np.arange(3.)
assert_(np.array2string(x, formatter={'float_kind':lambda x: "%.2f" % x}) ==
"[0.00 1.00 2.00]")
assert_(np.array2string(x, formatter={'float':lambda x: "%.2f" % x}) ==
"[0.00 1.00 2.00]")
s = np.array(['abc', 'def'])
assert_(np.array2string(s, formatter={'numpystr':lambda s: s*2}) ==
'[abcabc defdef]')
def test_datetime_array_str(self):
a = np.array(['2011-03-16', '1920-01-01', '2013-05-19'], dtype='M')
assert_equal(str(a), "['2011-03-16' '1920-01-01' '2013-05-19']")
a = np.array(['2011-03-16T13:55', '1920-01-01T03:12'], dtype='M')
assert_equal(np.array2string(a, separator=', ',
formatter={'datetime': lambda x:
"'%s'" % np.datetime_as_string(x, timezone='UTC')}),
"['2011-03-16T13:55Z', '1920-01-01T03:12Z']")
# Check that one NaT doesn't corrupt subsequent entries
a = np.array(['2010', 'NaT', '2030']).astype('M')
assert_equal(str(a), "['2010' 'NaT' '2030']")
def __repr__(self):
if len(self.data) >= 1:
str = '-----------------------------------------\n'
for each in self._list:
array = np.asarray(each)
str = str + np.array2string(array) \
+ '\n-----------------------------------------\n'
return str.rstrip("\n") # Remove trailing newline character
else:
return 'No matrix found'
def matrix_mismatch_string_builder(rec_mat, exp_mat):
expected_mat_str = np.array2string(np.asarray(exp_mat))
received_mat_str = np.array2string(np.asarray(rec_mat))
output_str = str("\n----------------------\n"
+ " Expected Output "
+ "\n----------------------\n"
+ expected_mat_str
+ "\n----------------------\n"
+ " Received Output "
+ "\n----------------------\n"
+ received_mat_str)
return output_str
test_arrayprint.py 文件源码
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda
作者: SignalMedia
项目源码
文件源码
阅读 25
收藏 0
点赞 0
评论 0
def test_basic(self):
"""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]')
test_arrayprint.py 文件源码
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda
作者: SignalMedia
项目源码
文件源码
阅读 27
收藏 0
点赞 0
评论 0
def test_style_keyword(self):
"""This should only apply to 0-D arrays. See #1218."""
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')
test_arrayprint.py 文件源码
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda
作者: SignalMedia
项目源码
文件源码
阅读 30
收藏 0
点赞 0
评论 0
def test_format_function(self):
"""Test custom format function for each element in array."""
def _format_function(x):
if np.abs(x) < 1:
return '.'
elif np.abs(x) < 2:
return 'o'
else:
return 'O'
x = np.arange(3)
if sys.version_info[0] >= 3:
x_hex = "[0x0 0x1 0x2]"
x_oct = "[0o0 0o1 0o2]"
else:
x_hex = "[0x0L 0x1L 0x2L]"
x_oct = "[0L 01L 02L]"
assert_(np.array2string(x, formatter={'all':_format_function}) ==
"[. o O]")
assert_(np.array2string(x, formatter={'int_kind':_format_function}) ==
"[. o O]")
assert_(np.array2string(x, formatter={'all':lambda x: "%.4f" % x}) ==
"[0.0000 1.0000 2.0000]")
assert_equal(np.array2string(x, formatter={'int':lambda x: hex(x)}),
x_hex)
assert_equal(np.array2string(x, formatter={'int':lambda x: oct(x)}),
x_oct)
x = np.arange(3.)
assert_(np.array2string(x, formatter={'float_kind':lambda x: "%.2f" % x}) ==
"[0.00 1.00 2.00]")
assert_(np.array2string(x, formatter={'float':lambda x: "%.2f" % x}) ==
"[0.00 1.00 2.00]")
s = np.array(['abc', 'def'])
assert_(np.array2string(s, formatter={'numpystr':lambda s: s*2}) ==
'[abcabc defdef]')
test_datetime.py 文件源码
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda
作者: SignalMedia
项目源码
文件源码
阅读 25
收藏 0
点赞 0
评论 0
def test_datetime_array_str(self):
a = np.array(['2011-03-16', '1920-01-01', '2013-05-19'], dtype='M')
assert_equal(str(a), "['2011-03-16' '1920-01-01' '2013-05-19']")
a = np.array(['2011-03-16T13:55Z', '1920-01-01T03:12Z'], dtype='M')
assert_equal(np.array2string(a, separator=', ',
formatter={'datetime': lambda x:
"'%s'" % np.datetime_as_string(x, timezone='UTC')}),
"['2011-03-16T13:55Z', '1920-01-01T03:12Z']")
# Check that one NaT doesn't corrupt subsequent entries
a = np.array(['2010', 'NaT', '2030']).astype('M')
assert_equal(str(a), "['2010' 'NaT' '2030']")
def __str__(self):
formatter = {'float_kind': lambda x: "{: 7.1f}".format(x) }
mmsiStr = " MMSI {:} ".format(self.mmsi) if self.mmsi is not None else ""
predStateStr = ("Pred state:" + np.array2string(self.predicted_state,
precision=1,
suppress_small=True,
formatter=formatter)
if self.predicted_state is not None else "")
return ("State: " + np.array2string(self.state, precision=1, suppress_small=True,formatter=formatter) +
" ({0:}|{1:}) ".format(self.m, self.n) +
predStateStr +
mmsiStr)
def __str__(self):
timeString = self.getTimeString()
mmsiString = 'MMSI: ' + str(self.mmsi) if self.mmsi is not None else ""
return ('Time: ' + timeString + " " +
'State:' + np.array2string(self.state, formatter={'float_kind': lambda x: '{: 7.1f}'.format(x)}) + " " +
'High accuracy: {:1} '.format(self.highAccuracy) +
mmsiString)
def test_basic(self):
"""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]')
def test_style_keyword(self):
"""This should only apply to 0-D arrays. See #1218."""
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')
def test_format_function(self):
"""Test custom format function for each element in array."""
def _format_function(x):
if np.abs(x) < 1:
return '.'
elif np.abs(x) < 2:
return 'o'
else:
return 'O'
x = np.arange(3)
if sys.version_info[0] >= 3:
x_hex = "[0x0 0x1 0x2]"
x_oct = "[0o0 0o1 0o2]"
else:
x_hex = "[0x0L 0x1L 0x2L]"
x_oct = "[0L 01L 02L]"
assert_(np.array2string(x, formatter={'all':_format_function}) ==
"[. o O]")
assert_(np.array2string(x, formatter={'int_kind':_format_function}) ==
"[. o O]")
assert_(np.array2string(x, formatter={'all':lambda x: "%.4f" % x}) ==
"[0.0000 1.0000 2.0000]")
assert_equal(np.array2string(x, formatter={'int':lambda x: hex(x)}),
x_hex)
assert_equal(np.array2string(x, formatter={'int':lambda x: oct(x)}),
x_oct)
x = np.arange(3.)
assert_(np.array2string(x, formatter={'float_kind':lambda x: "%.2f" % x}) ==
"[0.00 1.00 2.00]")
assert_(np.array2string(x, formatter={'float':lambda x: "%.2f" % x}) ==
"[0.00 1.00 2.00]")
s = np.array(['abc', 'def'])
assert_(np.array2string(s, formatter={'numpystr':lambda s: s*2}) ==
'[abcabc defdef]')
def test_datetime_array_str(self):
a = np.array(['2011-03-16', '1920-01-01', '2013-05-19'], dtype='M')
assert_equal(str(a), "['2011-03-16' '1920-01-01' '2013-05-19']")
a = np.array(['2011-03-16T13:55Z', '1920-01-01T03:12Z'], dtype='M')
assert_equal(np.array2string(a, separator=', ',
formatter={'datetime': lambda x:
"'%s'" % np.datetime_as_string(x, timezone='UTC')}),
"['2011-03-16T13:55Z', '1920-01-01T03:12Z']")
# Check that one NaT doesn't corrupt subsequent entries
a = np.array(['2010', 'NaT', '2030']).astype('M')
assert_equal(str(a), "['2010' 'NaT' '2030']")
def main():
n_particles = 6
bounds = [(-0.7, 0.7)] * (3 * n_particles)
np.random.seed(1)
ret = sda(sutton_chen, None, bounds=bounds)
# np.set_printoptions(precision=4)
print('xmin =\n{}'.format(np.array2string(ret.x, max_line_width=40)))
print("global minimum: f(xmin) = {}".format(ret.fun))
def check_mixed_mode(vis,mode):
logger.info('Check for mixed mode')
tb.open(vis + '/SPECTRAL_WINDOW')
bw_spw = np.array(tb.getcol('TOTAL_BANDWIDTH'))
tb.close()
if len(np.unique(bw_spw)) != 1:
if mode == 'split':
logger.info('Splitting continuum from spectral line')
cont_spw = np.where(bw_spw==np.max(np.unique(bw_spw)))[0]
print np.array2string(cont_spw, separator=',')[1:-1]
split(vis=vis, outputvis=vis+'.continuum', spw=np.array2string(cont_spw, separator=',')[1:-1], datacolumn='data')
spec_line = np.delete(bw_spw, cont_spw)
logger.info('Splitting spectral line')
for i in range(len(np.unique(spec_line))):
spec_line_spw = np.where(bw_spw==np.unique(spec_line)[i])[0]
split(vis=vis, outputvis=vis+'.sp{0}'.format(i), spw=np.array2string(spec_line_spw, separator=',')[1:-1],datacolumn='data')
ms.writehistory(message='eMER_CASA_Pipeline: Spectral line split from {0}'.format(vis),msname=vis+'.sp{0}'.format(i))
ms.writehistory(message='eMER_CASA_Pipeline: Spectral lines split from this ms',msname=vis)
os.system('mv {0} {1}'.format(vis, vis+'.original'))
os.system('mv {0} {1}'.format(vis+'.continuum', vis))
logger.info('Will continue with continuum, original data is {0}'.format(vis+'.original'))
return_variable = ''
if mode == 'check':
logger.info('MS is mixed mode. Please split')
return_variable = True
else:
if mode == 'split':
logger.info('Not mixed mode, continuing')
return_variable = ''
if mode == 'check':
return_variable = False
return return_variable
def test_basic(self):
"""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]')
def test_style_keyword(self):
"""This should only apply to 0-D arrays. See #1218."""
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')