def main():
    """
    Reads a structure from a Gaussian Log file and other parameters from a
    Gaussian Com file and creates a new Gaussian Com.
    """
    args = get_args()
    gaulog = GaussianLog(args.log)
    gaucom = GaussianCom(args.template_com)
    atoms_log_coords = gaulog.read_geometry(args.opt_step, args.scan_step)
    for no, atom in enumerate(gaucom.atoms_list):
        atom.SetVector(atoms_log_coords[no].GetVector())
    gaucom.write_to_file(args.new_com)
def do_restart(gl, gver='d'):
    comname = os.path.splitext(gl.name)[0] + '.com'
    gc = GC(comname)
    for atom,xyz in zip(gc.atoms_list, gl.final_geometry):
        atom.SetVector(xyz.GetVector())
    newcomname = misc.increment_filename(comname)
    # reduce scan steps accordingly
    steps_done = len(gl.bytedict['orientation:'])-1
    print steps_done
    if steps_done:  
        print steps_done
        for modred in gc.modreds:
            if modred.action == 'S':# this FAILs for multi- scans
                modred.scan_num_pts -= steps_done
    gc.write_to_file(newcomname)
    queue = guess_queue(newcomname) 
    gsub(newcomname, queue, gver)
def main():
    try:
        opts, args = getopt.gnu_getopt(sys.argv[1:], 'f:d:')
    except getopt.GetoptError as err:
        sys.stderr.write(str(err) + '\n')

    if len(args) < 1:
        usage()
        print('Missing:')
        print('  gaussian_input.com')
        sys.exit(2)
    elif len(args) > 1:
        usage()
        print('Hey! Too many args:')
        print('  %s' % (', '.join(args)))

    gaussian_com_filename = args[0]
    new_folder_name = 'residel'
    freeze_angs = 15

    for o, a in opts:
        if o == '-f':   freeze_angs = float(a)
        if o == '-d':   new_folder_name = a

    if not os.path.exists("./{}".format(new_folder_name)):
        os.makedirs(new_folder_name)

    # input
    gaussian_file = GaussianCom(gaussian_com_filename)
    resID_dict = build_resID_dict(gaussian_file.atoms_list)

    # get xyz tuples
    highlayer_xyz = []
    all_xyz = []
    non_wat_xyz = []
    for i,atom in enumerate(gaussian_file.atoms_list):
        if atom.oniom.layer == 'H':
            highlayer_xyz.append((atom.GetX(), atom.GetY(), atom.GetZ()))
        if not atom.resinfo.resname == 'WAT' or atom.oniom.layer == 'H':
            non_wat_xyz.append((atom.GetX(), atom.GetY(), atom.GetZ()))
        all_xyz.append((atom.GetX(), atom.GetY(), atom.GetZ()))

    if not len(highlayer_xyz):
        print('WELL WELL...')
        print('     no highlayer defined, freezing nothing')
    else:
    # indexes to freeze
        CUTOFF = freeze_angs + 1.0
        freeze_idx = [False for _ in all_xyz]
        for (i,xyz) in enumerate(all_xyz):
            atom = gaussian_file.atoms_list[i]
            tofreeze = min_dist( [xyz] , highlayer_xyz, CUTOFF) <= freeze_angs
            freeze_idx[i] = tofreeze
            if atom.resinfo.resname == 'WAT' or atom.oniom.layer == 'H':
                freeze_idx[i] = False

        # byres
        freeze_idx = byres(resID_dict, freeze_idx)

    # residue selection
    res_2_go = list(set(get_resID(gaussian_file.atoms_list[i]) for i in np.where(freeze_idx)[0])) 

    atoms_list = gaussian_file.atoms_list
    residues_list = Molecule("protein", atoms_list).make_residues_list()
    
    input_list = []
    for no, residue in enumerate(residues_list):
        if get_resID(residue[0]) not in res_2_go:
            continue

        residue_number_name = "{0.resinfo.resnum}_{0.resinfo.resname}".format(residue[0])
        
        print(residue_number_name)
        incomplete_residues_list = Molecule("protein", atoms_list).make_residues_list()
        incomplete_residues_list.remove(residue)
        new_atoms_list = []
        for res in incomplete_residues_list:
            new_atoms_list.extend(res)
        gaussian_file.atoms_list = new_atoms_list
        gaussian_file.redo_connectivity_list()
        no_electrons = 0
        # correct link atom number and count total number of electrons
        for i, atom in enumerate(new_atoms_list):
            no_electrons += atom.GetAtomicNum()
            if atom.oniom.link_bound_to:
                if int(atom.oniom.link_bound_to) > atoms_list.index(residue[0]):
                    atom.oniom.link_bound_to = str(int(atom.oniom.link_bound_to) - len(residue))
        #correct charge and multiplicity
        new_protein = Molecule("new_protein", new_atoms_list)
        charge = sum([res.get_charge() for res in incomplete_residues_list])
        no_electrons -= round(charge)
        multiplicity = int(gaussian_file.multiplicity_line.split()[1])
        if (no_electrons%2==0 and multiplicity-1%2!=0) or (no_electrons%2==1 and multiplicity-1%2!=1):
            print("Number of electrons and multiplicity are not compatible. Charge increased arbitrarily by one")
            charge += 1
        gaussian_file.multiplicity_line = "{0} {1}\n".format(int(round(charge))," ".join(gaussian_file.multiplicity_line.split()[1:]))
        gaussian_name  = "{0}_{1}.com".format(gaussian_com_filename[:-4],residue_number_name)
        
        gaussian_file.write_to_file("{0}/{1}".format(new_folder_name, gaussian_name))
        input_list.append(gaussian_name)
    
    script_file_name = "{0}/{1}".format(new_folder_name,"run.sh")
    with open(script_file_name, 'w') as run_script:
        for job in input_list:
            out_name = job[:-4]+".log"
            run_script.write("g09 {0} {1}\n".format(job,out_name))
