示例#1
0
def main():
    """Run main procedure."""
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("identifiers", nargs="+")
    args = parser.parse_args()

    atomnos = []
    atomcoords = []
    for identifier in args.identifiers:
        try:
            nos, _, coords = read_xyz(cirpy.resolve(identifier, "xyz"))
        except AttributeError:
            nos, _, coords = read_xyz(identifier)
        atomnos.append(nos[-1])
        atomcoords.append(coords[-1] - np.mean(coords[-1], axis=0))

    curnos = atomnos[0]
    curcoords = atomcoords[0]
    for nos, coords in zip(atomnos[1:], atomcoords[1:]):
        curdim = curcoords.max(axis=0) - curcoords.min(axis=0)
        extradim = coords.max(axis=0) - coords.min(axis=0)
        axis = curdim.argmin()

        v = np.zeros(3)
        v[axis] = (curdim[axis] + extradim[axis]) / 2 + 2.83
        coords = coords + v
        print(write_xyz(nos, coords))
示例#2
0
def main():
    """Run main procedure."""
    parser = argparse.ArgumentParser()
    parser.add_argument("xyz_files",
                        type=argparse.FileType("r"),
                        default="-",
                        nargs="+")
    args = parser.parse_args()

    refname = args.xyz_files[0].name
    refatomno, _, refcoord = read_xyz(args.xyz_files[0])
    refatomno, refcoord = refatomno[-1], refcoord[-1]
    uniquenos = sorted(set(refatomno))

    for xyz_file in args.xyz_files[1:]:
        atomno, comment, coord = read_xyz(xyz_file)
        atomno, coord = reorder(uniquenos, refatomno, refcoord, atomno[-1],
                                coord[-1])

        with open(xyz_file.name, "w") as stream:
            stream.write(write_xyz(atomno, coord, comment[-1]))
示例#3
0
def main():
    """Run main procedure."""
    parser = argparse.ArgumentParser()
    parser.add_argument("xyz_files",
                        type=argparse.FileType("r"),
                        default="-",
                        nargs="+")
    # TODO(schneiderfelipe): set charge and multiplicity
    parser.add_argument(
        "-a",
        "--acc",
        help="accuracy for SCC calculation, lower is better",
        type=float,
        default=1.0,
    )
    parser.add_argument(
        "--iterations",
        help="number of iterations in SCC",
        type=int,
        default=250,
    )
    parser.add_argument(
        "--gfn",
        help="specify parametrisation of GFN-xTB",
        type=int,
        default=2,
    )
    parser.add_argument("--etemp",
                        help="electronic temperature",
                        type=float,
                        default=300.0)
    parser.add_argument(
        "-s",
        "--solvent",
        help=("solvent (SMD/GBSA implicit solvation models)"),
        default="none",
    )
    parser.add_argument(
        "--do-not-cache-api",
        dest="cache_api",
        help="Do not reuse generate API objects (not recommended)",
        action="store_false",
    )

    parser.add_argument(
        "--free-atoms",
        help=("Only optimize the given atoms, as comma-separated one-based "
              "indices, ranges or atomic symbols"),
    )
    args = parser.parse_args()
    print(args)

    method = f"GFN{args.gfn}-xTB"
    solvent = smd2gbsa[args.solvent.lower()]

    if args.free_atoms:
        free_atom_indices = set()
        free_atom_nos = set()
        for i in args.free_atoms.split(","):
            try:
                free_atom_indices.add(int(i) - 1)
            except ValueError:
                if "-" in i:
                    start_plus_one, end = (int(j) for j in i.split("-", 1))
                    free_atom_indices.update(range(start_plus_one - 1, end))
                else:
                    free_atom_nos.add(
                        element(i).atomic_number)  # atomic numbers

    for xyz_file in args.xyz_files:
        atomno, comment, coord = read_xyz(xyz_file)
        atomno, comment, coord = atomno[-1], comment[-1], coord[-1]

        constraints = []
        if args.free_atoms:
            print(free_atom_indices)
            print(free_atom_nos)
            indices = list(
                set(range(len(atomno))) - free_atom_indices -
                set(i for i, no in enumerate(atomno) if no in free_atom_nos))
            print(f"Constraining atoms {indices}")
            constraints.append(FixAtoms(indices=indices))

        atomno, coord = minimize(
            atomno,
            coord,
            method=method,
            accuracy=args.acc,
            electronic_temperature=args.etemp,
            max_iterations=args.iterations,
            solvent=solvent,
            cache_api=args.cache_api,
            constraints=constraints,
        )

        with open(xyz_file.name, "w") as stream:
            stream.write(write_xyz(atomno, coord, comment))
