#!/usr/local/bin/py # Rajarshi Guha # 10/02/03 # # Reorders a HIN file so that hydrogens are all at the end # of the file, after the heavy atoms import shutil, os, string, sys, tempfile, copy if len(sys.argv) == 1: print """ Usage: reorder.py FILE1 FILE2 .... It will reorder the HIN files specified so that hydrogens are all at the end. It will write the new file to the old file, wiping out the previous contents """ sys.exit(0) for arg in sys.argv[1:]: try: f = open(arg,'r') except IOError: print """ Could'nt open file: %s. Skipped """ % (arg) llist = [] for line in f: if line == '\n': continue if string.find(line,'mol') >= 0: continue llist.append(line) f.close() numatom = len(llist) numh = 0 numo = 0 # Now find the num of H's for line in llist: if string.find(line,'H') > 0: numh += 1 numo = numatom - numh # make the map of old serial to new serial # First renumber the heavy atoms atommap = {} count = 1 for line in llist: line = string.split(line,' ') oldserial = line[1] sym = line[3] if sym == 'H' or sym == 'h': continue atommap[oldserial] = str(count) count += 1 # Now go through the list and renumber H's for line in llist: line = string.split(line,' ') oldserial = line[1] sym = line[3] if sym == 'H' or sym == 'h': atommap[oldserial] = str(count) count += 1 newllist = [] hlist = [] for line in llist: line = string.split(line) if line[3] == 'H' or line[3] == 'h': line[1] = atommap[ line[1] ] c = copy.deepcopy(line) for i in c[11:]: if i[0] not in string.digits: continue line[ c[11:].index(i) + 11 ] = atommap[i] hlist.append(string.join(line)) continue # Map the old serial's to their new values line[1] = atommap[ line[1] ] # Now transform the connection table c = copy.deepcopy(line) for i in c[11:]: if i[0] not in string.digits: continue line[ c[11:].index(i) + 11 ] = atommap[i] # Join the line and append to the new list newllist.append(string.join(line)) # Join the 2 lists newllist.extend(hlist) # Dump the transformed hin file fname = tempfile.mktemp() f = open(fname,'w') f.write('mol 1 '+arg+'\n') for line in newllist: f.write(line+'\n') f.write('endmol 1') f.close() shutil.copyfile(fname,arg) os.unlink(fname)