Here is the code:
import math
with open("test.stl") as file:
vertices = [map(float, line.split()[1:4])
for line in file
if line.lstrip().startswith('vertex')]
normals = [map(float, line.split()[2:5])
for line in file
if line.lstrip().startswith('facet')]
V=len(vertices)
ordering=[]
N=len(normals)
for i in range(0,N):
p1=vertices[3*i]
p2=vertices[3*i+1]
p3=verticies[3*i+2]
print p1
x1=p1[0]
y1=p1[1]
z1=p1[2]
x2=p2[0]
y2=p2[1]
z2=p2[2]
x3=p3[0]
y3=p3[1]
z3=p3[2]
a=[x2-x1,y2-y1,z2-z1]
b=[x3-x1,y3-y1,z3-z1]
a1=x2-x1
a2=y2-y1
a3=z2-z1
b1=x3-x1
b2=y3-y1
b3=z3-z1
normal=normals[i]
cross_vector=[a2*b3-a3*b2,a3*b1-a1*b3,a1*b2-a2*b1]
if cross_vector==normal:
ordering.append([i,i+1,i+2])
else:
ordering.append([i,i+2,i+1])
print ordering
print cross_vector
If I try to add print p1 (or any of the other variables such as cross_vector) inside of the for loop, there aren’t any errors but no output and if I try to print them outside of the for loop it says NameError: name ‘(variable name)’ is not defined. So if none of these variables are being defined, obviously my ordering array prints as [] (blank). How can I change this. Do variables have to be declared before they are defined?
Edit: Here is the error output when the code above is run:
Traceback (most recent call last):
File "convert.py", line 52, in <module>
print cross_vector
NameError: name 'cross_vector' is not defined
As explained above this happens with any variable defined in the for loop, I am just using cross_vector as an example.
To solve the problem diagnosed by DSM, use:
You might also want to try and drop the list comprehension, and work with iterators throughout, to save on memory for large files.
Edit:
At present, you load the entire file into memory, and then create two more full size lists in memory. Instead, you can write it in a way that only reads from the file in memory as required. As an example, we can replace the list comprehensions with generator comprehensions:
Here, we’ve avoided using any memory at all.
For this to be useful, you need to be able to replace your loop, from:
To a single iterator:
One way I can think of doing this is:
Which is the iterator equivalent of: