Example #1
0
    # with analytical one
    for i in range(0, nred):
        def f(x):
            q0i,Bi = force_field.getRedundantInternalCoordinates(x,0)
            return q0i[i]
        dqi_dx = utils.numerical_gradient(f,x0)
        err = la.norm(B[i,:] - dqi_dx)
        print "Internal coordinate %d" % i
        print " |dqi/dx (numerical) - dqi/dx (analytical)|= %e" % err
        assert err < 1.0e-8
    

if __name__ == "__main__":
    import sys
    
    atomlist0 = XYZ.read_xyz(sys.argv[1])[-1]
    x0 = XYZ.atomlist2vector(atomlist0)
    
    IC = InternalValenceCoords(atomlist0, verbose=3)

    test_wilson_bmatrix(IC.force_field, x0)
    
    # 1) transform cartesian to internal coordinates, x0 ~ q0
    q0 = IC.cartesian2internal(x0)

    # 2) Take a step along the last internal coordinate,
    # this will only work if the coordinate is not coupled
    # to any other.
    dq = np.zeros(len(q0))
    dq[-1] = 0.1
    q = q0+dq
Example #2
0
        print "  copy the atom type assignments of the monomer (in monomer.ff) to all"
        print "  monomeric units in oligomer.xyz and save the result to <oligomer.ff>"
        print ""
        exit(-1)

    # input files
    monomer_ff = sys.argv[1]
    oligomer_xyz = sys.argv[2]
    # output file
    oligomer_ff = sys.argv[3]

    atomlist_mono, atomtypes_mono, partial_charges_mono, lattice_vectors = PFF.read_force_field(
        monomer_ff)
    nat = len(atomlist_mono)

    atomlist_oligo = XYZ.read_xyz(oligomer_xyz)[0]

    # number of units
    nunit = len(atomlist_oligo) / len(atomlist_mono)
    assert nunit * len(atomlist_mono) == len(
        atomlist_oligo
    ), "Number of atoms must be multiple of number of atoms in monomer"

    atomtypes_oligo = []
    partial_charges_oligo = []
    for i in range(0, nunit):
        atomtypes_oligo += atomtypes_mono
        partial_charges_oligo += partial_charges_mono

    PFF.write_force_field(oligomer_ff,
                          atomlist_oligo,
def opt(xyzfile, optionfile):
    """performs an optimization"""

    outputfile = open("output_dftb.txt", "a")  # redirect output to file
    sys.stdout = outputfile

    try:
        I = 0  # index of electronic state (ground state)

        atomlist = XYZ.read_xyz(xyzfile)[0]  # read atomlist
        kwds = XYZ.extract_keywords_xyz(
            xyzfile)  # read keywords from xyz-file (charge)
        options = read_options(optionfile)  # read options
        scf_options = extract_options(options,
                                      SCF_OPTIONLIST)  # get scf-options

        # optimization (taken from optimize.py)
        pes = MyPES(atomlist, options, Nst=max(I + 1, 2), **kwds)

        x0 = XYZ.atomlist2vector(atomlist)  #convert geometry to a vector

        def f(x):
            save_xyz(x)  # also save geometries from line searches

            if I == 0 and type(pes.tddftb.XmY) != type(None):
                # only ground state is needed. However, at the start
                # a single TD-DFT calculation is performed to initialize
                # all variables (e.g. X-Y), so that the program does not
                # complain about non-existing variables.
                enI, gradI = pes.getEnergyAndGradient_S0(x)
            else:
                energies, gradI = pes.getEnergiesAndGradient(x, I)
                enI = energies[I]
            print "E = %2.7f" % (enI)
            return enI, gradI

        xyz_trace = xyzfile.replace(".xyz", "_trace.xyz")

        # This is a callback function that is executed by numpy for each optimization step.
        # It appends the current geometry to an xyz-file.
        def save_xyz(x, mode="a"):
            atomlist_opt = XYZ.vector2atomlist(x, atomlist)
            XYZ.write_xyz(xyz_trace, [atomlist_opt],
                          title="charge=%s" % kwds.get("charge", 0),
                          mode=mode)

        save_xyz(x0, mode="w")  # write original geometry

        Nat = len(atomlist)
        min_options = {'gtol': 1.0e-7, 'norm': 2}
        # The "BFGS" method is probably better than "CG", but the line search in BFGS is expensive.
        res = optimize.minimize(f,
                                x0,
                                method="CG",
                                jac=True,
                                callback=save_xyz,
                                options=min_options)
        # res = optimize.minimize(f, x0, method="BFGS", jac=True, callback=save_xyz, options=options)
        xopt = res.x
        save_xyz(xopt)

        print "Intermediate geometries written into file {}".format(xyz_trace)

        # write optimized geometry into file
        atomlist_opt = XYZ.vector2atomlist(xopt, atomlist)
        xyz_opt = xyzfile.replace(".xyz", "_opt.xyz")
        XYZ.write_xyz(xyz_opt, [atomlist_opt],
                      title="charge=%s" % kwds.get("charge", 0),
                      mode="w")

        # calculate energy for optimized geometry
        dftb2 = DFTB2(atomlist_opt, **options)  # create dftb object
        dftb2.setGeometry(atomlist_opt, charge=kwds.get("charge", 0.0))

        dftb2.getEnergy(**scf_options)
        energies = list(dftb2.getEnergies())  # get partial energies

        if dftb2.long_range_correction == 1:  # add long range correction to partial energies
            energies.append(dftb2.E_HF_x)

        return str(energies)

    except:
        print sys.exc_info()
        return "error"
        return self.mm_energy

    def get_MM_Gradient(self):
        return self.mm_gradient

    def get_MM_Charges(self):
        return self.mm_charges


if __name__ == "__main__":
    import sys
    """
    log_file = sys.argv[1]
    print read_geometry(log_file)
#    print read_forces(log_file)
#    print read_force_constants(log_file)
    """
    xyz_file = sys.argv[1]
    atomlist = XYZ.read_xyz(xyz_file)[0]
    uff_handler = UFF_handler(atomlist)
    print uff_handler.get_MM_Charges()
    uff_handler.calc(atomlist)
    print uff_handler.get_MM_Gradient()
    print uff_handler.get_MM_Energy()

    uff_handler.calc(atomlist)
    print uff_handler.get_MM_Gradient()
    print uff_handler.get_MM_Energy()

#    uff_handler.clean_up()
Example #5
0
        "--out_file",
        dest="out_file",
        help=
        "The table with the isomer assignments for each geometry is written to this file [default: %default]",
        type=str,
        default="isomer_classification.dat")

    (opts, args) = parser.parse_args()
    if len(args) != 2:
        print usage
        exit(-1)

    dynamics_file = args[0]
    isomer_file = args[1]

    isomers = XYZ.read_xyz(isomer_file)
    # determined canonical connectivities of isomers
    isomer_connectivities = []
    for isomer in isomers:
        isomer_can, A_can = MolecularGraph.morgan_ordering(isomer,
                                                           hydrogen_bonds=True)
        isomer_connectivities.append(A_can)
    # all isomers should have different connectivities
    n = len(isomers)
    for i in range(0, n):
        for j in range(i + 1, n):
            if np.sum(
                (isomer_connectivities[i] - isomer_connectivities[j])**2) == 0:
                print "WARNING: Isomer %d and %d in file '%s' have the same adjacency matrices!" % (
                    i + 1, j + 1, isomer_file)
