Example #1
0
 def __init__(self, data) :
     """
     data -- contents of an .xyz file as a str
     """
     data = data.split('\n')
     self.natom = int(data[0])
     self.units = data[1]
     
     self.labels = []
     self.masses = []
     self.charges = []
     self.geom = []
     
     for atom in data[2:] :
         
         atom = atom.split()
         
         if len(atom) != 4 :
             continue # Throw Error?
         self.labels.append(atom[0])
         self.masses.append(m.get_mass(atom[0]))
         self.charges.append(m.get_charge(atom[0]))
         self.geom.append(atom[1:])
     
     self.geom = [[float(coord) for coord in atom] for atom in self.geom]
Example #2
0
    def __init__(self, xyzfile):
        with open(xyzfile, "r") as f:
            lines = f.readlines() #opening the xyz file for reading
        self.xyz = xyzfile

        self.natom = int(lines[0]) #first line = num of atoms

        if len(lines) != (self.natom + 2):
            print("Error: incorrectly formatted xyz file")
            return

        self.units = lines[1].rstrip() #second line = Angstroms or Bohr
        if self.units != "Angstrom" and self.units != "Bohr":
            print("Error: unspecified units or units we are currently unequipped to handle.")
            return

        self.labels = []
        for line in lines[2:]:  #from the third line to the end
            self.labels = self.labels + [line[0]] #append the first character

        self.masses = [masses.get_mass(i) for i in self.labels] #creates a list of the masses

        self.charges = [masses.get_charge(i) for i in self.labels] #creates a list of the charges

        fgeoms = []
        for line in lines[2:]:  #from the third line to the end
            line = line.split()
            newline = line[1:]  #leave out the atom name, have list of xyz's
            for i in range(len(newline)):
                newline[i] = float(newline[i])  #converting to float
            fgeoms = fgeoms + [newline]  #a list of lists of the xyz values
        self.geoms = np.array(fgeoms)  #making an array out of the list of lists
Example #3
0
    def __init__(self, geom):
        """
        Creates a molecule with a geometry and corresponding units
        """

        lines = geom.strip().split("\n")

        units = lines[1].lower()
        
        natom = int(lines[0])

        atoms = []
        geom = []

        for line in lines[2:]:
            atom, x, y, z = line.split()
            atoms.append(atom)
            geom.append([float(x), float(y), float(z)])

        self.units = units
        self.natom = natom
        self.atoms = atoms
        self.geom = np.array(geom)

        mass = []
        charges =[]

        for atom in atoms:
            mass.append(float(masses.get_mass(atom)))
            charges.append(int(masses.get_charge(atom))) #might want to include symbols

        self.mass = mass
        self.charges = charges
Example #4
0
    def __init__(self,data):
        #checking if input string is filename or xyzstring by determining number of lines
        if data.endswith('.xyz'):
            with open(data, 'r') as moleculefile:
                self.moleculelines = moleculefile.readlines()
        else:
            self.moleculelines = data.split('\n')
        #units are supplied on line 2
        self.units = self.moleculelines[1].rstrip()
        #number of atoms is supplied on line 1
        self.natom = int((self.moleculelines[0]).rstrip())

        #create empty lists of atom labels, masses, charge, and geometry matrix         for later population
        self.labels = []
        self.masses = []
        self.charges = []
        self.geom = np.zeros((self.natom,3))

        #loop through atoms and populate information into empty lists
        for atom in range(self.natom):
            #+2 because atoms start at line 3
            element,x,y,z = self.moleculelines[atom+2].split()

            self.labels.append(element)
            self.charges.append(masses.get_charge(element))
            self.masses.append(masses.get_mass(element))
            self.geom[atom] = [x,y,z]
Example #5
0
	def __init__(self,TextFile):
		# Empty arrays defined to be later appended to
		self.current = 0
		self.textfile = TextFile
		labels = []
		geom = []
		charges = []
		mass = []
		# open text file, read in the values, and store them as the desired units
		with open(TextFile,'r') as my_file:
			data = my_file.read().replace('\n',' ')
			data = data.split()
			self.natom = int(data[0])
			del data[0]
			self.units = data[0]
			del data[0]
			# reading in rest of the data
			for i in range(self.natom):
				# Store the first line of the column as a label
				labels.append(data[4*i])
				# Temporary list defined to store subarray of geom
				temp = []
				# Cycle through the x,y,z coordinates
				for j in range(3):
					temp.append(float(data[4 * i + j + 1]))
				# Append 1x3 subarray to geom array
				geom.append(temp)
			self.labels = labels
			self.geom = np.array(geom)
			for i in range(self.natom):
				mass.append(masses.get_mass(str(labels[i])))
				charges.append(masses.get_charge(str(labels[i])))
			self.charges = charges
			self.masses = mass
Example #6
0
    def mass_charge(self):
        sys.path.insert(0, '../../extra-files')
        import masses as M

        mass = [float(M.get_mass(self.labels[i])) for i in range(self.natom)]
        charge = [M.get_charge(self.labels[i]) for i in range(self.natom)]
        return (mass, charge)
Example #7
0
def generate_sto3g_data(atoms, geom):
    """Create the sto3g_data."""
    sto3g_data = []
    for atom, geom in zip(atoms, geom):
        for subshell, coefficient in zip(subshells[atom], coefficient_tuple):
            atom_index = masses.get_charge(atom) - 1
            for orbital in subshell_to_orbitals(subshell):
                # A full function will be needed for this if I extend into d
                # block elements.
                subshell_index = int(orbital[0]) - 1
                sto3g_data.append({
                    "a":
                    exponential_tuple[atom_index][subshell_index],
                    "d":
                    coefficient,
                    "r":
                    geom.tolist()[0],
                    "l":
                    1 if orbital == "2px" else 0,
                    "m":
                    1 if orbital == "2py" else 0,
                    "n":
                    1 if orbital == "2pz" else 0,
                })
    return sto3g_data
Example #8
0
    def __init__(self, geom):
        """
        Creates a molecule with a geometry and corresponding units
        """

        lines = geom.strip().split("\n")

        units = lines[1].lower()

        natom = int(lines[0])

        atoms = []
        geom = []

        for line in lines[2:]:
            atom, x, y, z = line.split()
            atoms.append(atom)
            geom.append([float(x), float(y), float(z)])

        self.units = units
        self.natom = natom
        self.atoms = atoms
        self.geom = np.array(geom)

        mass = []
        charges = []

        for atom in atoms:
            mass.append(float(masses.get_mass(atom)))
            charges.append(int(
                masses.get_charge(atom)))  #might want to include symbols

        self.mass = mass
        self.charges = charges
Example #9
0
    def __init__(self, data):
        """
        data -- contents of an .xyz file as a str
        """
        data = data.split('\n')
        self.natom = int(data[0])
        self.units = data[1]

        self.labels = []
        self.masses = []
        self.charges = []
        self.geom = []

        for atom in data[2:]:

            atom = atom.split()

            if len(atom) != 4:
                continue  # Throw Error?
            self.labels.append(atom[0])
            self.masses.append(m.get_mass(atom[0]))
            self.charges.append(m.get_charge(atom[0]))
            self.geom.append(atom[1:])

        self.geom = [[float(coord) for coord in atom] for atom in self.geom]