示例#4
0
def main():
    """Run main procedure."""
    # TODO(schneiderfelipe): accept multiple files
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("traj_files", nargs="+")
    args = parser.parse_args()

    gnorms = []
    energies = []
    all_atomnos = []
    all_atomcoords = []
    for traj_file in args.traj_files:
        atomnos, comments, atomcoords = read_xyz(traj_file)
        all_atomnos.extend(atomnos)
        all_atomcoords.extend(atomcoords)
        for comment in comments:
            fields = comment.split()
            gnorms.append(float(fields[3]))
            energies.append(float(fields[1]))
    energies = np.array(energies)
    energies -= energies.min()
    energies *= hartree * N_A / (kilo * calorie)

    u = mda.Universe.empty(n_atoms=len(all_atomnos[0]), trajectory=True)
    u.add_TopologyAttr("type", [element[i] for i in all_atomnos[0]])
    u.load_new(all_atomcoords, order="fac")
    print(u)

    selection = None
    print("(enter 'q' for exit, 'h' for help)")
    while True:
        code = input("select> ").strip().split()
        if code[0] == "q":
            break
        elif code[0] == "h":
            for key in commands:
                print(f"{key:15s}: {commands[key]}")
        elif code[0] == "e":
            fig, ax = plt.subplots(2)
            ax[0].plot(energies)
            ax[0].set_xlabel("frame")
            ax[0].set_ylabel("energy (kcal/mol)")

            ax[1].plot(gnorms)
            ax[1].set_xlabel("frame")
            ax[1].set_ylabel("grad. norm (Eh/a0)")
            plt.show()
        elif code[0] == "s":
            print(selection)
            if selection is not None:
                print(selection_text)
        elif code[0] == "pca":
            if selection is None:
                print("empty selection, doing nothing")
                continue

            p = pca.PCA(u, select=selection_text)
            p.run()

            n_pcs = np.where(p.cumulated_variance > 0.95)[0][0]
            print(n_pcs)
            print(p.cumulated_variance[0:n_pcs])
            pca_space = p.transform(selection, n_components=n_pcs)
            print(pca_space)
            print(pca.cosine_content(pca_space, 0))
        elif code[0] == "p":
            if selection is None:
                print("empty selection, doing nothing")
                continue

            n = len(selection)
            if n == 2:
                data_label = "bond length (Å)"
            elif n == 3:
                data_label = "bond angle (°)"
            elif n == 4:
                data_label = "dihedral angle (°)"
            else:
                print("too few or too many indices")
                continue

            data = []
            for i, (e, ts) in enumerate(zip(energies, u.trajectory)):
                if n == 2:
                    d = distances.calc_bonds(
                        selection[0].position, selection[1].position
                    )
                elif n == 3:
                    d = np.degrees(
                        distances.calc_angles(
                            selection[0].position,
                            selection[1].position,
                            selection[2].position,
                        )
                    )
                elif n == 4:
                    d = np.degrees(
                        distances.calc_dihedrals(
                            selection[0].position,
                            selection[1].position,
                            selection[2].position,
                            selection[3].position,
                        )
                    )

                data.append(d)
                if i % 100 == 0 or i == len(u.trajectory) - 1:
                    print(
                        f"frame = {ts.frame:4d}: e = {e:5.1f} kcal/mol, {data_label.split('(')[0][:-1]} = {d:7.3f} {data_label[-2]}"
                    )
            data = np.array(data)

            fig, ax = plt.subplots(1, 2)
            ax[0].plot(data)
            ax[0].set_xlabel("frame")
            ax[0].set_ylabel(data_label)

            ax[1].plot(energies, data, "o", label="data points")
            ax[1].set_xlabel("energy (kcal/mol)")
            ax[1].set_ylabel(data_label)

            if n == 2:
                dx = 0.1
            elif n == 3:
                dx = 10.0
            elif n == 4:
                dx = 10.0
            res = stats.binned_statistic(
                data, energies, "min", min(25, (data.max() - data.min()) / dx)
            )

            # print(res.statistic)
            mask = np.isnan(res.statistic)
            res.statistic[mask] = np.interp(
                np.flatnonzero(mask), np.flatnonzero(~mask), res.statistic[~mask]
            )
            # print(res.statistic)

            # ax[1].hlines(res.statistic, res.bin_edges[:-1], res.bin_edges[1:], colors='g', lw=2, label='binned min. energies')
            ax[1].barh(
                (res.bin_edges[:-1] + res.bin_edges[1:]) / 2,
                res.statistic,
                align="center",
                height=res.bin_edges[1:] - res.bin_edges[:-1],
                alpha=0.25,
                label="binned min. energies",
            )
            ax[1].legend()

            plt.show()

        else:
            try:
                selection_text = " ".join(code)
                selection = u.select_atoms(selection_text)
            except mda.exceptions.SelectionError as e:
                print(e)

    print("bye")
示例#5
0
def main():
    """Run main procedure."""
    parser = argparse.ArgumentParser()
    parser.add_argument("out_file", type=argparse.FileType("r"), default="-")
    parser.add_argument("--classic", action="store_true")
    args = parser.parse_args()

    irc = False
    data = []
    for line in args.out_file:
        if "Step        E(Eh)      dE(kcal/mol)  max(|G|)   RMS(G)" in line:
            irc = True
        elif irc:
            line = line.strip()
            if line:
                fields = line.split()
                data.append([float(x) for x in fields[:5]])
                if len(fields) > 5 and fields[5] == "<=":
                    ts_step = int(data[-1][0]) - 1  # first step is one
            else:
                break

    try:
        coords = read_xyz(
            args.out_file.name.replace(".out", "_TSOpt_IRC_Full_trj.xyz"))[2]
    except ValueError:
        coords = read_xyz(
            args.out_file.name.replace(".out", "_IRC_Full_trj.xyz"))[2]

    rmsd = [0.0]
    for i in range(1, len(coords)):
        rmsd.append(rmsd[-1] + calc_rmsd(coords[i - 1], coords[i]))
    rmsd = np.array(rmsd)

    data = np.array(data)
    # xi = (data[:, 0] - data[:, 0].min()) / data[:, 0].max()
    xi = rmsd
    y = data[:, 1] - data[:, 1].min()

    forward_barrier = y.max() - y[0]
    backward_barrier = y.max() - y[-1]
    print(
        f"forward barrier  = {forward_barrier:6.4f} Eh = {forward_barrier * hartree * N_A / kilo:5.1f} kJ/mol = {forward_barrier * hartree * N_A / (kilo * calorie):5.1f} kcal/mol"
    )
    print(
        f"backward barrier = {backward_barrier:6.4f} Eh = {backward_barrier * hartree * N_A / kilo:5.1f} kJ/mol = {backward_barrier * hartree * N_A / (kilo * calorie):5.1f} kcal/mol"
    )

    if not args.classic:
        xi_new = np.linspace(xi.min(), xi.max(), 10000)

        # points = ~np.isclose(xi, xi[ts_step])
        # f = interpolate.InterpolatedUnivariateSpline(xi[points], y[points])
        f = interpolate.InterpolatedUnivariateSpline(xi, y, k=4)
        fp = f.derivative()
        fpp = f.derivative(n=2)

        plt.subplot(311)
    else:
        plt.subplot(211)

    plt.plot(xi, y, "o", label="calculated")
    plt.vlines(xi[ts_step], y.min(), y.max())
    plt.xlabel(r"IRC ($\xi$)")
    plt.ylabel(r"Potential Energy, V($\xi$) [Eh]")

    if not args.classic:
        # add interpolation
        pass
        plt.plot(xi_new, f(xi_new), "--", label="interpolated")
        plt.legend()

        plt.subplot(312)
        rf = -fp(xi_new)
        plt.plot(xi_new, rf, "--")
        plt.vlines(xi[ts_step], rf.min(), rf.max())
        plt.xlabel(r"IRC ($\xi$)")
        plt.ylabel(r"Reaction Force, F($\xi$) [Eh/$\Delta\xi$]")

        # TODO(schneiderfelipe): get max and min force along the coordinate
        # and do the usual analysis
        plt.subplot(313)
        rfc = fpp(xi_new)
        plt.plot(xi_new, rfc, "--")
        plt.vlines(xi[ts_step], rfc.min(), rfc.max())
        plt.xlabel(r"IRC ($\xi$)")
        plt.ylabel(
            r"Reaction Force Constant, $\kappa$($\xi$) [Eh/$\Delta\xi^2$]")
    else:
        plt.subplot(212)
        plt.plot(xi, data[:, 3], "o", label="max(|G|)")
        plt.vlines(xi[ts_step], 0, data[:, 3].max())
        plt.plot(xi, data[:, 4], "o", label="RMS(G)")
        plt.xlabel(r"IRC ($\xi$)")
        plt.ylabel(r"Gradient, G($\xi$) [Eh/Bohr]")
        plt.legend()

    # plt.tight_layout()
    plt.show()