Example #6
0
    if len(args) < 2:
        print "Missing arguments:"
        print "    xyz_input xyz_output"
        exit(-1)

    xyz_in = args[0]
    xyz_out = args[1]

    if len(args) < 3:
        print "possible commands: 'scale', 'dislocate'"
        exit(-1)
    cmd = args[2]
    # the remaining command line arguments depend
    cmd_args = map(eval, args[3:])

    atomlist0 = XYZ.read_xyz(xyz_in)[-1]
    PG = PerturbedGeometries(atomlist0)

    kwds = XYZ.extract_keywords_xyz(xyz_in)

    if cmd == "scale":
        if len(cmd_args) < 3:
            print "Arguments for 'scale':"
            print "    smin smax N"
            exit(-1)
        geometries = PG.scale(*cmd_args)
    elif cmd == "dislocate":
        if len(cmd_args) < 4:
            print "Arguments for 'dislocate':"
            print "    atom radius nshells N"
            exit(-1)
Example #7
0
#!/usr/bin/env python
"""
print xyz-coordinates in a format that can be pasted into python scripts
"""
from DFTB import XYZ
import pprint

if __name__ == "__main__":
    import sys
    usage = "Usage: python %s <xyz input>\n" % sys.argv[0]

    if len(sys.argv) < 2:
        print usage
        exit(-1)
    xyz = sys.argv[1]
    atomlist = XYZ.read_xyz(xyz)[0]

    pprint.pprint(atomlist)
    # load cube files for components of vector potential
    print "load magnetic vector potential from cube files..."
    atomlist, origin, axes, Ax_data = Cube.readCube(Ax_cube_file)
    atomlist, origin, axes, Ay_data = Cube.readCube(Ay_cube_file)
    atomlist, origin, axes, Az_data = Cube.readCube(Az_cube_file)
    # extract positions of points and values of A
    points, Ax = Cube.get_points_and_values(origin, axes, Ax_data)
    points, Ay = Cube.get_points_and_values(origin, axes, Ay_data)
    points, Az = Cube.get_points_and_values(origin, axes, Az_data)

    # fit magnetic dipoles
    fitter = MagneticDipoleFitter()
    fitter.setFitPoints(points, Ax, Ay, Az)
    # fitting centers
    if opts.fit_centers != "":
        print "loading fit centers from '%s'" % opts.fit_centers
        atomlist = XYZ.read_xyz(opts.fit_centers)[0]
    fitter.setAtomicCenters(atomlist)

    magnetic_dipoles = fitter.fitVectorPotential(mtot)

    # save magnetic dipoles
    fh = open(dat_file, "w")
    print >> fh, "# atom-centered magnetic dipoles fitted to the vector potential A(r)"
    print >> fh, "# The dipoles were projected onto principle axes of rotation (with all masses = 1) "
    print >> fh, "#   Mx        My        Mz"
    np.savetxt(fh, magnetic_dipoles)
    fh.close()
    print "magnetic dipoles saved to '%s'" % dat_file