Example #10
0
	def read(self, geom_str):
		#Read in the file containing the geometry of the molecule in question
		#print("\n" + "MOLECULE INFORMATION" + "\n")
		geom = []
		self.labels = []
		self.masses = []
		self.charges = []
		lines = geom_str.strip().splitlines()
		self.natom = int(lines[0])
		#print("Number of atoms: " + str(self.natom) + "\n")
		#print("Units are currently in: " + self.units + "\n")
		for line in lines[2:]:
			atom, x, y, z = line.split() 
			self.labels.append(atom) 
			geom.append([float(x), float(y), float(z)])
		self.geom = np.array(geom)	
		#print("Atoms: " + str(self.labels)+ "\n")
		#Reading in the masses and charges of the atoms from the .xyz file
		
		for x in self.labels:
			self.masses.append(get_mass(x))
			self.charges.append(get_charge(x))
		y = 0
		for x in self.labels:
			#print("Mass of " + x + " is: " + str(self.masses[y]))
			#print("Charge of " + x + " is: " + str(self.charges[y]))
			y += 1
		#print("\n")
		#print("Molecular Geometry in: " + self.units + "\n")
		#print(self.geom)

		return self.geom, self.natom, self.labels	
Example #11
0
 def __init__(self, TextFile):
     # Empty arrays defined to be later appended to
     self.textfile = TextFile
     labels = []
     geom = []
     charges = []
     mass = []
     # open text file, read in the values, and store them as the desired units
     with open(TextFile, 'r') as my_file:
         data = my_file.read().replace('\n', ' ')
         data = data.split()
         self.natom = int(data[0])
         del data[0]
         self.units = data[0]
         del data[0]
         # reading in rest of the data
         for i in range(self.natom):
             # Store the first line of the column as a label
             labels.append(data[4 * i])
             # Temporary list defined to store subarray of geom
             temp = []
             # Cycle through the x,y,z coordinates
             for j in range(3):
                 temp.append(float(data[4 * i + j + 1]))
             # Append 1x3 subarray to geom array
             geom.append(temp)
         self.labels = labels
         self.geom = np.array(geom)
         for i in range(self.natom):
             mass.append(masses.get_mass(str(labels[i])))
             charges.append(masses.get_charge(str(labels[i])))
         self.charges = charges
         self.masses = mass
Example #12
0
	def __init__(self,inputString,lengthUnits="Angstrom",angleUnits="Degree"):

		self.inputString = inputString
		self.lengthUnits = lengthUnits
		self.angleUnits  = angleUnits

		self.read(inputString)

		self.masses  = [ float(get_mass(i)) for i in self.atoms ]
		self.charges = [ int(get_charge(i)) for i in self.atoms ]
Example #13
0
def nuclear_attraction_matrix(sto3g_data, labels, geom):
    """Compute the nuclear attraction matrix."""
    number_ao = len(sto3g_data)
    V = np.zeros((number_ao, number_ao))
    for label, geom in zip(labels, geom):
        Z = masses.get_charge(label)
        V_temp = np.zeros((number_ao, number_ao))
        for index in np.ndindex(V.shape):
            orbitals = [sto3g_data[i] for i in index]
            n_attract = functools.partial(attraction_term, Z, geom.tolist()[0])
            gaussian_recursion(orbitals, [], n_attract, V_temp, index)

        V += V_temp

    return V
Example #14
0
def nuclear_attraction_matrix(sto3g_data, labels, geom):
    """Compute the nuclear attraction matrix."""
    number_ao = len(sto3g_data)
    V = np.zeros((number_ao, number_ao))
    for label, geom in zip(labels, geom):
        Z = masses.get_charge(label)
        V_temp = np.zeros((number_ao, number_ao))
        for index in np.ndindex(V.shape):
            orbitals = [sto3g_data[i] for i in index]
            n_attract = functools.partial(attraction_term, Z, geom.tolist()[0])
            gaussian_recursion(orbitals, [], n_attract, V_temp, index)

        V += V_temp
        
    return V
Example #15
0
 def __init__(self, geom_str):
     lines=geom_str.splitlines()                             # splitting lines of input file
     self.natom = int(lines[0])                              # number of atoms in the input
     self.units = lines[1]                                   # units of geometry
     self.labels = []                                        # atoms in the input file
     self.mass = []                                          # mass of each atom
     self.charge = []                                        # charge of each atom
     self.geom = []                                          # geometry of molecule in xyz coordinates
     for line in lines[2:]:
         atom,x,y,z = line.split()
         self.labels.append(str(atom))
         self.mass.append(float(masses.get_mass(atom)))
         self.charge.append(int(masses.get_charge(atom)))
         self.geom.append([float(x),float(y),float(z)])
     self.geom = np.array(self.geom)                         # matrix of xyz coordinates
Example #16
0
 def __init__(self, geom_str):
     lines = geom_str.splitlines()  # splitting lines of input file
     self.natom = int(lines[0])  # number of atoms in the input
     self.units = lines[1]  # units of geometry
     self.labels = []  # atoms in the input file
     self.mass = []  # mass of each atom
     self.charge = []  # charge of each atom
     self.geom = []  # geometry of molecule in xyz coordinates
     for line in lines[2:]:
         atom, x, y, z = line.split()
         self.labels.append(str(atom))
         self.mass.append(float(masses.get_mass(atom)))
         self.charge.append(int(masses.get_charge(atom)))
         self.geom.append([float(x), float(y), float(z)])
     self.geom = np.array(self.geom)  # matrix of xyz coordinates
Example #17
0
 def __init__(self, xyzstring, units="angstrom"):
   labels = []
   geom   = []
   try:
     lines  = xyzstring.strip().splitlines()
     natom  = int(lines[0])
     for line in lines[2:]:
       l, x, y, z = line.split()
       labels.append(l.upper())
       geom.append([float(x), float(y), float(z)])
   except:
     raise Exception("Invalid .xyz string\n'''\n{:s}\n'''\npassed to Molecule constructor.".format(xyzstring))
   self.units   = units
   self.natom   = natom    
   self.labels  = labels
   self.masses  = [get_mass(label)   for label in labels]
   self.charges = [get_charge(label) for label in labels]
   self.geom    = np.array(geom)
Example #18
0
 def __init__(self, geom_path):
     f = open(geom_path)
     lines = f.readlines()
     f.close()
     self.natom = int(lines[0])
     self.units = lines[1]
     # initialize stuff
     self.labels = []
     self.charges = []
     self.masses = []
     self.xyz = []
     # get geoms
     for line in lines[2:]:
         atom, x, y, z = line.split()
         self.labels.append(atom)
         self.charges.append(get_charge(atom))
         self.masses.append(get_mass(atom))
         self.xyz.append((float(x), float(y), float(z)))
     self.geom = np.array(self.xyz)                            # make numpy array
Example #19
0
def generate_sto3g_data(atoms, geom):
    """Create the sto3g_data."""
    sto3g_data = []
    for atom, geom in zip(atoms, geom):
        for subshell, coefficient in zip(subshells[atom], coefficient_tuple):
            atom_index = masses.get_charge(atom) - 1
            for orbital in subshell_to_orbitals(subshell):
                # A full function will be needed for this if I extend into d
                # block elements.
                subshell_index = int(orbital[0]) - 1
                sto3g_data.append({
                    "a": exponential_tuple[atom_index][subshell_index],
                    "d": coefficient,
                    "r": geom.tolist()[0],
                    "l": 1 if orbital == "2px" else 0,
                    "m": 1 if orbital == "2py" else 0,
                    "n": 1 if orbital == "2pz" else 0,
                })
    return sto3g_data
Example #20
0
	def parse_molecule(self, mole_str):
		"""
		Parses data from .xyz file to change class attributes
		:param mole_str: string (typically .xyz file) describing a molecule
		"""
		lines = mole_str.strip().split("\n")
		self.natom = int(lines[0])
		if lines[1].lower() == "angstrom":
			self.units = "angstrom"
		elif lines[1].lower() == "bohr":
			self.units = "bohr" 
		self.labels = [i.strip().split(" ")[0].strip() for i in lines[2:]]
		self.masses =  [m.get_mass( l ) for l in self.labels ]
		self.charges = [m.get_charge( l ) for l in self.labels ]
		tempArray = [i.split("   ")[1:4] for i in lines[2:]]
		for a in range(len(tempArray)):
			for b in range(len(tempArray[a])):
				tempArray[a][b] = float(tempArray[a][b]
)
		self.geom = np.array(tempArray)
Example #21
0
 def __init__(self, xyz):
     self.units = "Angstrom"
     self.labels = []
     self.masses = []
     self.charges = []
     xyz_lines = filename_to_lines(xyz)
     # Get the number of atoms.
     natom = get_elt_0(xyz_lines, "Line 1", "file {}".format(xyz))
     self.natom = validate_int(natom, "Line 1")
     # Validate the file length.
     validate_array_length(self.natom + 2, xyz_lines, "XYZ input", "lines")
     geom = numpy.empty([0, 3])
     for i, line in enumerate(xyz_lines[2:]):
         # Ensure a coordinate line is valid before processing it.
         atom, matr_row = validate_coord_line(line, i + 3)
         geom = numpy.vstack((geom, matr_row))
         self.labels.append(atom)
         self.charges.append(masses.get_charge(atom))
         self.masses.append(masses.get_mass(atom))
     self.geom = geom
Example #22
0
 def __init__(self, xyz):
         self.units = "Angstrom"
         self.labels = []
         self.masses = []
         self.charges = []
         xyz_lines = filename_to_lines(xyz)
         # Get the number of atoms.
         natom = get_elt_0(xyz_lines, "Line 1", "file {}".format(xyz)) 
         self.natom = validate_int(natom, "Line 1")
         # Validate the file length.
         validate_array_length(self.natom + 2, xyz_lines, "XYZ input", "lines")
         geom = numpy.empty([0, 3])
         for i, line in enumerate(xyz_lines[2:]):
             # Ensure a coordinate line is valid before processing it.
             atom, matr_row = validate_coord_line(line, i + 3)
             geom = numpy.vstack((geom, matr_row))
             self.labels.append(atom)
             self.charges.append(masses.get_charge(atom))
             self.masses.append(masses.get_mass(atom))
         self.geom = geom
Example #23
0
	def parse_molecule(self, mole_str):
		"""
		Parses data from .xyz file to change class attributes
		:param mole_str: string (typically .xyz file) describing a molecule
		"""
		lines = mole_str.strip().split("\n")
		self.natom = int(lines[0])
		if lines[1].lower() == "angstrom":
			self.units = "angstrom"
		elif lines[1].lower() == "bohr":
			self.units = "bohr" 
		self.labels = [i.strip().split(" ")[0].strip() for i in lines[2:]]
		self.masses =  [m.get_mass( l ) for l in self.labels ]
		self.charges = [m.get_charge( l ) for l in self.labels ]
		self.molecular_charge = 0
		tempArray = [i.split("   ")[1:4] for i in lines[2:]]
		for a in range(len(tempArray)):
			for b in range(len(tempArray[a])):
				tempArray[a][b] = float(tempArray[a][b]
)
		self.geom = np.array(tempArray)
Example #24
0
 def __init__(
     self, xyz_file
 ):  #Initializes member variables: natom, units, labels, masses, charges, geom
     with open(xyz_file) as f:
         geom = [line.split() for line in f]
     try:  #Tests formatting of .xyz file
         self.natom = int(geom.pop(0)[0])  #Gets number of atoms
         units = geom.pop(0)  #Gets units of coordinates
         for i in units:
             if isinstance(i, str) == True:
                 i = str(i)
                 if i.upper() == "BOHR" or i.upper() == "ANGSTROM":
                     self.units = i
     except:
         sys.exit(
             "Error: Check .xyz file to ensure correct format. \n Number of Atoms \n Unit of Length \n Atom with Coordinates \n . \n . \n ."
         )
     self.labels = []
     self.masses = []
     self.charges = []
     for i in geom:  #Loops over the labels with coordinates of the file
         a = i.pop(0)
         self.labels.append(a)  #Builds list of labels
         try:
             self.masses.append(
                 masses.get_mass(a))  #Builds list of atomic masses
             self.charges.append(
                 masses.get_charge(a))  #Builds list of atom charges
         except:
             sys.exit("Error: Check that labels are written correctly.")
     try:
         geom = [list(map(float, j)) for j in geom]
         self.geom = np.array(
             geom)  #Makes array out of list of lists containing coordinates
     except:
         sys.exit(
             "Error: Check if coordinates are in numerical format with x, y, and z components."
         )
     f.close()
Example #25
0
    def __init__(self, xyzfile):
        with open(xyzfile, "r") as f:
            lines = f.readlines()  #opening the xyz file for reading
        self.xyz = xyzfile

        self.natom = int(lines[0])  #first line = num of atoms

        if len(lines) != (self.natom + 2):
            print("Error: incorrectly formatted xyz file")
            return

        self.units = lines[1].rstrip()  #second line = Angstroms or Bohr
        if self.units != "Angstrom" and self.units != "Bohr":
            print(
                "Error: unspecified units or units we are currently unequipped to handle."
            )
            return

        self.labels = []
        for line in lines[2:]:  #from the third line to the end
            self.labels = self.labels + [line[0]]  #append the first character

        self.masses = [masses.get_mass(i)
                       for i in self.labels]  #creates a list of the masses

        self.charges = [masses.get_charge(i)
                        for i in self.labels]  #creates a list of the charges

        fgeoms = []
        for line in lines[2:]:  #from the third line to the end
            line = line.split()
            newline = line[1:]  #leave out the atom name, have list of xyz's
            for i in range(len(newline)):
                newline[i] = float(newline[i])  #converting to float
            fgeoms = fgeoms + [newline]  #a list of lists of the xyz values
        self.geoms = np.array(
            fgeoms)  #making an array out of the list of lists
Example #26
0
 def __init__(self,
              filename='molecule.xyz',
              units='Angstrom',
              charge=0,
              mult=1):
     self.units = units
     self.labels = []
     self.charges = []
     self.masses = []
     self.geom_list = []
     self.index = 0
     self.charge = charge
     self.mult = mult
     with open(filename, 'r') as fn:
         self.natom = int(fn.readline())
         geom_lines = fn.readlines()[1:]
         for line in geom_lines:
             line_list = line.split()
             self.labels.append(line_list[0].upper())
             self.charges.append(masses.get_charge(line_list[0]))
             self.masses.append(masses.get_mass(line_list[0]))
             self.geom_list.append(
                 [line_list[1], line_list[2], line_list[3]])
     self.geom = np.array(self.geom_list).astype(float)
Example #27
0
 def __init__(self,geom_str,units = "Angstrom"):
 
     self.read(geom_str)
     self.units = units
     self.charge = [get_charge(i) for i in self.label]
     self.mass   = [get_mass(i)   for i in self.label]
Example #28
0
    def __init__(self, xyz_file, units="Angstrom"):

        self.units = units
        self.read(xyz_file)
        self.masses = [ float(get_mass(i)) for i in self.atoms ]
        self.charges = [ int(get_charge(i)) for i in self.atoms ]
Example #29
0
    def __init__(self, geom_str, units="Angstrom"):

        self.read(geom_str)
        self.units = units
        self.charge = [get_charge(i) for i in self.label]
        self.mass = [get_mass(i) for i in self.label]
Example #30
0
    def __init__(self, xyz_file, units="Angstrom"):

        self.units = units
        self.read(xyz_file)
        self.masses = [ float(get_mass(i)) for i in self.atoms ]
        self.charges = [ int(get_charge(i)) for i in self.atoms ]
Example #31
0
 def __init__(self, geom, units = "Angstrom"):
     self.read(geom)
     self.units = units
     self.charge = [get_charge(atom) for atom in self.atoms]
     self.mass = [get_mass(atom) for atom in self.atoms]
Example #32
0
 def __init__(self, geom, units="Angstrom"):
     self.read(geom)
     self.units = units
     self.charge = [get_charge(atom) for atom in self.atoms]
     self.mass = [get_mass(atom) for atom in self.atoms]