示例#1
0
def runtestgeo(tmpdir, name, thresh, deleteH=True, geo_type="oct"):
    initgeo = resource_filename(Requirement.parse("molSimplify"),
                                "tests/inputs/geocheck/" + name + "/init.xyz")
    optgeo = resource_filename(Requirement.parse("molSimplify"),
                               "tests/inputs/geocheck/" + name + "/opt.xyz")
    refjson = resource_filename(Requirement.parse("molSimplify"),
                                "tests/refs/geocheck/" + name + "/ref.json")
    mymol = mol3D()
    mymol.readfromxyz(optgeo)
    init_mol = mol3D()
    init_mol.readfromxyz(initgeo)
    if geo_type == "oct":
        _, _, dict_struct_info = mymol.IsOct(init_mol=init_mol,
                                             debug=False,
                                             flag_deleteH=deleteH)
    elif geo_type == "one_empty":
        _, _, dict_struct_info = mymol.IsStructure(
            init_mol=init_mol,
            dict_check=dict_oneempty_check_st,
            angle_ref=oneempty_angle_ref,
            num_coord=5,
            debug=False,
            flag_deleteH=deleteH)
    with open(refjson, "r") as fo:
        dict_ref = json.load(fo)
    # passGeo = (sorted(dict_ref.items()) == sorted(dict_struct_info.items()))
    print("ref: ", dict_ref)
    print("now: ", dict_struct_info)
    passGeo = comparedict(dict_ref, dict_struct_info, thresh)
    return passGeo
示例#2
0
def getAllLigands(xyz):
    mymol3d = mol3D()
    mymol3d.readfromxyz(xyz)
    # OUTPUT
    #   -mol3D: mol3D of all ligands
    mm = mymol3d.findMetal()[0]
    mbonded = mymol3d.getBondedAtoms(mm)
    ligands=[]
    ligAtoms=[]
    #Get the 1st atom of one ligand
    for iatom in mbonded:
        if iatom not in ligAtoms:
           lig = [iatom]
           oldlig = []
           while len(lig) > len(oldlig):
               #make a copy of lig
               oldlig = lig[:]
               for i in oldlig:
                   lbonded = mymol3d.getBondedAtoms(i)
                   for j in lbonded:
                       if (j != mm) and (j not in lig):
                           lig.append(j)
           newlig = mol3D()
           for i in lig:
               newlig.addAtom(mymol3d.atoms[i])
               ligAtoms.append(i)
           ligands.append(newlig)
    print "Ligand analysis of xyz file: ",xyz
    print "There are ",len(ligands)," ligand(s) bonded with metal center\
            ",mm," in the complex"
    for i in range(0,len(ligands)):
        print "Number of atoms in ligand # ",i," : ",ligands[i].natoms
    return ligands
示例#3
0
def getAllLigands(xyz):
    mymol3d = mol3D()
    mymol3d.readfromxyz(xyz)
    # OUTPUT
    #   -mol3D: mol3D of all ligands
    mm = mymol3d.findMetal()[0]
    mbonded = mymol3d.getBondedAtoms(mm)
    ligands = []
    ligAtoms = []
    # Get the 1st atom of one ligand
    for iatom in mbonded:
        if iatom not in ligAtoms:
            lig = [iatom]
            oldlig = []
            while len(lig) > len(oldlig):
                # make a copy of lig
                oldlig = lig[:]
                for i in oldlig:
                    lbonded = mymol3d.getBondedAtoms(i)
                    for j in lbonded:
                        if (j != mm) and (j not in lig):
                            lig.append(j)
            newlig = mol3D()
            for i in lig:
                newlig.addAtom(mymol3d.atoms[i])
                ligAtoms.append(i)
            ligands.append(newlig)
    print("Ligand analysis of xyz file: ", xyz)
    print("There are ", len(ligands), " ligand(s) bonded with metal center\
            ", mm, " in the complex")
    for i in range(0, len(ligands)):
        print("Number of atoms in ligand # ", i, " : ", ligands[i].natoms)
    return ligands
示例#4
0
def get_geo_metrics(init_mol, job_info, geofile):
    mol_now = read_geometry_to_mol(geofile)
    dict_geo_metrics = {}
    info_list = ['flag_oct']
    dict_info = ['inspect_oct_angle_devi_max', 'inspect_max_del_sig_angle',
                 'inspect_dist_del_all', 'inspect_dist_del_eq', 'inspect_devi_linear_avrg',
                 'inspect_devi_linear_max']
    actural_dict_info = ['actural_rmsd_max']
    mol = mol3D()
    mol.copymol3D(mol_now)
    inspect_flag, _, dict_oct, inspect_flag_loose, _ = mol.Oct_inspection(init_mol=init_mol,
                                                                          catoms_arr=job_info['catoms'])
    _mol = mol3D()
    _mol.copymol3D(mol_now)
    flag_oct, _, dict_oct_info = _mol.IsOct(init_mol=init_mol)
    actural_dict_geo = {}
    inspect_dict_geo = {}
    for key in dict_oct_info:
        val = dict_oct_info[key] if (dict_oct_info[key] != -1) and (dict_oct_info[key] != "lig_mismatch") else 1.20 * dict_oct_check_st[key]
        actural_dict_geo['actural_%s' % key] = val
    for key in dict_oct:
        inspect_dict_geo['inspect_%s' % key] = dict_oct[key]
    for info in info_list:
        dict_geo_metrics.update({info: locals()[info]})
    for info in dict_info:
        dict_geo_metrics.update({info: inspect_dict_geo[info]})
    for info in actural_dict_info:
        dict_geo_metrics.update({info: actural_dict_geo[info]})
    return dict_geo_metrics
示例#5
0
def compareNumAtoms(xyz1,xyz2):
    print "Checking total number of atoms"
    mol1 = mol3D()
    mol1.readfromxyz(xyz1)
    mol2 = mol3D()
    mol2.readfromxyz(xyz1)
   # Compare number of atoms
    passNumAtoms = (mol1.natoms == mol2.natoms)
    print "Pass total number of atoms check: ",passNumAtoms
    return passNumAtoms
示例#6
0
def freeze_bottom_n_layers(super_cell, n):
    frozen_cell = mol3D()
    frozen_cell.copymol3D(super_cell)
    counter = 0
    while counter < n:
        frozen_cell_new = freeze_under_layer(frozen_cell)
        frozen_cell = mol3D()
        frozen_cell.copymol3D(frozen_cell_new)
        counter += 1
    return frozen_cell
示例#7
0
def compareNumAtoms(xyz1, xyz2):
    print("Checking total number of atoms")
    mol1 = mol3D()
    mol1.readfromxyz(xyz1)
    mol2 = mol3D()
    mol2.readfromxyz(xyz1)
    # Compare number of atoms
    passNumAtoms = (mol1.natoms == mol2.natoms)
    print("Pass total number of atoms check: ", passNumAtoms)
    return passNumAtoms
示例#8
0
 def obtain_mol3d(self):
     new_mol = mol3D()
     this_mol = mol3D()
     this_mol.readfromxyz(self.geopath)
     if this_mol.natoms > 0:
         self.mol = this_mol
         self.natoms = this_mol.natoms
         self.health = True
     else:
         self.comments.append('geo file appears empty')
         self.health = False
示例#9
0
def fuzzy_compare_xyz(xyz1, xyz2, thresh):
    fuzzyEqual = False
    mol1 = mol3D()
    mol1.readfromxyz(xyz1)
    mol2 = mol3D()
    mol2.readfromxyz(xyz2)
    mol1, U, d0, d1 = kabsch(mol1, mol2)
    rmsd12 = mol1.rmsd(mol2)
    print(('rmsd is ' + '{0:.2f}'.format(rmsd12)))
    if rmsd12 < thresh:
        fuzzyEqual = True
    return fuzzyEqual
示例#10
0
def fuzzy_compare_xyz(xyz1,xyz2,thresh):
    fuzzyEqual=False
    mol1 = mol3D()
    mol1.readfromxyz(xyz1)
    mol2 = mol3D()
    mol2.readfromxyz(xyz2)
    mol1,U,d0,d1 = kabsch(mol1,mol2)
    rmsd12 = mol1.rmsd(mol2)
    print('rmsd is ' +'{0:.2f}'.format(rmsd12))
    if rmsd12 < thresh:
        fuzzyEqual=True
    return fuzzyEqual
示例#11
0
def process_geometry_optimizations(this_run, basedir, outfile, output):
    energy, ss_act, ss_target, tot_time, thermo_grad_error, solvent_cont, tot_step = output.wordgrab(
        ['FINAL', 'S-SQUARED:', 'S-SQUARED:', 'processing', 'Maximum component of gradient is too large',
         'C-PCM contribution to final energy:', 'Optimization Cycle'],
        [2, 2, 4, 3, 0, 4, 3], last_line=True)
    check_conv(this_run, tot_time, energy, output)
    this_run.geo_opt = True
    scrpath = basedir + '/scr/'
    optimpath = scrpath + 'optim.xyz'
    this_run.scrpath = optimpath
    if this_run.converged:
        if os.path.getsize(optimpath) > 45:
            this_run.init_energy = float(output.wordgrab(['FINAL ENERGY'], 'whole_line')[0][0][2])
            try:
                extract_optimized_geo(optimpath)
                this_run.geopath = scrpath + 'optimized.xyz'
            except:
                this_run.geopath = optimpath
            if os.path.isfile(outfile):
                diople_vec, diople_moment = grab_dipole_moment(outfile)
                this_run.diople_vec = diople_vec
                this_run.diople_moment = diople_moment
            else:
                raise ValueError("Output file does not exist: ", outfile)
            read_molden_file(this_run)
            obtain_wavefunction_molden(this_run)
            this_run.init_mol = mol3D()
            this_run.init_mol.readfromtxt(get_initgeo(optimpath))
            this_run.mol = mol3D()
            this_run.mol.readfromtxt(get_lastgeo(optimpath))
            try:
                use_initmol = False if (this_run.iscsd or this_run.isMutation) else True
                this_run.check_oct_needs_init(debug=False, external=True, use_initmol=use_initmol)
            except:
                print("Warning: falied get geo_check!!!")
            ### Note that we should put get_ligsymmetry_graphdet to avoid building the graph for this_run.init_mol before the geocheck
            this_run.init_ligand_symmetry, this_run.init_mol_graph_det = get_ligsymmetry_graphdet(this_run.init_mol)
            this_run.ligand_symmetry, this_run.mol_graph_det = get_ligsymmetry_graphdet(this_run.mol)
            this_run.obtain_rsmd()
            this_run.obtain_ML_dists()
            this_run.get_check_flags()
            this_run.get_optimization_time_step(current_path=outfile)
            if this_run.geo_flag:
                this_run.status = 0
            else:
                this_run.status = 1
        else:
            print(("Warning: optim file %s is empty. Skipping this run." % optimpath))
            this_run.converged = False
    else:
        this_run.status = 7
    return this_run
示例#12
0
def assemble_connectivity_from_parts(metal_mol, custom_ligand_dict):
    ## custom_ligand_dict.keys() must be eq_ligands_list, ax_ligand_list
    ##                                    ax_con_int_list ,eq_con_int_list
    ## with types: eq/ax_ligand2_list list of mol3D
    ##             eq/ax_con_int_list list of list/tuple of int e.g,  [[1,2] [1,2]]
    blank_mol = mol3D()
    # start with the connectivity matrix of the whole comlpex
    n_total = 1+ sum(m.mol.natoms for m in custom_ligand_dict["eq_ligand_list"]) + \
                 sum(m.mol.natoms for m in custom_ligand_dict["ax_ligand_list"])
    con_mat = np.zeros((n_total, n_total))

    this_complex = mol3D()
    this_complex.copymol3D(metal_mol)
    live_row = 1  # metal goes in row 0

    for i, class_lig in enumerate(custom_ligand_dict["eq_ligand_list"]):
        this_lig = class_lig.mol
        this_dim = this_lig.natoms
        this_con = custom_ligand_dict["eq_con_int_list"][i]
        this_lig.convert2OBMol()
        this_lig.createMolecularGraph()
        con_mat[live_row:live_row + this_dim,
                live_row:live_row + this_dim] = this_lig.graph
        for con_atoms in this_con:
            con_mat[0, live_row + con_atoms] = 1
            con_mat[live_row + con_atoms, 0] = 1
        live_row = live_row + this_dim
        this_complex.combine(this_lig, [], dirty=True)
    for i, class_lig in enumerate(custom_ligand_dict["ax_ligand_list"]):
        this_lig = class_lig.mol
        this_dim = this_lig.natoms
        this_con = custom_ligand_dict["ax_con_int_list"][i]
        this_lig.convert2OBMol()
        this_lig.createMolecularGraph()
        con_mat[live_row:live_row + this_dim,
                live_row:live_row + this_dim] = this_lig.graph
        for con_atoms in this_con:
            con_mat[0, live_row + con_atoms] = 1
            con_mat[live_row + con_atoms, 0] = 1
        live_row = live_row + this_dim
        this_complex.combine(this_lig, [], dirty=True)
    if not int(sum(con_mat[:, 0])) == 6:
        print('coordination number is ' + str(sum(con_mat[:, 0])))
        print('error, not oct ')
        sys.exit()
    # overwrite the connectivity matrix
    this_complex.graph = con_mat
    return this_complex
示例#13
0
def substplaceff_mode3(core, substr, substreact, compreact, cpoint, args, connected, frozenats):
    enc = 0
    # align substrate according to connection atom and shadow atom
    substr.alignmol(substr.getAtom(substreact), atom3D('H', cpoint))
    # perform rotations
    Bcoords = core.getAtomCoords(compreact)
    adjsidx = substr.getBondedAtoms(substreact)[0]
    if substr.natoms > 1:
        # align ligand center of symmetry
        substr = align_lig_centersym(Bcoords, substr, substreact, core, False)
    if substr.natoms > 2:
        # check for linear molecule and align
        substr = check_rotate_linear_lig(Bcoords, substr, substreact)
        # check for symmetric molecule
        substr = check_rotate_symm_lig(Bcoords, substr, substreact, core)
        # rotate around M-L axis to minimize steric repulsion
        substr = rotate_MLaxis_minimize_steric(
            Bcoords, substr, substreact, core)
    # distort substrate molecule
    adjsidx = substr.getBondedAtoms(substreact)[0]
    XYBL = XYcoeff*(substr.getAtom(substreact).rad +
                    substr.getAtom(adjsidx).rad)
    substr.BCM(adjsidx, substreact, XYBL)
    # combine molecules
    ts3D = mol3D()
    ts3D.copymol3D(core)
    ts3D = ts3D.combine(substr)
    ts3D.charge += substr.charge
    if 'a' in args.ffoption or args.substplaceff:
        ts3D, enc = ffopt(args.ff, ts3D, connected, 1,
                          frozenats, False, [], 'Adaptive')
    return ts3D, enc
示例#14
0
    def __init__(self, infile, active_sites=None):
        # also, molecule no longer explicitly optimized in this function
        self.infile = infile
        infile_type = self.infile.split('.')[-1]
        print(self.infile)
        self.OH_bond_length = 0.975

        self.molecule = mol3D.mol3D()
        self.molecule.OBMol = self.molecule.getOBMol(infile,
                                                     infile_type,
                                                     ffclean=False)
        self.molecule.convert2mol3D()

        if active_sites == None:
            self.active_sites = self.standardActiveSites()
        else:
            self.active_sites = active_sites

        self.bond_length_cutoffs = {
            'C': 1.953,
            'H': 1.443,
            'I': 2.543,
            'Cl': 2.154,
            'B': 2.027,
            'N': 1.834,
            'F': 1.707,
            'Br': 2.423,
            'P': 2.297,
            'S': 2.198,
            'O': 1.810
        }  # X-O (angstroms)
        self.dtheta = 5  # change this if you want to
        self.binding_dict = {'O2': self.bindO2, 'O': self.bindO, 'OH': self.bindOH, 'O2H': self.bindO2H, 'CN' : self.bindCN, \
                             'CO': self.bindCO}
示例#15
0
def get_metal_and_bonded_atoms(job_outfile, geometry=None):
    """Get metal and bonded atoms of complex.

    Parameters
    ----------
        job_outfile : str
            Path for output file.
        geometry : str, optional
            Type of geometry to define metal bonding. Default is None.

    Returns
    -------
        geo_flag : bool
            Flag describing geometry. True if good geometry.
    
    """
    # given the path to the outfile of a job, returns a the metal atom index and a list of indices for the metal bonded atoms
    # indices are zero-indexed...Terachem uses 1 indexed lists

    xyz_path = job_outfile.rsplit('.', 1)[0] + '.xyz'
    mol = mol3D()
    mol.readfromxyz(xyz_path)
    metal_index = mol.findMetal()[0]

    if geometry in ['Oct', 'oct', 'Octahedral', 'octahedral']:
        bonded_atom_indices = mol.getBondedAtomsOct(metal_index)
    else:
        print('Warning, generic getBondedAtoms() used for: ' + job_outfile + '. Check behavior')
        bonded_atom_indices = mol.getBondedAtoms(metal_index)

    return metal_index, bonded_atom_indices
示例#16
0
def compareMLBL(xyz1,xyz2,thresh):
    print "Checking metal-ligand bond length"
    mol1 = mol3D()
    mol1.readfromxyz(xyz1)
    mol2 = mol3D()
    mol2.readfromxyz(xyz1)
    bl1 = getMetalLigBondLength(mol1)
    bl2 = getMetalLigBondLength(mol2)
    passMLBL =True
    for i in range(0,len(bl1)):
        if not fuzzy_equal(bl1[i],bl2[i],thresh):
            print "Error! Metal-Ligand bondlength mismatch for bond # ",i
            passMLBL = False
    print "Pass metal-ligand bond length check: ",passMLBL
    print "Threshold for bondlength difference: ",thresh
    return passMLBL
示例#17
0
def xyz2gxyz(filename):
    # convert normal xyz file to gamess format
    mol = mol3D()  # create mol3D object
    mol.readfromxyz(filename)  # read molecule
    gfilename = filename.replace('.xyz', '.gxyz')  # new file name
    mol.writegxyz(gfilename)  # write gamess formatted xyz file
    return gfilename.split('.gxyz')[0]
示例#18
0
def check_top_layer_correct(super_cell, atom_type):
    # remove the layer on
    # top of the cell if
    # wrong material is exposed
    trimmed_cell = mol3D()
    trimmed_cell.copymol3D(super_cell)
    globs = globalvars()
    elements = globs.elementsbynum()
    print(('chekcing surface  for  ' + atom_type + '\n'))
    if not atom_type in elements:
        print("unkown surface type, unable to trim ")
        return trimmed_cell
    else:
        stop_flag = False
        counter = 0  # 3 tries max
        while not stop_flag:
            atom_type_surf = find_all_surface_atoms(
                trimmed_cell, tol=1e-3, type_of_atom=atom_type)
            top_surf = find_all_surface_atoms(
                trimmed_cell, tol=1e-3, type_of_atom=False)
#            print("top surf",top_surf)
#            print("atom top surf",atom_type_surf)
            if set(atom_type_surf) == set(top_surf):
                print('match')
                stop_flag = True
            else:
                counter += 1
                trimmed_cell = shave_surface_layer(trimmed_cell, 1e-3)
            if counter == 3:
                print('unable to find target atom in 3 cuts')
                stop_flag = True
    return trimmed_cell
示例#19
0
def compareMLBL(xyz1, xyz2, thresh):
    print("Checking metal-ligand bond length")
    mol1 = mol3D()
    mol1.readfromxyz(xyz1)
    mol2 = mol3D()
    mol2.readfromxyz(xyz1)
    bl1 = getMetalLigBondLength(mol1)
    bl2 = getMetalLigBondLength(mol2)
    passMLBL = True
    for i in range(0, len(bl1)):
        if not fuzzy_equal(bl1[i], bl2[i], thresh):
            print("Error! Metal-Ligand bondlength mismatch for bond # ", i)
            passMLBL = False
    print("Pass metal-ligand bond length check: ", passMLBL)
    print("Threshold for bondlength difference: ", thresh)
    return passMLBL
示例#20
0
def shave__type(super_cell, dim, mode):
    ## dim  = 0,1,2
    # x,y,z
    #   mode = 1 for max, -1 for min
    shaved_cell = mol3D()
    shaved_cell.copymol3D(super_cell)
    TOL = 1e-1

    dim_ref = 1000

    if (mode == -1):
        for i, atoms in enumerate(super_cell.getAtoms()):
            coords = atoms.coords()
            if (coords[dim] < dim_ref):
                dim_ref = coords[dim]
        del_list = list()
        for i, atoms in enumerate(super_cell.getAtoms()):
            coords = atoms.coords()
            if abs(coords[dim] - dim_ref) < TOL:
                del_list.append(i)
    if (mode == 1):
        extents = find_extents(super_cell)
        dim_max = extents[dim]
        del_list = list()
        for i, atoms in enumerate(super_cell.getAtoms()):
            coords = atoms.coords()
            if abs(coords[dim] - dim_max) < TOL:
                del_list.append(i)
    # return
    shaved_cell.deleteatoms(del_list)
    return shaved_cell
示例#21
0
def read_run(outfile_PATH):
    # Evaluates all aspects of a run using the outfile and derivative files
    results = manager_io.read_outfile(outfile_PATH, long_output=True)
    infile_dict = manager_io.read_infile(outfile_PATH)
    results['levela'], results['levelb'] = infile_dict['levelshifta'], infile_dict['levelshiftb']
    results['method'], results['hfx'] = infile_dict['method'], infile_dict['hfx']
    results['constraints'] = infile_dict['constraints']

    mullpop_path = os.path.join(os.path.split(outfile_PATH)[0], 'scr', 'mullpop')
    if os.path.exists(mullpop_path):
        mullpops = manager_io.read_mullpop(outfile_PATH)
        metal_types = ['Cr', 'Mn', 'Fe', 'Co', 'Ni', 'Mo', 'Tc', 'Ru', 'Rh']
        metals = [i for i in mullpops if i.split()[0] in metal_types]
        if len(metals) > 1:
            results['metal_spin'] = np.nan
        elif len(metals) == 0:
            pass
        else:
            results['metal_spin'] = float(metals[0].split()[-1])
    else:
        results['metal_spin'] = np.nan

    optim_path = os.path.join(os.path.split(outfile_PATH)[0], 'scr', 'optim.xyz')

    check_geo = False
    if os.path.isfile(optim_path):
        fil = open(optim_path, 'r')
        lines = fil.readlines()
        fil.close()
        if len(lines) > 0:
            check_geo = True  # Only apply geo check if an optimized geometry exists

    if check_geo:
        tools.extract_optimized_geo(optim_path)
        optimized_path = os.path.join(os.path.split(optim_path)[0], 'optimized.xyz')

        mol = mol3D()
        mol.readfromxyz(optimized_path)

        IsOct, flag_list, oct_check = mol.IsOct(dict_check=mol.dict_oct_check_st,
                                                silent=True)

        if IsOct:
            IsOct = True
        else:
            IsOct = False

        results['Is_Oct'] = IsOct
        results['Flag_list'] = flag_list
        results['Oct_check_details'] = oct_check

    else:
        results['Is_Oct'] = None
        results['Flag_list'] = None
        results['Oct_check_details'] = None

    return results
示例#22
0
def read_geometry_to_mol(geofile):
    with open(geofile, 'r') as fo:
        num_atoms = int(fo.readline().split()[0])
    num_lines = num_atoms + 2  ## +2 for the xyz format.
    with open(geofile, 'r') as fo:
        geotext = fo.readlines()[-num_lines:]
    mol = mol3D()
    mol.readfromtxt(geotext)
    return mol
示例#23
0
def change_basis(mol, old_basis, new_basis):
    new_mol = mol3D()
    new_mol.copymol3D(mol)
    point_coefficients = [get_basis_coefficients(
        at.coords(), old_basis) for at in new_mol.getAtoms()]
    new_points = [get_basis_coefficients(
        point, new_basis) for point in point_coefficients]
    for i, at in enumerate(new_mol.getAtoms()):
        at.setcoords(new_points[i])
    return new_mol
示例#24
0
def zero_x(super_cell):
    zeroed_cell = mol3D()
    zeroed_cell.copymol3D(super_cell)
    TOL = 1e-1
    xmin = 1000
    for i, atoms in enumerate(super_cell.getAtoms()):
        coords = atoms.coords()
        if (coords[0] < xmin):
            xmin = coords[0]
    zeroed_cell.translate([-1*xmin, 0, 0])
    return zeroed_cell
示例#25
0
def zero_z(super_cell):
    zeroed_cell = mol3D()
    zeroed_cell.copymol3D(super_cell)
    TOL = 1e-1
    zmin = 1000
    for i, atoms in enumerate(super_cell.getAtoms()):
        coords = atoms.coords()
        if (coords[2] < zmin):
            zmin = coords[2]
    zeroed_cell.translate([0, 0, -1*zmin])
    return zeroed_cell
示例#26
0
def process_single_points(this_run, basedir, output):
    energy, ss_act, ss_target, tot_time, thermo_grad_error, solvent_cont, tot_step = output.wordgrab(
        ['FINAL', 'S-SQUARED:', 'S-SQUARED:', 'processing', 'Maximum component of gradient is too large',
         'C-PCM contribution to final energy:', 'Optimization Cycle'],
        [2, 2, 4, 3, 0, 4, 3], last_line=True)
    this_run.geo_opt = False
    this_run.converged = True if not energy == None else False
    if this_run.converged:
        this_run.tot_step = tot_step
        this_run.init_energy = energy
        scrpath = basedir + '/scr/'
        optimpath = scrpath + 'xyz.xyz'
        this_run.scrpath = optimpath
        this_run.init_mol = mol3D()
        this_run.init_mol.readfromtxt(get_initgeo(optimpath))
        this_run.mol = mol3D()
        this_run.mol.readfromtxt(get_initgeo(optimpath))
        obtain_wavefunction_molden(this_run)
        read_molden_file(this_run)
    return this_run
示例#27
0
def zero_y(super_cell):
    zeroed_cell = mol3D()
    zeroed_cell.copymol3D(super_cell)
    TOL = 1e-1
    ymin = 1000
    for i, atoms in enumerate(super_cell.getAtoms()):
        coords = atoms.coords()
        if (coords[1] < ymin):
            ymin = coords[1]
    zeroed_cell.translate([0, -1*ymin, 0])
    return zeroed_cell
示例#28
0
def common_processing(jobname, basedir, output, outfile, spin, 
                      dbname=False, gene=False):
    dbname = jobname if dbname == False else dbname
    this_run = DFTRun(dbname, external=True)
    this_run.name = dbname
    this_run.octahedral = True
    if gene != False:
        # Assigns a gene, which is used during design
        temp_name = "_".join(jobname.split('_')[0:13]) #stops before job manager extra keywords
        translate_dict = translate_job_name(temp_name)
        this_run.gene = translate_dict['gene']
    energy, ss_act, ss_target, tot_time, thermo_grad_error, solvent_cont, tot_step, d3_energy = output.wordgrab(
        ['FINAL', 'S-SQUARED:', 'S-SQUARED:', 'processing', 'Maximum component of gradient is too large',
         'C-PCM contribution to final energy:', 'Optimization Cycle', 'DFTD Dispersion Correction:'],
        [2, 2, 4, 3, 0, 4, 3, -2], last_line=True)
    iscsd = isCSD(dbname)
    this_run.isMutation = isMutation(dbname)
    this_run.iscsd = iscsd
    this_run.charge = output.wordgrab(['Total charge'], -1)[0][0]
    try:
        this_run.charge = int(this_run.charge)
    except:
        this_run.charge = False
    if not d3_energy == None:
        this_run.d3opt_flag = True
    else:
        this_run.d3_energy = np.nan
        this_run.d3opt_flag = False
    if not (this_run.iscsd or this_run.isMutation):
        print(("jobname: ", dbname))
        bind_complex_info(this_run, dbname, spin)
    else:
        init_mol = mol3D()
        init_mol.readfromxyz(basedir + '/%s.xyz' % jobname)
        bind_csd_info(this_run, dbname, spin, init_mol)
    this_run.outpath = outfile
    this_run.tot_time = tot_time
    this_run.alpha = output.wordgrab(['Hartree-Fock exact exchange:'], -1)[0][0] * 100
    this_run.functional = output.wordgrab(['DFT Functional requested:'], -1)[0][0]
    this_run.terachem_version = output.wordgrab(['TeraChem'], 2)[0][0]
    this_run.alpha_level_shift = output.wordgrab(['Alpha level shift'], -1)[0][0]
    this_run.beta_level_shift = output.wordgrab(['Beta level shift'], -1)[0][0]
    this_run.basis = output.wordgrab(['Using basis set:'], -1)[0][0]
    if not energy == None:
        this_run.energy = float(energy)
    else:
        this_run.energy = np.nan
    this_run = collect_spin_info(this_run, spin, ss_act, ss_target)
    scrpath = basedir + '/scr/'
    this_run.scrpath_real = scrpath
    if os.path.isdir(this_run.scrpath_real):
        calculate_mulliken_spins(this_run)
    return this_run
示例#29
0
def get_geo_metrics(init_mol, job_info, geofile, frame=-1):
    mol_now = read_geometry_to_mol(geofile, frame=frame)
    dict_geo_metrics = {}
    info_list = ['flag_oct']
    dict_info = [
        'inspect_oct_angle_devi_max', 'inspect_max_del_sig_angle',
        'inspect_dist_del_all', 'inspect_dist_del_eq',
        'inspect_devi_linear_avrg', 'inspect_devi_linear_max'
    ]
    actural_dict_info = ['actural_rmsd_max']
    mol = mol3D()
    mol.copymol3D(mol_now)
    inspect_flag, _, dict_oct, inspect_flag_loose, _ = mol.Oct_inspection(
        init_mol=init_mol, catoms_arr=job_info['catoms'])
    _mol = mol3D()
    _mol.copymol3D(mol_now)
    flag_oct, _, dict_oct_info = _mol.IsOct(init_mol=init_mol)
    eqsym, maxdent, ligdents, homoleptic, ligsym = init_mol.get_symmetry_denticity(
    )
    if not maxdent > 1:
        choice = 'mono'
    else:
        choice = 'multi'
    actural_dict_geo = {}
    inspect_dict_geo = {}
    for key in dict_oct_info:
        val = dict_oct_info[key] if (dict_oct_info[key] != -1) and (dict_oct_info[key] != "lig_mismatch") else 1.20 * \
                                                                                                               dict_oct_check_st[
                                                                                                                   choice][
                                                                                                                   key]
        actural_dict_geo['actural_%s' % key] = val
    for key in dict_oct:
        inspect_dict_geo['inspect_%s' % key] = dict_oct[key]
    for info in info_list:
        dict_geo_metrics.update({info: locals()[info]})
    for info in dict_info:
        dict_geo_metrics.update({info: inspect_dict_geo[info]})
    for info in actural_dict_info:
        dict_geo_metrics.update({info: actural_dict_geo[info]})
    return dict_geo_metrics
示例#30
0
def runtestgeo_optonly(tmpdir, name, thresh, deleteH=True, geo_type="oct"):
    optgeo = resource_filename(Requirement.parse("molSimplify"),
                               "tests/inputs/geocheck/" + name + "/opt.xyz")
    refjson = resource_filename(Requirement.parse("molSimplify"),
                                "tests/refs/geocheck/" + name + "/ref.json")
    mymol = mol3D()
    mymol.readfromxyz(optgeo)
    if geo_type == "oct":
        _, _, dict_struct_info = mymol.IsOct(debug=False, flag_deleteH=deleteH)
    with open(refjson, "r") as fo:
        dict_ref = json.load(fo)
    passGeo = comparedict(dict_ref, dict_struct_info, thresh)
    return passGeo
示例#31
0
def fvalency(xyzf):
    # setting properties
    xyz = mol3D()
    xyz.readfromxyz(xyzf)
    # getting idxs of interest
    midx = xyz.findMetal()[0]  # monometallic complexes
    # list of idx of the first-coord sphere
    fidx_list = xyz.getBondedAtoms(midx)
    fvalency_list = []
    for idx in fidx_list:
        valency = len(xyz.getBondedAtoms(idx)) - 1
        fvalency_list.append(valency)

    return fvalency_list
示例#32
0
    def FillMatchedO2(self, qdatas, energy, cat_fn, AS_CHELPG):
        for i, entry in enumerate(self.catO2_df["CatalystO2_File_Name"]):
            catO2_entry_name = catalyst_name(entry)
            for qdata in qdatas:
                if qdata.filename.split('_')[0] == catO2_entry_name:
                    #if qdata.filename.split('_')[1] == entry.split('_')[1]:
                    self.catO2_df.at[i, energy] = qdata.E
                    self.catO2_df.at[i, cat_fn] = qdata.filename
                    try:
                        chelpgs = qdata.chelpg
                        active_site_index = self.catO2_df.iloc[i][
                            'Active_Site']
                        self.catO2_df.at[i,
                                         AS_CHELPG] = chelpgs[active_site_index
                                                              - 1]

                    except Exception as e:
                        print("Could not get CHELPG charges for " +
                              qdata.filename)
                        print(e)

                    #if self.catO2_df[i, 'Active_Site_ID'] == 'C':
                    if True:
                        self.molecule = mol3D.mol3D()
                        self.molecule.qdata2mol3D(qdata.atoms, qdata.coord)
                        print(qdata.atoms)
                        print(qdata.coord)
                        print(self.molecule.coords())
                        as_atom = self.molecule.atoms[active_site_index - 1]
                        print(as_atom.symbol(), as_atom.coords())
                        connection_list = self.molecule.getBondedAtomsSmart(
                            active_site_index, oct=False)
                        connection_list = [c for c in connection_list
                                           ]  #This indexes from 1
                        #get atomic symbol of each connection
                        print(qdata.filename, active_site_index - 1,
                              connection_list)
                        sys.exit(-1)
                        if len(connection_list) == 3:
                            for en_conn, connection in enumerate(
                                    connection_list):
                                sym_conn_list = qdata.atoms[connection]
                                chelpg_conn_list = qdata.chelpg[connection]
                                neigh = self.neighbor_dict[cat_fn][en_conn]
                                self.catO2_df.at[
                                    i, neigh] = qdata.chelpg[connection]

                    #get CHELPG of each connection

                    break  # assumes cat_dir does not contain multiple files for the same catalyst
示例#33
0
def fsym(xyzf):
    # setting properties
    xyz = mol3D()
    xyz.readfromxyz(xyzf)
    # getting idxs of interest
    midx = xyz.findMetal()[0]  # monometallic complexes
    # list of idx of the first-coord sphere
    fidx_list = xyz.getBondedAtoms(midx)
    fsym_list = []
    for idx in fidx_list:
        sym = xyz.getAtom(idx).sym
        fsym_list.append(sym)

    return fsym_list
示例#34
0
def GetConf(mol, args, catoms=[]):
    """Uses distance geometry to get a random conformer.
        
    Parameters
    ----------
        mol : mol3D
            mol3D class instance for molecule of interest.
        args : Namespace
            Namespace argument from inparse.
        catoms : list, optional
            List of connection atoms used to generate additional constraints if specified (see GetBoundsMatrices()). Default is empty.
        
    Returns
    -------
        Conf3D : mol3D
            mol3D class instance of new conformer.

    """
    # Create a mol3D copy with a dummy metal metal
    Conf3D = mol3D()
    Conf3D.copymol3D(mol)
    Conf3D.addAtom(atom3D('Fe', [0, 0, 0]))  #Add dummy metal to the mol3D
    dummy_metal = openbabel.OBAtom()  #And add the dummy metal to the OBmol
    dummy_metal.SetAtomicNum(26)
    Conf3D.OBMol.AddAtom(dummy_metal)
    for i in catoms:
        Conf3D.OBMol.AddBond(i + 1, Conf3D.OBMol.NumAtoms(), 1)
    natoms = Conf3D.natoms
    Conf3D.createMolecularGraph()

    shape = findshape(args, mol)
    LB, UB = GetBoundsMatrices(Conf3D, natoms, catoms, shape)
    status = False
    while not status:
        D = Metrize(LB, UB, natoms)
        D0, status = GetCMDists(D, natoms)
    G = GetMetricMatrix(D, D0, natoms)
    L, V = Get3Eigs(G, natoms)
    X = np.dot(V, L)  # get projection
    x = np.reshape(X, 3 * natoms)
    res1 = optimize.fmin_cg(DistErr,
                            x,
                            fprime=DistErrGrad,
                            gtol=0.1,
                            args=(LB, UB, natoms),
                            disp=0)
    X = np.reshape(res1, (natoms, 3))
    Conf3D = SaveConf(X, Conf3D, True, catoms)

    return Conf3D
示例#35
0
def fcharge(xyzf, charge):
    # setting properties
    xyz = mol3D()
    xyz.readfromxyz(xyzf)
    xyz.calccharges(charge)
    # getting idxs of interest
    midx = xyz.findMetal()[0]  # monometallic complexes
    # list of idx of the first-coord sphere
    fidx_list = xyz.getBondedAtoms(midx)
    fcharge_list = []
    for idx in fidx_list:
        charge = xyz.partialcharges[idx]
        fcharge_list.append(float(charge))

    return fcharge_list
示例#36
0
def shave_surface_layer(super_cell, TOL=1e-1):
  #  dlist = fractionate_points_by_plane(super_cell,n)
 #   points_below_plane(point,n,refd)

    shaved_cell = mol3D()
    shaved_cell.copymol3D(super_cell)
    extents = find_extents(super_cell)
    zmax = extents[2]
    del_list = list()
    for i, atoms in enumerate(super_cell.getAtoms()):
        coords = atoms.coords()
        if abs(coords[2] - zmax) < TOL:
            del_list.append(i)
    shaved_cell.deleteatoms(del_list)
    return shaved_cell