Sortcolumn.py
This script sorts the coordinates of the atoms in the POSCAR-file and outputs a sorted copy as POSCAR_sorted.
POSCAR_sorted is ready to go, so it can be named POSCAR and run in VASP like that (though it's always advisable to perform a visual check yourself).
The most important aspect in the sorting is to respect the groups of atom-types.
That's why the script takes first the column number to be sorted (from 1 to 3) and then the number of atoms per type in the right order (i.e. the line of atom numbers in the POSCAR).
To obtain the script copy the full source code below into your favourite text-editor and call the file (preferably) "sortcolumn.py".
Lastly make it executable with chmod u+x.
Disclaimer: Due to incompatibilities with Python versions older than Python 3, the script cannot be executed on Tekla2.
Source Code sortcolumn.py[edit]
#!/usr/bin/env python
##Instructions list: by default operates on the POSCAR-file.
##The program yields a POSCAR_sorted as output,
##which is identical to the original but with one column
##sorted by increasing value and respecting the number of elements.
##
##Input in the terminal the column number (1,2 or 3) to be sorted
##and then the for each atomtype the number of atoms.
import sys
filelines = 1000
offset = 2
digits = "{0:.10f}"
spaces = 8
l = len(sys.argv) - offset
if (l < offset):
print("Give me axis and the number of atoms per type so I can split the sorting")
sys.exit()
def getKey(item = []):
return item[int(sys.argv[1])-1]
f = open('POSCAR', mode='r')
s = open('POSCAR_sorted', mode='w')
for i in range(filelines):
temp = f.readline()
s.write(temp)
if (temp[0:3] == 'Car' or temp[0:3] == 'Dir'):
break
for j in range(offset, offset + l):
data = []
for i in range(int(sys.argv[j])):
temp = f.readline().split(' ')
temp = [x for x in temp if x != or x == '\n']
temp[0:3] = [float(x) for x in temp[0:3]]
data.append(temp)
data = sorted(data, key=lambda x: x[int(sys.argv[1])-1])
for i in range(0, len(data)-1):
if len(data[i]) == 3:
s.write(' '*spaces+str(digits.format(data[i][0]))+' '*spaces+str(digits.format(data[i][1]))+' '*spaces+str(digits.format(data[i][2]))+'\n')
elif len(data[i]) == 6:
s.write(' '*spaces+str(digits.format(data[i][0]))+' '*spaces+str(digits.format(data[i][1]))+' '*spaces+str(digits.format(data[i][2]))+" "+data[i][3]+" "+data[i][4]+" "+data[i][5])
else:
print("Check your coordinate format, buddy")
sys.exit()
for i in range(filelines):
temp = f.readline()
s.write(temp)
f.close()
s.close()
##Program written by N.Daelman on December the 1st 2016