Example #9
0
    """ % basename(sys.argv[0])

    args = sys.argv[1:]

    if len(args) < 3:
        print usage
        exit(-1)

    xyz_file = args[0]  # path to xyz-file
    state1 = int(args[1])  # index of lower electronic state
    state2 = int(args[2])  # index of upper electronic state

    # load initial geometry, we take the last geometry, so it is
    # easier to restart a previous MECI calculation.
    atomlist0 = XYZ.read_xyz(xyz_file)[-1]
    # read the charge of the molecule from the comment line in the xyz-file
    kwds = XYZ.extract_keywords_xyz(xyz_file)
    # initialize the TD-DFTB calculator
    pes = PotentialEnergySurfaces(atomlist0, Nst=state2 + 1, **kwds)

    meci = MECI(
        atomlist0,
        pes,
        #coord_system='internal',
        coord_system='cartesian',
        state1=state1,
        state2=state2)

    meci.opt(step_size=0.1, gtol=0.001)
Example #10
0
    txt = "  %d C\n" % Nat
    txt += " O N C H\n"
    for i, (Zi, posi) in enumerate(atomlist):
        #        x,y,z = posi
        x, y, z = map(lambda v: AtomicData.bohr_to_angs * v, posi)
        txt += " %d  %d  %20.7f %20.7f %20.7f\n" % (i + 1, atomtypes[Zi], x, y,
                                                    z)
    txt += "%d\n" % (3 * Nat)
    for i in range(0, Nat):
        txt += "%d 1\n" % (i + 1)
        txt += "%d 2\n" % (i + 1)
        txt += "%d 3\n" % (i + 1)

    fh = open(gen_out, "w")
    print >> fh, txt
    fh.close()


if __name__ == "__main__":
    import sys
    usage = "Usage: python %s <xyz input> <gen output>\n" % sys.argv[0]
    usage += "  converts and xyz-file to the gen-format expected by Seifert's DFTB program\n"

    if len(sys.argv) < 3:
        print usage
        exit(-1)
    xyz_in = sys.argv[1]
    gen_out = sys.argv[2]

    write_gen(gen_out, XYZ.read_xyz(xyz_in)[0])
Example #11
0
                    redirect = " 2> /dev/null"
                else:
                    redirect = ""
                print "Optimizing geometries in %s with UFF force field => %s" % (
                    dynamic_file, opt_file)
                ret = os.system(
                    "obminimize -ff UFF %s %s | sed -e \"/^WARNING:/ d\" >  %s"
                    % (dynamic_file, redirect, opt_file))
                assert ret == 0, "Optimization with obminimize failed!"
            else:
                print "found optimized %s" % opt_file
            dynamic_file = opt_file

        print "Identifying and classifying fragments in %s" % dynamic_file
        try:
            geometries = XYZ.read_xyz(dynamic_file)
        except IOError:
            print "WARNING: could not open %s. - skipped" % dynamic_file
            continue
        geometries = [geometries[-1]]
        fragtraj, fragdic = MolecularGraph.fragment_trajectory(geometries)
        fragment_geometries.update(fragdic)
        # length of the i-th trajectory
        nt = max(len(fragtraj), len(ntraj))
        # extend fraction list so that it has as many time steps as the longest trajectory
        if len(ntraj) < nt:
            nadd = nt - len(ntraj)
            ntraj = np.hstack((ntraj, np.zeros(nadd)))
        ntraj[:len(fragtraj)] += 1
        # fragments
        for k, fracs in fragment_fractions.iteritems():
Example #12
0
    cut_atomlist = []
    for i,(Zi,posi) in enumerate(atomlist):
        if i in removed:
            pass
        else:
            cut_atomlist.append( (Zi, posi) )
    return cut_atomlist


if __name__ == "__main__":
    import sys
    from os.path import expandvars, expanduser

    from DFTB import XYZ

    usage = "python %s <in .xyz> <out .xyz> <radius in bohr>\n" % sys.argv[0]
    usage += "  removes all atoms outside sphere of radius R and all connected atoms\n"

    if len(sys.argv) < 4:
        print usage
        exit(-1)

    xyz_in = expandvars(expanduser(sys.argv[1]))
    xyz_out = expandvars(expanduser(sys.argv[2]))
    R = float(sys.argv[3])

    atomlist = XYZ.read_xyz(xyz_in)[0]
    cut_atomlist = cut_sphere(atomlist, R)
    print "Removed %d atoms" % (len(atomlist) - len(cut_atomlist))
    XYZ.write_xyz(xyz_out, [cut_atomlist])
        type=str,
        default="cartesian")

    (opts, args) = parser.parse_args()

    if len(args) < 4:
        parser.print_help()
        exit(-1)

    xyz0 = args[0]
    xyz1 = args[1]
    N = int(args[2])
    xyz_interp = args[3]

    # read initial geometry
    atomlist0 = XYZ.read_xyz(xyz0)[0]
    x0 = XYZ.atomlist2vector(atomlist0)

    # read final geometry
    atomlist1 = XYZ.read_xyz(xyz1)[0]
    x1 = XYZ.atomlist2vector(atomlist1)

    # interpolation parameter
    rs = np.linspace(0.0, 1.0, N)

    geometries_interp = []

    if opts.coord_system == "cartesian":
        for r in rs:
            xr = x0 + r * (x1 - x0)
            geometries_interp.append(XYZ.vector2atomlist(xr, atomlist0))
Example #14
0
from DFTB import XYZ
import sys

frame = 433
geometries = XYZ.read_xyz("dynamics.xyz")

XYZ.write_xyz("frame_%d.xyz" % frame, [geometries[433]])
Example #15
0
    def __init__(self, xyz_file, dyson_file=None):
        super(Main, self).__init__()
        self.settings = Settings({
            "Continuum Orbital": {
                "Ionization transitions":
                [0, ["only intra-atomic", "inter-atomic"]]
            },
            "Averaging": {
                "Euler angle grid points": 5,
                "polar angle grid points": 1000,
                "sphere radius Rmax": 300.0,
            },
            "Scan": {
                "nr. points": 20
            },
            "Cube": {
                "extra space / bohr": 15.0,
                "points per bohr": 3.0
            }
        })
        # perform DFTB calculation

        # BOUND ORBITAL = H**O
        self.atomlist = XYZ.read_xyz(xyz_file)[0]
        # shift molecule to center of mass
        print "shift molecule to center of mass"
        pos = XYZ.atomlist2vector(self.atomlist)
        masses = AtomicData.atomlist2masses(self.atomlist)
        pos_com = MolCo.shift_to_com(pos, masses)
        self.atomlist = XYZ.vector2atomlist(pos_com, self.atomlist)

        self.tddftb = LR_TDDFTB(self.atomlist)
        self.tddftb.setGeometry(self.atomlist, charge=0)
        options = {"nstates": 1}
        try:
            self.tddftb.getEnergies(**options)
        except DFTB.Solver.ExcitedStatesNotConverged:
            pass

        self.valorbs, radial_val = load_pseudo_atoms(self.atomlist)

        if dyson_file == None:
            # Kohn-Sham orbitals are taken as Dyson orbitals
            self.H**O, self.LUMO = self.tddftb.dftb2.getFrontierOrbitals()
            self.bound_orbs = self.tddftb.dftb2.getKSCoefficients()
            self.orbe = self.tddftb.dftb2.getKSEnergies()
            orbital_names = []
            norb = len(self.orbe)
            for o in range(0, norb):
                if o < self.H**O:
                    name = "occup."
                elif o == self.H**O:
                    name = "H**O"
                elif o == self.LUMO:
                    name = "LUMO "
                else:
                    name = "virtual"
                name = name + "  " + str(o).rjust(4) + (
                    "   %+10.3f eV" % (self.orbe[o] * 27.211))
                orbital_names.append(name)
            initially_selected = self.H**O
        else:
            # load coefficients of Dyson orbitals from file
            names, ionization_energies, self.bound_orbs = load_dyson_orbitals(
                dyson_file)
            self.orbe = np.array(ionization_energies) / 27.211
            orbital_names = []
            norb = len(self.orbe)
            for o in range(0, norb):
                name = names[o] + "  " + str(o).rjust(4) + (
                    "   %4.2f eV" % (self.orbe[o] * 27.211))
                orbital_names.append(name)
            initially_selected = 0

        self.photo_kinetic_energy = slako_tables_scattering.energies[0]
        self.epol = np.array([15.0, 0.0, 0.0])

        # Build Graphical User Interface
        main = QtGui.QWidget()
        mainLayout = QtGui.QHBoxLayout(main)
        #
        selectionFrame = QtGui.QFrame()
        selectionFrame.setSizePolicy(QtGui.QSizePolicy.Fixed,
                                     QtGui.QSizePolicy.Preferred)
        mainLayout.addWidget(selectionFrame)
        selectionLayout = QtGui.QVBoxLayout(selectionFrame)
        #
        label = QtGui.QLabel(selectionFrame)
        label.setText("Select bound MO:")
        selectionLayout.addWidget(label)

        # bound orbitals
        self.orbitalSelection = QtGui.QListWidget(selectionFrame)
        self.orbitalSelection.itemSelectionChanged.connect(
            self.selectBoundOrbital)
        norb = len(self.orbe)
        self.orbital_dict = {}
        for o in range(0, norb):
            name = orbital_names[o]
            self.orbital_dict[name] = o
            item = QtGui.QListWidgetItem(name, self.orbitalSelection)
            if o == initially_selected:
                selected_orbital_item = item
            selectionLayout.addWidget(self.orbitalSelection)

        ### VIEWS
        center = QtGui.QWidget()
        mainLayout.addWidget(center)
        centerLayout = QtGui.QGridLayout(center)
        #
        boundFrame = QtGui.QFrame()

        centerLayout.addWidget(boundFrame, 1, 1)
        boundLayout = QtGui.QVBoxLayout(boundFrame)
        # "Bound Orbital"
        label = QtGui.QLabel(boundFrame)
        label.setText("Bound Orbital")
        boundLayout.addWidget(label)
        #
        self.boundOrbitalViewer = QCubeViewerWidget(boundFrame)
        boundLayout.addWidget(self.boundOrbitalViewer)

        # continuum orbital
        continuumFrame = QtGui.QFrame()
        centerLayout.addWidget(continuumFrame, 1, 2)
        continuumLayout = QtGui.QVBoxLayout(continuumFrame)
        # "Dipole-Prepared Continuum Orbital"
        label = QtGui.QLabel(continuumFrame)
        label.setText("Dipole-Prepared Continuum Orbital")
        continuumLayout.addWidget(label)

        self.continuumOrbitalViewer = QCubeViewerWidget(continuumFrame)
        continuumLayout.addWidget(self.continuumOrbitalViewer)

        self.efield_objects = []
        self.efield_actors = []
        self.selected = None
        # picker
        self.picker = self.continuumOrbitalViewer.visualization.scene.mayavi_scene.on_mouse_pick(
            self.picker_callback)
        self.picker.tolerance = 0.01

        # PHOTO KINETIC ENERGY
        sliderFrame = QtGui.QFrame(continuumFrame)
        continuumLayout.addWidget(sliderFrame)
        sliderLayout = QtGui.QHBoxLayout(sliderFrame)
        # label
        self.pke_label = QtGui.QLabel()
        self.pke_label.setText("PKE: %6.4f eV" %
                               (self.photo_kinetic_energy * 27.211))
        sliderLayout.addWidget(self.pke_label)
        # Slider for changing the PKE
        self.pke_slider = QtGui.QSlider(QtCore.Qt.Horizontal)
        self.pke_slider.setMinimum(0)
        self.pke_slider.setMaximum(len(slako_tables_scattering.energies) - 1)
        self.pke_slider.setValue(0)
        self.pke_slider.sliderReleased.connect(self.changePKE)
        self.pke_slider.valueChanged.connect(self.searchPKE)
        sliderLayout.addWidget(self.pke_slider)

        #

        # molecular frame photoangular distribution
        mfpadFrame = QtGui.QFrame()
        centerLayout.addWidget(mfpadFrame, 2, 1)
        mfpadLayout = QtGui.QVBoxLayout(mfpadFrame)
        mfpadLayout.addWidget(QtGui.QLabel("Molecular Frame PAD"))
        mfpadTabs = QtGui.QTabWidget()
        mfpadLayout.addWidget(mfpadTabs)
        # 2D map
        mfpadFrame2D = QtGui.QFrame()
        mfpadTabs.addTab(mfpadFrame2D, "2D")
        mfpadLayout2D = QtGui.QVBoxLayout(mfpadFrame2D)
        self.MFPADfig2D = Figure()
        self.MFPADCanvas2D = FigureCanvas(self.MFPADfig2D)
        mfpadLayout2D.addWidget(self.MFPADCanvas2D)
        self.MFPADCanvas2D.draw()
        NavigationToolbar(self.MFPADCanvas2D, mfpadFrame2D, coordinates=True)
        # 3D
        mfpadFrame3D = QtGui.QFrame()
        mfpadTabs.addTab(mfpadFrame3D, "3D")
        mfpadLayout3D = QtGui.QVBoxLayout(mfpadFrame3D)
        self.MFPADfig3D = Figure()
        self.MFPADCanvas3D = FigureCanvas(self.MFPADfig3D)
        mfpadLayout3D.addWidget(self.MFPADCanvas3D)
        self.MFPADCanvas3D.draw()
        NavigationToolbar(self.MFPADCanvas3D, mfpadFrame3D, coordinates=True)

        # orientation averaged photoangular distribution
        avgpadFrame = QtGui.QFrame()
        centerLayout.addWidget(avgpadFrame, 2, 2)
        avgpadLayout = QtGui.QVBoxLayout(avgpadFrame)
        self.activate_average = QtGui.QCheckBox("Orientation Averaged PAD")
        self.activate_average.setToolTip(
            "Check this box to start averaging of the molecular frame PADs over all orientations. This can take a while."
        )
        self.activate_average.setCheckState(QtCore.Qt.Unchecked)
        self.activate_average.stateChanged.connect(self.activateAveragedPAD)
        avgpadLayout.addWidget(self.activate_average)

        avgpadTabs = QtGui.QTabWidget()
        avgpadLayout.addWidget(avgpadTabs)
        # 1D map
        avgpadFrame1D = QtGui.QFrame()
        avgpadTabs.addTab(avgpadFrame1D, "1D")
        avgpadLayout1D = QtGui.QVBoxLayout(avgpadFrame1D)
        self.AvgPADfig1D = Figure()
        self.AvgPADCanvas1D = FigureCanvas(self.AvgPADfig1D)
        avgpadLayout1D.addWidget(self.AvgPADCanvas1D)
        self.AvgPADCanvas1D.draw()
        NavigationToolbar(self.AvgPADCanvas1D, avgpadFrame1D, coordinates=True)
        # 2D map
        avgpadFrame2D = QtGui.QFrame()
        avgpadFrame2D.setToolTip(
            "The averaged PAD should have no phi-dependence anymore. A phi-dependence is a sign of incomplete averaging."
        )
        avgpadTabs.addTab(avgpadFrame2D, "2D")
        avgpadLayout2D = QtGui.QVBoxLayout(avgpadFrame2D)
        self.AvgPADfig2D = Figure()
        self.AvgPADCanvas2D = FigureCanvas(self.AvgPADfig2D)
        avgpadLayout2D.addWidget(self.AvgPADCanvas2D)
        self.AvgPADCanvas2D.draw()
        NavigationToolbar(self.AvgPADCanvas2D, avgpadFrame2D, coordinates=True)
        # Table
        avgpadFrameTable = QtGui.QFrame()
        avgpadTabs.addTab(avgpadFrameTable, "Table")
        avgpadLayoutTable = QtGui.QVBoxLayout(avgpadFrameTable)
        self.avgpadTable = QtGui.QTableWidget(0, 6)
        self.avgpadTable.setToolTip(
            "Activate averaging and move the PKE slider above to add a new row with beta values. After collecting betas for different energies you can save the table or plot a curve beta(PKE) for the selected orbital."
        )
        self.avgpadTable.setHorizontalHeaderLabels(
            ["PKE / eV", "sigma", "beta1", "beta2", "beta3", "beta4"])
        avgpadLayoutTable.addWidget(self.avgpadTable)
        # Buttons
        buttonFrame = QtGui.QFrame()
        avgpadLayoutTable.addWidget(buttonFrame)
        buttonLayout = QtGui.QHBoxLayout(buttonFrame)
        deleteButton = QtGui.QPushButton("Delete")
        deleteButton.setToolTip("clear table")
        deleteButton.clicked.connect(self.deletePADTable)
        buttonLayout.addWidget(deleteButton)
        buttonLayout.addSpacing(3)
        scanButton = QtGui.QPushButton("Scan")
        scanButton.setToolTip(
            "fill table by scanning automatically through all PKE values")
        scanButton.clicked.connect(self.scanPADTable)
        buttonLayout.addWidget(scanButton)
        saveButton = QtGui.QPushButton("Save")
        saveButton.setToolTip("save table as a text file")
        saveButton.clicked.connect(self.savePADTable)
        buttonLayout.addWidget(saveButton)
        plotButton = QtGui.QPushButton("Plot")
        plotButton.setToolTip("plot beta2 column as a function of PKE")
        plotButton.clicked.connect(self.plotPADTable)
        buttonLayout.addWidget(plotButton)
        """
        # DOCKS
        self.setDockOptions(QtGui.QMainWindow.AnimatedDocks | QtGui.QMainWindow.AllowNestedDocks)
        #
        selectionDock = QtGui.QDockWidget(self)
        selectionDock.setWidget(selectionFrame)
        selectionDock.setFeatures(QtGui.QDockWidget.DockWidgetFloatable | QtGui.QDockWidget.DockWidgetMovable)
        self.addDockWidget(QtCore.Qt.DockWidgetArea(1), selectionDock)
        #
        boundDock = QtGui.QDockWidget(self)
        boundDock.setWidget(boundFrame)
        boundDock.setFeatures(QtGui.QDockWidget.DockWidgetFloatable | QtGui.QDockWidget.DockWidgetMovable)
        boundDock.setSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred)
        self.addDockWidget(QtCore.Qt.DockWidgetArea(2), boundDock)
        # 
        continuumDock = QtGui.QDockWidget(self)
        continuumDock.setWidget(continuumFrame)
        continuumDock.setFeatures(QtGui.QDockWidget.DockWidgetFloatable | QtGui.QDockWidget.DockWidgetMovable)
        continuumDock.setSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred)
        self.addDockWidget(QtCore.Qt.DockWidgetArea(2), continuumDock)
        """
        self.setCentralWidget(main)

        self.status_bar = QtGui.QStatusBar(main)
        self.setStatusBar(self.status_bar)
        self.default_message = "Click on the tip of the green arrow in the top right figure to change the orientation of the E-field"
        self.statusBar().showMessage(self.default_message)

        # Menu bar
        menubar = self.menuBar()
        exitAction = QtGui.QAction('&Exit', self)
        exitAction.setShortcut('Ctrl+Q')
        exitAction.setStatusTip('Exit program')
        exitAction.triggered.connect(exit)
        fileMenu = menubar.addMenu('&File')
        fileMenu.addAction(exitAction)

        settingsMenu = menubar.addMenu('&Edit')
        settingsAction = QtGui.QAction('&Settings...', self)
        settingsAction.setStatusTip('Edit settings')
        settingsAction.triggered.connect(self.editSettings)
        settingsMenu.addAction(settingsAction)

        self.loadContinuum()
        # select H**O
        selected_orbital_item.setSelected(True)
Example #16
0
    window = QtGui.QMainWindow()
    viewer = QCubeViewerWidget(window)

    files = sys.argv[1:]
    cubes = []
    molecules = []
    charge_lists = []
    for f in files:
        if ".cub" in f:
            cube = CubeData()
            cube.loadFromFile(f)
            cubes.append(cube)
            molecules.append(cube.atomlist)
        elif ".xyz" in f:
            atomlist = XYZ.read_xyz(f)[-1]
            molecules.append(atomlist)
        elif ".chg" in f:
            atomlist, charges = XYZ.read_charges(f)
            molecules.append(atomlist)
            charge_lists.append(charges)
        else:
            print "Unknown file type: %s" % f
        window.setWindowTitle(window.windowTitle() + " %s " % f)
    viewer.setCubes(cubes)
    viewer.setGeometries(molecules)
    
    if len(charge_lists) > 0:
        viewer.setGeometriesAndCharges(molecules, charge_lists)
        viewer.selectShowOptions(options=["surfaces", "charges", "transition charges"])
        
Example #17
0
    """
    fragtraj = []
    fragdic = {
    }  # dictionary that translates fragment identifiers into molecular geometries
    for atomlist in geometries:
        fragments = disconnected_fragments(atomlist)
        fragment_labels = [
            identifier(*morgan_ordering(atomlist)) for atomlist in fragments
        ]
        #
        for ifrag, fl in enumerate(fragment_labels):
            if fl not in fragdic:
                fragdic[fl] = fragments[ifrag]
        #
        fragtraj.append(fragment_labels)
    return fragtraj, fragdic