def main():

    gaussian_com_filename = sys.argv[1] 
    new_folder_name = os.path.splitext(sys.argv[1])[0]
    freeze_angs = 15 

    if not os.path.exists("./{}".format(new_folder_name)):
        os.makedirs(new_folder_name)

    # input
    gaussian_file = GaussianCom(gaussian_com_filename)
    resID_dict = build_resID_dict(gaussian_file.atoms_list)

    # get xyz tuples
    highlayer_xyz = []
    all_xyz = []
    non_wat_xyz = []   #all MM and non waters
    for i,atom in enumerate(gaussian_file.atoms_list):
        if atom.oniom.layer == 'H':
            highlayer_xyz.append((atom.GetX(), atom.GetY(), atom.GetZ()))
        if not atom.resinfo.resname == 'WAT' or atom.oniom.layer == 'H':
            non_wat_xyz.append((atom.GetX(), atom.GetY(), atom.GetZ()))
        all_xyz.append((atom.GetX(), atom.GetY(), atom.GetZ()))

    if not len(highlayer_xyz):
        print('WELL WELL...')
        print('     no highlayer defined, freezing nothing')
    else:
    # indexes to freeze [list of atoms to "freeze"]
        CUTOFF = freeze_angs + 1.0
        freeze_idx = [False for _ in all_xyz]
        for (i,xyz) in enumerate(all_xyz):
            atom = gaussian_file.atoms_list[i]
            tofreeze = min_dist( [xyz] , highlayer_xyz, CUTOFF) <= freeze_angs
            freeze_idx[i] = tofreeze
            if atom.resinfo.resname == 'WAT' or atom.oniom.layer == 'H':
                freeze_idx[i] = False

        # byres - returns the same freeze_idx list, but if at least one atom is true, then changes all to True
        freeze_idx = byres(resID_dict, freeze_idx)

    # residue selection [list of tuples (resn, resid)]
    res_2_go = list(set(get_resID(gaussian_file.atoms_list[i]) for i in np.where(freeze_idx)[0])) 

    old_atoms_list = gaussian_file.atoms_list
    residues_list = Molecule("protein", old_atoms_list).make_residues_list()

    # do the magic
    for no, residue in enumerate(residues_list):
        if get_resID(residue[0]) not in res_2_go:
            continue
        
        #NOTA: a lista de residues (residue[0]) parece uma [lista de residues[lista atoms]] devo conseguir descompactar isto
        resname = residue[0].resinfo.resname
        resid = residue[0].resinfo.resnum
        residue_number_name = "{0}_{1}".format(resname,resid)

        original_charges = zerate_res_charge(old_atoms_list, (resname, resid))
        
        #print(residue_number_name)

        gaussian_name  = "{0}_{1}.com".format(
            gaussian_com_filename[:-4],
            residue_number_name
        )
        gaussian_file.write_to_file("{0}/{1}".format(
            new_folder_name,
            gaussian_name)
        )
        reset_res_charge(old_atoms_list, (resname, resid), original_charges)
