user1967364
user1967364

Reputation: 99

Python: numpy shape to coordinate

I have a python script what adjusts coordinates of triangles towards the centre of gravity of the triangle. This works just fine, however to generate a workable output (i need to write a text file wich can be imported by other software, Abaqus) i want to write a coordinate list in a text file.

But i can't get this to work proparly. I think i first will need to create a list or tuple from the numpy array. However this doesn't work correctly. There's still an array per coordinate in this list.

How can i fix this? The script i currently have i shown below.

newcoords = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0], [0.0, 0.0], [1.0, 1.0], [0.0, 1.0]]
newelems = [[0, 1, 2], [3, 4, 5]]

import numpy as np

#define triangles
triangles = np.array([[newcoords[e] for e in newelem] for newelem in newelems])

#find centroid of each triangle
CM = np.mean(triangles,axis=1)

#find vector from each point in triangle pointing towards centroid
point_to_CM_vectors = CM[:,np.newaxis] - triangles

#calculate similar triangles 1% smaller
new_triangle = triangles + 0.01*point_to_CM_vectors

newcoord = []
newcoord.append(list(zip(*new_triangle)))
print 'newcoord =', newcoord

#generate output
fout = open('_PartInput3.inp','w')
print >> fout, '*Node-new_triangle'
for i,x in  enumerate(newcoord):
  print >> fout, i+1, ',', x[0], ',', x[1]
fout.close()

The coordinate list in the output file '_PartInput3.inp' should look the following:

*Node-new_triangle
1, 0.00333333,  0.00333333
2, 0.99333333,  0.00333333
3, 0.00333333,  0.99333333
4, 0.00333333,  0.00666667
5, 0.99333333,  0.99666667
6, 0.00333333,  0.99666667

Thanks in advance for any help!

Upvotes: 0

Views: 1307

Answers (1)

YXD
YXD

Reputation: 32511

#generate output
fout = open('_PartInput3.inp','w')
fout.write('*Node-new_triangle\n')
s = new_triangle.shape
for i, x in enumerate(new_triangle.reshape(s[0]*s[1], 2)):
    fout.write("{}, {}, {}\n".format(i+1, x[0], x[1]))
fout.close()

or better

#generate output
with open('_PartInput3.inp','w') as fout:
    fout.write('*Node-new_triangle\n')
    s = new_triangle.shape
    for i, x in enumerate(new_triangle.reshape(s[0]*s[1], 2)):
        fout.write("{}, {}, {}\n".format(i+1, x[0], x[1]))

Upvotes: 1

Related Questions