0

I am beginning a code to create an array of coordinates of an FCC lattice. Here is my code so far, with helpful print statements:

def init_FCC(a, x_rep,y_rep,z_rep):
    n_atoms = 4*x_rep*y_rep*z_rep
    UC = array([[0, 0, 0],[(a/2),(a/2),0],[(a/2), 0, (a/2)],[0,(a/2),(a/2)]])
    coords = UC[:]
    print(array_equal(coords,UC))
    for n in range(x_rep):
        if array_equal(coords,UC) == False:
            coords = vstack((coords, UC))
        UC[:,0] += a
        print(UC,id(UC))
        print(coords,id(coords),'\n',60*'*')
    return(coords)

When using the function, for example a=5, x_rep=3, the print statements indicate that the if statement is never True, i.e. the arrays 'UC' and 'coords' are always the same. But as you can see, directly after the if statement I alter the first column of UC, but not coords, each time the for loop iterates. I checked the ids of each to ensure they are different memory locations. Why is the array coords changing when I alter UC, and how do I prevent this? As an after-note, I know this is probably not the best way to accomplish my end goal of creating an FCC lattice but I wanted to make my own code.

Thanks.

3
  • 1
    You are reassigning coords right here: coords = vstack((coords, UC)), hence the new memory location. Commented Aug 24, 2017 at 1:15
  • 1
    None of array, array_equal or v_stack are defined. Commented Aug 24, 2017 at 1:18
  • array, array_equal, and vstack are all numpy functions. As I stated in the question, the if statement is never True and the vstack operation is never executed. I verified this with separate print statements, apologies for not including that. Commented Aug 24, 2017 at 1:30

2 Answers 2

1

when you do varr_array2 = var_array1 you are just creating a new "label" for the same object, see these examples:

a = np.array([[0,0,0],[1,1,1], [2,2,2], [3,3,3]])
b = a

print (a is b)
True

c = a.copy()
print (a is c)
False

b[0] = [0,0,0]
print (a)
[[0 0 0]
 [1 1 1]
 [2 2 2]
 [3 3 3]]

c[0] = [9,9,9]
print (a)
[[0 0 0]
 [1 1 1]
 [2 2 2]
 [3 3 3]]

print(c)
[[9 9 9]
 [1 1 1]
 [2 2 2]
 [3 3 3]]

Conclusion: Use array.copy().

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, this solution works. However, I still do not understand why using coords = UC[:] or coords = list(UC) do not work. According to their ids, they are separate objects. Any insight?
0

coords = UC[:] provides an alternative view on the array, not a copy of it. You need coords = UC.copy().

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.