Пример #5
0
        sys.stderr.write(
            '    --target/--nsteps/--stepsize only with --Bscan\n')
        sys.exit(2)


def getdist(a, b, gc):
    x1 = gc.atoms_list[a - 1].GetX()
    y1 = gc.atoms_list[a - 1].GetY()
    z1 = gc.atoms_list[a - 1].GetZ()
    x2 = gc.atoms_list[b - 1].GetX()
    y2 = gc.atoms_list[b - 1].GetY()
    z2 = gc.atoms_list[b - 1].GetZ()
    return geom.distance((x1, y1, z1), (x2, y2, z2))


gc = GC(args.COM)

# handle existing modreds
if args.keep:
    new_modred = gc.modreds
elif args.delete:
    new_modred = [m for m in gc.modreds if m.action not in ['S', 'F']]
elif args.deleteALL:
    new_modred = []

# check conflicts
to_add = []
if args.Bfreeze:
    to_add += args.Bfreeze
if args.Bscan:
    to_add += [args.Bscan]
    if args.nsteps or args.stepsize or args.target:
        parser.print_help()
        sys.stderr.write('\ngscan.py: error:\n')
        sys.stderr.write('    --target/--nsteps/--stepsize only with --Bscan\n')
        sys.exit(2)

def getdist(a,b,gc):
    x1 = gc.atoms_list[a-1].GetX()
    y1 = gc.atoms_list[a-1].GetY()
    z1 = gc.atoms_list[a-1].GetZ()
    x2 = gc.atoms_list[b-1].GetX()
    y2 = gc.atoms_list[b-1].GetY()
    z2 = gc.atoms_list[b-1].GetZ()
    return geom.distance((x1, y1, z1), (x2, y2, z2))

gc = GC(args.COM)

# handle existing modreds
if args.keep:
    new_modred = gc.modreds
elif args.delete:
    new_modred = [m for m in gc.modreds if m.action not in ['S', 'F']]
elif args.deleteALL:
    new_modred = []

# check conflicts
to_add = []
if args.Bfreeze:
    to_add += args.Bfreeze
if args.Bscan:
    to_add += [args.Bscan]