if __name__ == "__main__":
    import sys
    atomlist = XYZ.read_xyz(sys.argv[1])[0]
    fragments = disconnected_fragments(atomlist)

    atomlists_ordered = [
        morgan_ordering(atomlist)[0] for atomlist in fragments
    ]

    XYZ.write_xyz("/tmp/fragments.xyz", atomlists_ordered)  #atomlists_frag)

    print((fragment_trajectory(XYZ.read_xyz(sys.argv[1]))))
Example #18
0
def has_Cn(atomlist):
    pass

def has_reflection(atomlist):
    pass

########################################

def write_atomlist(atomlist):
    Nat = len(atomlist)
    pos = XYZ.atomlist2vector(atomlist)
    txt  = "                in Angstrom:\n"
    txt +=     "Atom          X           Y           Z\n"
    for i in range(0, Nat):
        txt += ("  %s  " % i).rjust(3)
        txt += "%+4.7f  %+4.7f  %+4.7f\n" % tuple(pos[3*i:3*(i+1)]*AtomicData.bohr_to_angs)
    txt += "\n"
    return txt

########################################


if __name__ == "__main__":
    import sys
    atomlist = XYZ.read_xyz(sys.argv[1])[0]
    atomlist_std = MolCo.standard_orientation(atomlist)
    group = detect_symmetry_brute_force(atomlist_std)
#    group = C2v()
    group.check_symmetry(atomlist_std)
#    atomlist_std_trans = group.elems[1].transform(atomlist_std)
Example #19
0
    if len(args) < 3:
        print usage
        exit(-1)

    geom_file = args[0]
    energy_file = args[1]
    force_file = args[2]

    print "Compute forces with DFTB"
    print "========================"
    print ""
    fh_en = open(energy_file, "w")
    print >> fh_en, "# ELECTRONIC ENERGY / HARTREE"

    # first geometry
    atomlist = XYZ.read_xyz(geom_file)[0]
    # read charge from title line in .xyz file
    kwds = XYZ.extract_keywords_xyz(geom_file)
    charge = kwds.get("charge", opts.charge)

    pes = PotentialEnergySurfaces(atomlist, charge=charge)
    # dftbaby needs one excited states calculation to set all variables
    x = XYZ.atomlist2vector(atomlist)
    pes.getEnergies(x)

    for i, atomlist in enumerate(XYZ.read_xyz(geom_file)):
        # compute electronic ground state forces with DFTB
        x = XYZ.atomlist2vector(atomlist)
        en = pes.getEnergy_S0(x)
        # total ground state energy including repulsive potential
        en_tot = en[0]
Example #20
0
        if line.strip()[0] == "#":
            # ignore comments
            continue
        molname, geom_file, dftb_force_file, force_file, keywords_str = line.strip(
        ).split(None, 4)
        molname = molname.replace("__", " ")
        keywords = dict(
            map(
                lambda s: tuple(
                    s.replace(" ", "").replace("\t", "").split("=")),
                keywords_str.split()))
        weight = float(keywords.get("weight", 1.0))
        max_error = float(keywords.get("max_error", 0.01))
        active_atoms_str = keywords.get("active_atoms", "")
        if active_atoms_str == "":
            # include all atoms
            active_atoms = []
        else:
            active_atoms = map(int, active_atoms_str.split(","))

        print "weight = %s" % weight
        print "max_error = %s" % max_error
        geometries = XYZ.read_xyz(geom_file)
        forces_wo_frep = XYZ.read_xyz(dftb_force_file, units="hartree/bohr")
        forces_with_frep = XYZ.read_xyz(force_file, units="hartree/bohr")
        print "add geometries from %s" % geom_file
        Fitter.add_polyatomic_curve(geometries, forces_wo_frep, forces_with_frep, \
                                 curve_name=molname, weight=weight, max_error=max_error, active_atoms=active_atoms)
#    Fitter.fit(3.0, 30.0)
    Fitter.fit(**options)
if __name__ == "__main__":
    import sys
    from optparse import OptionParser

    usage = "Usage: python %s <monomer geometry .xyz> <polymer geometry .xyz> <pattern for monomer transition densities> <pattern for polymer transition densities>\n" % sys.argv[0]
    usage += "  The excited states of the polymer are analysed in terms of the excited states of the monomer\n"

    parser = OptionParser(usage)

    (opts, args) = parser.parse_args()
    if len(args) < 4:
        print(usage)
        exit(-1)

    atomlist_mono = XYZ.read_xyz(args[0])[0]
    atomlist_poly = XYZ.read_xyz(args[1])[0]
    monomer_pattern = args[2]
    polymer_pattern = args[3]

    print("load transition densities for monomer states")
    Ptrans_mono = []  # list of transition densities matrices in AO basis, one for each state
    for tdense_file in glob.glob(monomer_pattern+"*.mat"):
        print(tdense_file)
        PtransI = np.loadtxt(tdense_file)
        # remove hydrogen orbitals
        nao,nao = PtransI.shape
        nhyd = count_hydrogens(atomlist_mono)
        print(("remove %d hydrogens" % nhyd))
        PtransI = PtransI[:(nao-nhyd),:][:,:(nao-nhyd)]
        Ptrans_mono.append(PtransI)
Example #22
0
    parser = OptionParser(usage)
    parser.add_option(
        "--convert",
        dest="convert",
        help=
        "Type of conversion: 'b2a' - from bohr to Angstrom, 'a2b' - from Angstrom to bohr [default: %default]",
        default="b2a")
    (opts, args) = parser.parse_args()
    if len(args) < 2:
        print(usage)
        exit(-1)
    xyz_in = args[0]
    xyz_out = args[1]
    if xyz_in[-2:] == "in":
        # initial conditions file ###.in
        coords, vels = XYZ.read_initial_conditions(xyz_in, units="")
        structures = [coords]
    else:
        structures = XYZ.read_xyz(xyz_in, units="")
    unit_fac, units = unit_conversion[opts.convert]
    for i, atomlist_in in enumerate(structures):
        vec_in = XYZ.atomlist2vector(atomlist_in)
        vec_out = unit_fac * vec_in
        atomlist_out = XYZ.vector2atomlist(vec_out, atomlist_in)
        if i == 0:
            mode = "w"
        else:
            mode = "a"
        XYZ.write_xyz(xyz_out, [atomlist_out], units="", mode=mode)
Example #23
0
"""
compute gradients along a trajectory of geometries using Gaussian
"""
from DFTB import XYZ
import Gaussian

if __name__ == "__main__":
    import sys
    import os
    if len(sys.argv) < 3:
        print "Usage: %s <geometry file> <gradient file>" % sys.argv[0]
        print "Compute gradients for all geometries in <geometry file> and write them to <gradient file>"
        exit(-1)
    geom_file = sys.argv[1]
    grad_file = sys.argv[2]
    tmp_dir = "/scratch/humeniuka/dftb/"
    os.system("module load g09")
    for atomlist in XYZ.read_xyz(geom_file):
        tmp_com = tmp_dir + "gaussian.com"
        tmp_out = tmp_dir + "gaussian.log"
        Gaussian.write_input(tmp_com, atomlist, \
                        route="# PBE/6-311G(3df,3pd)++ Force", \
                        title="Gradients for fitting repulsive potential")
        # compute forces with gaussian
        os.system("g09 < %s > %s" % (tmp_com, tmp_out))
        try:
            forces = Gaussian.read_forces(tmp_com)
        except Gaussian.FormatError as e:
            print e
        XYZ.write(grad_file, [forces], title="forces", units="forces", mode='a')
def hessian(xyzfile, optionfile):
    """calculates hessian matrix"""

    outputfile = open("output_dftb.txt", "a")  # redirect output to file
    sys.stdout = outputfile

    try:
        I = 0  # index of electronic state (ground state)

        atomlist = XYZ.read_xyz(xyzfile)[0]  # read xyz file
        kwds = XYZ.extract_keywords_xyz(xyzfile)  # read keywords (charge)
        options = read_options(optionfile)  # read options
        scf_options = extract_options(options,
                                      SCF_OPTIONLIST)  # get scf-options

        pes = MyPES(atomlist, options, Nst=max(I + 1, 2), **kwds)  # create PES

        atomvec = XYZ.atomlist2vector(atomlist)  # convert atomlist to vector

        # FIND ENERGY MINIMUM
        # f is the objective function that should be minimized
        # it returns (f(x), f'(x))
        def f(x):
            if I == 0 and type(pes.tddftb.XmY) != type(None):
                # only ground state is needed. However, at the start
                # a single TD-DFT calculation is performed to initialize
                # all variables (e.g. X-Y), so that the program does not
                # complain about non-existing variables.
                enI, gradI = pes.getEnergyAndGradient_S0(x)
            else:
                energies, gradI = pes.getEnergiesAndGradient(x, I)
                enI = energies[I]
            return enI, gradI

        minoptions = {'gtol': 1.0e-7, 'norm': 2}
        # somehow numerical_hessian does not work without doing this mimimization before
        res = optimize.minimize(f,
                                atomvec,
                                method="CG",
                                jac=True,
                                options=minoptions)

        # COMPUTE HESSIAN AND VIBRATIONAL MODES
        # The hessian is calculated by numerical differentiation of the
        # analytical gradients
        def grad(x):
            if I == 0:
                enI, gradI = pes.getEnergyAndGradient_S0(x)
            else:
                energies, gradI = pes.getEnergiesAndGradient(x, I)
            return gradI

        print "Computing Hessian"  # calculate hessians from gradients
        hess = HarmonicApproximation.numerical_hessian_G(grad, atomvec)

        string = ""  # create string that is to be written into file
        for line in hess:
            for column in line:
                string += str(column) + " "
            string = string[:-1] + "\n"

        with open("hessian.txt",
                  "w") as hessianfile:  # write hessian matrix to file
            hessianfile.write(string)
            # this would look nicer but is not as exact
            #hessianfile.write(annotated_hessian(atomlist, hess))

        # calculate energy for optimized geometry
        dftb2 = DFTB2(atomlist, **options)  # create dftb object
        dftb2.setGeometry(atomlist, charge=kwds.get("charge", 0.0))

        dftb2.getEnergy(**scf_options)
        energies = list(dftb2.getEnergies())  # get partial energies

        if dftb2.long_range_correction == 1:  # add long range correction to partial energies
            energies.append(dftb2.E_HF_x)

        return str(energies)

    except:
        print sys.exc_info()
        return "error"
Example #25
0
    usage += "  To see a list of all available fragments run the program without the list parameter.\n"
    usage += "  Type --help to see all options."
    parser = optparse.OptionParser(usage)
    parser.add_option(
        "--filter_mode",
        dest="filter_mode",
        help=
        "Determines whether the filter should 'keep' or 'delete' the selected fragments [default: %default]",
        default="keep")
    parser.add_option(
        "--out_xyz",
        dest="out_xyz",
        help="Filtered geometry is written to this file [default: %default]",
        default="filtered.xyz")

    (opts, args) = parser.parse_args()
    if len(args) < 1:
        print(usage)
        exit(-1)
    xyz_in = args[0]
    selected_fragments = args[1:]

    atomlist_full = XYZ.read_xyz(xyz_in)[-1]
    atomlist_filtered = filter_fragments(atomlist_full,
                                         selected_fragments,
                                         filter_mode=opts.filter_mode)

    if len(selected_fragments) > 0:
        XYZ.write_xyz(opts.out_xyz, [atomlist_filtered])
        print("filtered geometry written to %s" % opts.out_xyz)
Example #26
0
    print """
    ****************************
    *                          *
    *  Nudged Elastic Band     *
    *                          *
    ****************************
    """
    print opts

    # path to xyz-file
    xyz_file = args[0]
    #
    name = basename(xyz_file.replace(".xyz", ""))
    # Read the geometry from the xyz-file
    atomlists = XYZ.read_xyz(xyz_file)
    atomlist = atomlists[0]

    neb = NEB(force_constant=opts.force_constant,
              mass=opts.mass,
              nr_processors=opts.nr_processors)
    neb.setGeometry(atomlist)
    neb.setName(name)

    images = [XYZ.atomlist2vector(atomlist) for atomlist in atomlists]
    neb.setImages(images, states=[0 for im in images])
    neb.addImagesLinearly(2)
    # save initial path
    neb.plot()
    neb.findMEP(tolerance=opts.tolerance,
                nsteps=opts.nsteps,
Example #27
0
"""
split an xyz file that contains many structures into separate files
"""
from DFTB import XYZ

if __name__ == "__main__":
    import sys
    import optparse
    usage = "Usage: python %s <xyz file with many structures> <output prefix>\n" % sys.argv[
        0]
    usage += "  splits the input file into output prefix_####.xyz"

    parser = optparse.OptionParser(usage)
    parser.add_option(
        "--step",
        dest="step",
        help="Only every N-th geometry is extracted [default: %default]",
        type=int,
        default=1)
    (opts, args) = parser.parse_args()

    if len(args) < 2:
        print usage
        exit(-1)
    xyz_file = sys.argv[1]
    prefix = sys.argv[2]
    structures = XYZ.read_xyz(xyz_file)
    for i, atomlist in enumerate(structures):
        if (i + 1) % opts.step == 0 or i == 0:
            XYZ.write_xyz(prefix + "%.4d.xyz" % (i + 1), [atomlist])
def test_scattering_orbitals():
    from DFTB.LR_TDDFTB import LR_TDDFTB
    from DFTB import XYZ

    atomlist = XYZ.read_xyz("h2.xyz")[0]

    tddftb = LR_TDDFTB(atomlist)
    tddftb.setGeometry(atomlist, charge=0)
    options = {"nstates": 1}
    tddftb.getEnergies(**options)

    valorbs, radial_val = load_pseudo_atoms(atomlist)

    E = 5.0 / 27.211
    bs = AtomicScatteringBasisSet(atomlist, E)
    print bs.bfs

    SKT_bf, SKT_ff = load_slako_scattering(atomlist, E)
    S_bb, H0_bb = tddftb.dftb2._constructH0andS()
    S_bf, H0_bf = ScatteringHamiltonianMatrix(atomlist, valorbs, SKT_bf)
    #
    invS_bb = la.inv(S_bb)
    # (H-E*S)^t . Id . (H-E*S)
    HmE2 = np.dot(H0_bf.conjugate().transpose(), np.dot(invS_bb, H0_bf)) \
           - E * np.dot( S_bf.conjugate().transpose(), np.dot(invS_bb, H0_bf)) \
           - E * np.dot(H0_bf.conjugate().transpose(), np.dot(invS_bb,  S_bf)) \
           + E**2 * np.dot(S_bf.conjugate().transpose(), np.dot(invS_bb, S_bf))
    Scont = continuum_flux(atomlist, SKT_bf)
    S2 = np.dot(S_bf.conjugate().transpose(), np.dot(la.inv(S_bb), S_bf))
    """
    #
    H2 = np.dot(H0_bf.transpose(), np.dot(la.inv(S_bb), H0_bf))
    S2 = np.dot( S_bf.transpose(), np.dot(la.inv(S_bb), S_bf))
    print "H2"
    print H2
    print "S2"
    print S2
    scat_orbe2, scat_orbs = sla.eig(H2) #, S2)
    print "PKE = %s" % E
    print "Energies^2 = %s" % scat_orbe2
    scat_orbe = np.sqrt(scat_orbe2)
    sort_indx = np.argsort(scat_orbe)
    scat_orbe = scat_orbe[sort_indx]
    scat_orbs = scat_orbs[:,sort_indx]
    print "Energies of scattering orbitals: %s" % scat_orbe
    orbE = np.argmin(abs(scat_orbe-E))
    """
    assert np.sum(abs(HmE2.conjugate().transpose() - HmE2)) < 1.0e-10
    assert np.sum(abs(S2.conjugate().transpose() - S2)) < 1.0e-10
    lambdas, scat_orbs = sla.eigh(HmE2)
    print "lambdas = %s" % lambdas

    from DFTB.Scattering import PAD

    for i in range(0, len(lambdas)):
        if abs(lambdas[i]) > 1.0e-8:
            print "%d  lambda = %s" % (i, lambdas[i])

            ###
            def wavefunction(grid, dV):
                # evaluate orbital
                amp = Cube.orbital_amplitude(grid,
                                             bs.bfs,
                                             scat_orbs[:, i],
                                             cache=False)
                return amp

            PAD.asymptotic_density(wavefunction, 20, E)
            ###

            for (flm, l, m) in classify_lm(bs, scat_orbs[:, i]):
                if abs(flm).max() > 1.0e-4:
                    print " %s %s     %s" % (l, m, abs(flm))
            Cube.orbital2grid(atomlist, bs.bfs, scat_orbs[:,i], \
                          filename="/tmp/scattering_orbital_%d.cube" % i, dbuff=25.0)
            delattr(Cube.orbital_amplitude, "cached_grid")
Example #29
0
        positions, velocities = velocities_finite_diff(fragment_atomlists[f],
                                                       dt)
        for i in range(0, Nt):
            vm = velocities[i] * masses
            vel_com = np.array(
                [np.sum(vm[0::3]),
                 np.sum(vm[1::3]),
                 np.sum(vm[2::3])]) / M
            ekin_com_f = 1.0 / 2.0 * M * np.sum(vel_com**2)
            ekin_tot_f = 1.0 / 2.0 * np.sum(masses * velocities[i]**2)

            ekin_com[i, f] += ekin_com_f
            ekin_tot[i, f] += ekin_tot_f
    return ekin_com, ekin_tot


if __name__ == "__main__":
    import sys
    traj_file = sys.argv[1]
    dt = float(sys.argv[2])
    atomlists = XYZ.read_xyz(traj_file)
    ekin_com, ekin_tot = partition_kinetic_energy(atomlists, 3.0)

    print((ekin_com[:100, 0]))
    print((ekin_com[:100, 1]))
    import matplotlib.pyplot as plt

    for f in range(0, 2):
        plt.plot(ekin_com[:, f] / ekin_com[:, f].max(), ls="-.")
    plt.show()