def main():
    
    try:
        opts, args = getopt.gnu_getopt(sys.argv[1:], 'f:o:m:wd:', ['keep='])
    except getopt.GetoptError as err:
        sys.stderr.write(err + '\n')
        usage()
        sys.exit(2)
    
    if len(args) < 1:
        usage()
        print('missing:')
        print('  gaussian_input.com')
        sys.exit(2)
    elif len(args) > 1:
        usage()
        print('too many args:')
        print('  %s' % (','.join(args)))
    
    filein = args[0]
    basename, input_extension = splitext(filein)
    if input_extension != '.com':
        print('WARNING:')
        print('  inputname suffix is: %s' % input_extension)
    
    # defaults
    outputname = basename + '.frost.com'
    freeze_angs = False
    freeze_mm_wat = False
    del_wat_angs = False
    keep_N_wat = False
    MASK = -1
    
    # provided input
    for o, a in opts:
        if o == '-f':   freeze_angs = float(a)
        elif o == '-o': outputname = a 
        elif o == '-w': freeze_mm_wat = True
        elif o == '-m': MASK = int(a)
        elif o == '-d': del_wat_angs = float(a)
        elif o == '--keep': keep_N_wat = int(a)
    
    # input
    gaucom = GAUCOM(filein)
    resID_dict = build_resID_dict(gaucom.atoms_list)


    # get xyz tuples
    highlayer_xyz = []
    all_xyz = []
    non_wat_xyz = []
    for i,atom in enumerate(gaucom.atoms_list):
        if atom.oniom.layer == 'H':
            highlayer_xyz.append((atom.GetX(), atom.GetY(), atom.GetZ()))
        if not atom.resinfo.resname == 'WAT' or atom.oniom.layer == 'H':
            non_wat_xyz.append((atom.GetX(), atom.GetY(), atom.GetZ()))
        all_xyz.append((atom.GetX(), atom.GetY(), atom.GetZ()))

    if not len(highlayer_xyz) and freeze_angs:
        print('WELL WELL...')
        print('     no highlayer defined, freezing nothing')
        sys.exit()
    elif freeze_angs == False:
        freeze_idx = [False for _ in all_xyz]        
        if freeze_mm_wat:
            for (i,xyz) in enumerate(all_xyz):
                atom = gaucom.atoms_list[i]
                freeze_idx[i] = (atom.oniom.layer=='L' and
                    atom.resinfo.resname=='WAT')
    else:
        # indexes to freeze
        CUTOFF = freeze_angs + 1.0
        freeze_idx = [False for _ in all_xyz]
        for (i,xyz) in enumerate(all_xyz):
            atom = gaucom.atoms_list[i]
            tofreeze = min_dist( [xyz] , highlayer_xyz, CUTOFF) >= freeze_angs
            tofreeze = tofreeze or (freeze_mm_wat and 
                atom.oniom.layer=='L' and atom.resinfo.resname=='WAT')
            freeze_idx[i] = tofreeze


    # byres
    freeze_idx = byres(resID_dict, freeze_idx)

    # freeze now
    for (i, at) in enumerate(gaucom.atoms_list):
        if freeze_idx[i]:
            at.oniom.mask = MASK


    # delete waters?
    del_idx = [False for _ in all_xyz]
    if del_wat_angs:
        CUTOFF = del_wat_angs + 1.0
        for (i,xyz) in enumerate(all_xyz):
            atom = gaucom.atoms_list[i]
            del_idx[i] = (
                (min_dist([xyz], highlayer_xyz, CUTOFF) <= del_wat_angs) and
                (atom.resinfo.resname == 'WAT') and
                (atom.oniom.layer == 'L')
                         )
        del_idx = byresTrue(resID_dict, del_idx)

    if keep_N_wat:
        dists = []
        for resID in resID_dict:
            if resID[0] == 'WAT':
                waters = [gaucom.atoms_list[i] for i in resID_dict[resID]]
                if 'H' not in [a.oniom.layer for a in waters]:
                    xyz = [(atom.GetX(), atom.GetY(), atom.GetZ()) for a in waters]
                    dists.append((resID, min_dist(xyz, non_wat_xyz)))
            if (i+1)%1001 == 0:
                print(i)
        dists.sort(key=lambda x: x[1])

        # update del_idx
        for (resID, dist) in dists[keep_N_wat:]:
            for i in resID_dict[resID]:
                del_idx[i] = True
        

    if keep_N_wat or del_wat_angs:

        del_idx = byres(resID_dict, del_idx)
        print('Deleted atoms: %d' % (del_idx.count(True)))

        # delete atoms
        new_atoms_list = []
        deleted = []
        for (i,atom) in enumerate(gaucom.atoms_list):
            if not del_idx[i]:
                new_atoms_list.append(atom)
            else:
                atom.set_pdbinfo(atoms.PDBinfo('ATOM', i))
                atom.pdbinfo.altloc = atom.oniom.layer
                deleted.append(atom)

        # write pdb with deleted atoms
        write_pdb('%s.delwat.pdb' % (outputname), deleted)
        

        # update atoms list
        gaucom.atoms_list = new_atoms_list
        gaucom.redo_connectivity_list() # works for TS structures?
        
    # print pdb copy of model by mask
    topdb_dict = {}
    for (i,atom) in enumerate(gaucom.atoms_list):
        mask = atom.oniom.mask
        atom.set_pdbinfo(atoms.PDBinfo('ATOM', i))
        atom.pdbinfo.altloc = atom.oniom.layer
        if mask not in topdb_dict:
            topdb_dict[mask] = []
        topdb_dict[mask].append(atom)

    for mask in topdb_dict:
        write_pdb('%s.%d.pdb' % (outputname, mask), topdb_dict[mask])

    # write output
    gaucom.write_to_file(outputname)

    return 0