Beispiel #1
0
	def __init__(self, file_path=None, elements_list=None, basenames_list=None, calculation_type='lda_paw', minimal_form=None):

		super(Potcar, self).__init__(file_path)

		if file_path:
			if self.get_lines_containing_string("PAW_PBE"): #be careful if potcars different than used to in future
				self.calculation_type = 'gga_paw_pbe'
			else:
				self.calculation_type = 'lda_paw'

		if minimal_form:
			calculation_type = minimal_form['calculation_type']
			basenames_list = minimal_form['basenames']

		if elements_list or basenames_list:
			self.calculation_type = calculation_type

			element_mapping_file = File(Potcar.element_mapping_path)
			element_mapping_string = str(element_mapping_file)
			potcar_dict = json.loads(element_mapping_string)

			base_path = potcar_dict[calculation_type]['path']

			if elements_list:
				potcar_paths = [Path.clean(base_path, potcar_dict[calculation_type][element], 'POTCAR') for element in elements_list]
			elif basenames_list:
				potcar_paths = [Path.clean(base_path, basename, 'POTCAR') for basename in basenames_list]

			concatenated_file = File()
			for path in potcar_paths:
				concatenated_file = concatenated_file + File(path)

			self.lines = concatenated_file.lines
Beispiel #2
0
    def test_write_to_path(self):
        file_path = Path.clean(self.data_path, 'small_file.txt')
        file = File(file_path)

        file[0] += " for line 0"
        file[3] = "line 3"
        file += ""
        file += "here\nand here"
        file += ""

        self.assertEqual(file.lines, [
            'Small file for line 0', '  Very small  ', '', 'line 3', '',
            'here', 'and here', ''
        ])

        file.write_to_path(
            Path.clean(self.data_path, 'small_file_ammended.txt'))

        file_2 = File(Path.clean(self.data_path, 'small_file_ammended.txt'))

        file_2[2] = "no more"
        file_2.write_to_path()

        file_3 = File(Path.clean(self.data_path, 'small_file_ammended.txt'))

        self.assertEqual(file_3.lines, [
            'Small file for line 0', '  Very small  ', 'no more', 'line 3', '',
            'here', 'and here', ''
        ])
Beispiel #3
0
    def test_add(self):
        file_path = Path.clean(self.data_path, 'small_file.txt')
        file = File(file_path)
        add_str = "string to add"
        right_full_str = file + add_str
        self.assertEqual(right_full_str,
                         "Small file\n  Very small  \n\nstring to add")

        l_add_str = "  left string to add"
        left_full_str = l_add_str + file

        self.assertEqual(left_full_str,
                         "  left string to addSmall file\n  Very small  \n\n")

        file_path_1 = Path.clean(self.data_path, 'small_file.txt')
        file_path_2 = Path.clean(self.data_path, 'small_file_2.txt')
        first_file = File(file_path_1)
        second_file = File(file_path_2)

        final_file = first_file + second_file

        self.assertEqual(final_file.lines, [
            'Small file', '  Very small  ', '', '', 'Small file 2',
            '  Not as small  ', ''
        ])
Beispiel #4
0
    def test_init(self):
        with self.assertRaises(IOError):
            file = File(Path.clean(self.data_path, 'file.txt'))

        file = File()
        self.assertEqual(file.lines, [])
        self.assertEqual(file.load_path, None)

        with self.assertRaises(IOError):
            file.write_to_path()

        file_path = Path.clean(self.data_path, 'file1.txt')
        file = File(file_path)
        self.assertEqual(file.lines[0], "This is a test file")
        self.assertEqual(file.lines[4], "line 5")
        self.assertEqual(file.lines[6], "end of testing file")
        with self.assertRaises(IndexError):
            file.lines[7]

        self.assertEqual(file.load_path, file_path)

        file_path = Path.clean(self.data_path, 'small_file.txt')
        file = File(file_path)
        self.assertEqual(file.lines, ['Small file', '  Very small  ', ''])

        file_path = Path.clean(self.data_path, 'empty.txt')
        file = File(file_path)
        self.assertEqual(file.lines, [])

        file_path = Path.clean(self.data_path, 'almost_empty.txt')
        file = File(file_path)  #this file contains: line 1: '\n' line 2: ''
        self.assertEqual(file.lines, [''])
    def test_init(self):
        file_path = Path.clean(self.data_path, "kpt_1")

        kpoints = Kpoints(file_path)

        self.assertEqual(kpoints.scheme, 'Gamma')

        kpoints.scheme = "monkhorst"

        self.assertEqual(kpoints.scheme, 'Monkhorst')

        self.assertEqual(kpoints.subdivisions_list, [4, 2, 4])

        kpoints.subdivisions_list = [6, 6, 8]

        self.assertEqual(kpoints.subdivisions_list, [6, 6, 8])

        new_path = Path.clean(self.data_path, "new_kpt_1")
        kpoints.write_to_path(new_path)

        kpoints_2 = Kpoints(new_path)

        self.assertEqual(kpoints_2.subdivisions_list, [6, 6, 8])
        self.assertEqual(kpoints.scheme, 'Monkhorst')

        with self.assertRaises(Exception):
            kpoints_2.scheme = "Lonkhorst"

        with self.assertRaises(Exception):
            kpoints_2.subdivisions_list = ['2', '4', '5', '6']

        kpoints_3 = Kpoints(scheme_string="Gamma", subdivisions_list=[4, 6, 8])
        self.assertEqual(str(kpoints_3),
                         'Kpoints File\n0\nGamma\n4 6 8\n0 0 0\n')
Beispiel #6
0
    def test_str(self):
        file = File(Path.clean(self.data_path, 'small_file.txt'))
        self.assertEqual(str(file), "Small file\n  Very small  \n\n")

        file = File(Path.clean(self.data_path, 'empty.txt'))
        self.assertEqual(str(file), "")

        file = File(Path.clean(
            self.data_path,
            'almost_empty.txt'))  #this file contains: line 1: '\n' line 2: ''
        self.assertEqual(str(file), "\n")
    def test_init(self):
        file_path = Path.clean(self.data_path, "poscar_small")
        poscar = Poscar(file_path)

        self.assertEqual(poscar.species_list, ['Si', 'O'])
        self.assertEqual(poscar.lines, [
            'Poscar', '1.0', '5.0 0.2 0.1', '0.4\t 6.0   0.7',
            '-0.2   0.0  7.7    ', 'Si   O', '2  1', 'Direct',
            '0.11 0.22 0.33', '0.33 0.22 0.11', '0.22 0.33 0.11  '
        ])
        self.assertEqual(poscar.species_count_list, [2, 1])
        self.assertEqual(poscar.coordinate_mode, 'Direct')
        self.assertEqual(
            poscar.coordinates,
            [[0.11, 0.22, 0.33], [0.33, 0.22, 0.11], [0.22, 0.33, 0.11]])

        lattice = [[2.2, 2.3, 2.1], [1.2, 3.3, 0.0], [-1.2, -2.2, 4.4]]
        species_list = ['K', 'V', 'O']
        species_count_list = [1, 2, 3]
        coordinate_mode = 'cart'
        coordinates = [[0.2, 0.3, 0.4], [0.5, 0.5, 0.1], [-0.01, 0.1, 0.01],
                       [2.33, 6.5, 3.2], [0.0, 0.1, -0.1], [0.1, 0.5, 0.5]]
        poscar = Poscar(None, lattice, species_list, species_count_list,
                        coordinate_mode, coordinates)

        self.assertEqual(poscar.species_list, ['K', 'V', 'O'])
        self.assertEqual(poscar.lines, [
            'Poscar', '1.0', '2.2 2.3 2.1', '1.2 3.3 0.0', '-1.2 -2.2 4.4',
            'K V O', '1 2 3', 'Cartesian', '0.2 0.3 0.4', '0.5 0.5 0.1',
            '-0.01 0.1 0.01', '2.33 6.5 3.2', '0.0 0.1 -0.1', '0.1 0.5 0.5'
        ])
        self.assertEqual(poscar.species_count_list, [1, 2, 3])
        self.assertEqual(poscar.coordinate_mode, 'Cartesian')
        self.assertEqual(poscar.coordinates, coordinates)
def npar_converger(base_path, structure, npar_list, base_kpoints_scheme,
                   base_kpoints_subdivisions_list, base_ediff, base_encut,
                   node_count):
    """Takes in a structure, set of npars, and base params and runs set in base_path"""
    encut_convergence_set_path = Path.clean(base_path)
    Path.make(encut_convergence_set_path)

    for npar in npar_list:
        run_path = Path.join(encut_convergence_set_path, str(npar))

        input_dictionary = {
            'external_relaxation_count': 0,
            'kpoint_schemes_list': [base_kpoints_scheme],
            'kpoint_subdivisions_lists': [base_kpoints_subdivisions_list],
            'submission_script_modification_keys_list': ['100'],
            'submission_node_count_list': [node_count],
            'ediff': [base_ediff],
            'encut': [base_encut],
            'npar': [npar]
        }

        vasp_relaxation = VaspRelaxation(run_path,
                                         structure,
                                         input_dictionary,
                                         verbose=False)

        if vasp_relaxation.update():
            print "npar:", npar, "node_count:", node_count, round(
                vasp_relaxation.get_final_energy(True),
                5), round(vasp_relaxation.total_time, 2)
        else:
            pass
Beispiel #9
0
	def write_input_files_to_path(self):
		"""
		Simply write files to path
		"""

		if self.initial_structure:
			self.initial_structure.to_poscar_file_path(Path.clean(self.path, 'POSCAR'))
		elif not Path.exists(self.contcar_path):
			raise Exception("Neither an initial structure nor an existing contcar path have been provided. Nowhere to get the structure.")
		else:
			Path.copy(self.contcar_path, self.get_extended_path('POSCAR'))

		for file_path in [self.chargecar_path, self.wavecar_path]:
			if Path.exists(file_path):
				Path.copy(file_path, self.path)

		self.initial_incar.write_to_path(Path.join(self.path, 'INCAR'))

		if self.initial_kpoints: 
			self.initial_kpoints.write_to_path(Path.join(self.path, 'KPOINTS'))
		elif 'kspacing' not in self.incar:
			raise Exception("If no kpoints is provided, must have kspacing parameter in incar set")
			
		self.initial_potcar.write_to_path(Path.join(self.path, 'POTCAR'))
		self.submission_script_file.write_to_path(Path.join(self.path, 'submit.sh'))
	def test_loaded(self):
		file_path = Path.clean(self.data_path, "incar_1")
		incar = Incar(file_path)

		self.assertEqual(incar.lines, ['', 'Comment here #messy messy', 'ALGO = Fast #stuff here', 'whats up', '', '', 'EDIFF = 0.00075', 'ENCUT = 520', 'IBRION = 2', 'ICHARG = 1', 'ISIF = 3', 'ISMEAR = -5', 'ISPIN = 2', 'LORBIT = 11 #comment with equals sign', '', '', '', 'LREAL = Auto', 'LWAVE = False', 'MAGMOM = 15*0.6', 'NELM = 100', 'NSW = 99', 'PREC = Accurate', '', '#lonely sigma with equals signequalsequals!', '', 'X = y #equalsequals', 'f   #equals', 'SIGMA = 0.05'])
		self.assertEqual(incar.dict.items(), [('ALGO', 'Fast'), ('EDIFF', '0.00075'), ('ENCUT', '520'), ('IBRION', '2'), ('ICHARG', '1'), ('ISIF', '3'), ('ISMEAR', '-5'), ('ISPIN', '2'), ('LORBIT', '11'), ('LREAL', 'Auto'), ('LWAVE', 'False'), ('MAGMOM', '15*0.6'), ('NELM', '100'), ('NSW', '99'), ('PREC', 'Accurate'), ('X', 'y'), ('SIGMA', '0.05')])

		
    def test_init(self):
        site = Site()
        site['position'] = [0.1, 0.2, 0.4, "dir"]
        site['type'] = 'Ba'
        site_2 = Site()
        site_2['position'] = [0.6, 0.22, 0.44, "cart"]
        site_2['type'] = 'Ti'

        structure = Structure(lattice=Lattice(a=[3.4, 0.1, 0.2],
                                              b=[2.3, 5.0, 0.0],
                                              c=[0.0, 0.0, 1.0]),
                              sites=SiteCollection([site, site_2]))

        self.assertEqual(structure.lattice.to_array(),
                         [[3.4, 0.1, 0.2], [2.3, 5.0, 0.0], [0.0, 0.0, 1.0]])
        self.assertEqual(structure.sites.get_sorted_list()[0]['type'], 'Ba')
        self.assertEqual(structure.sites.get_coordinates_list(),
                         [[0.1, 0.2, 0.4], [0.6, 0.22, 0.44]])

        file_path = Path.clean(self.data_path, "poscar_small")
        structure = Structure(file_path)

        self.assertEqual(structure.lattice.to_array(),
                         [[5.0, 0.2, 0.1], [0.4, 6.0, 0.7], [-0.2, 0.0, 7.7]])
        self.assertEqual(
            structure.sites.get_sorted_list()[1]['coordinate_mode'], 'Direct')
        self.assertEqual(
            structure.get_coordinates_list(),
            [[0.11, 0.22, 0.33], [0.33, 0.22, 0.11], [0.22, 0.33, 0.11]])

        write_file_path = Path.clean(self.data_path, "poscar_small_rewritten")
        structure.to_poscar_file_path(write_file_path)

        structure = Structure(write_file_path)

        self.assertEqual(structure.lattice.to_array(),
                         [[5.0, 0.2, 0.1], [0.4, 6.0, 0.7], [-0.2, 0.0, 7.7]])
        self.assertEqual(
            structure.sites.get_sorted_list()[1]['coordinate_mode'], 'Direct')
        self.assertEqual(
            structure.get_coordinates_list(),
            [[0.11, 0.22, 0.33], [0.33, 0.22, 0.11], [0.22, 0.33, 0.11]])
Beispiel #12
0
def get_structure_list(path):
    """loads in poscars at path and returns list of structures"""

    path = Path.clean(path)
    files = Path.get_list_of_files_at_path(path)
    structs = {}
    
    for file in files:
        structs[file] = Structure(Path.join(path, file))

    return structs
Beispiel #13
0
	def write_input_files_to_path(self, structure, incar, kpoints, potcar, submission_script_file, wavecar_path, chargecar_path):
		"""
		Simply write files to path
		"""

		structure.to_poscar_file_path(Path.clean(self.path, 'POSCAR'))
		incar.write_to_path(Path.clean(self.path, 'INCAR'))
		if kpoints: 
			kpoints.write_to_path(Path.clean(self.path, 'KPOINTS'))
		elif 'kspacing' not in incar:
			raise Exception("If no kpoints is provided, must have kspacing parameter in incar set")
			
		potcar.write_to_path(Path.clean(self.path, 'POTCAR'))
		submission_script_file.write_to_path(Path.clean(self.path, 'submit.sh'))

		if wavecar_path and Path.exists(wavecar_path):
			Path.copy(wavecar_path, self.get_extended_path('WAVECAR'))

		if chargecar_path and Path.exists(chargecar_path):
			Path.copy(chargecar_path, self.get_extended_path('CHARGECAR'))
    def get_submission_file():
        if QueueAdapter.host in ['Fenrir', 'Asathor']:
            return File(Path.clean("/home/angsten/.submit.sh"))

        elif QueueAdapter.host == 'Tom_hp':
            file = File()
            file[0] = 'fake submit script'
            file[1] = 'nodes = 3'
            return file
        elif QueueAdapter.host == 'Savio':
            return File('/global/home/users/angsten/submit.sh')
    def test_conversion(self):
        file_path = Path.clean(self.data_path, "big_posc")

        structure = Structure(file_path)
        structure_2 = Structure(file_path)

        structure_2.convert_sites_to_cartesian_coordinates()
        structure_2.convert_sites_to_direct_coordinates()
        print structure

        for i in range(len(structure.sites)):
            for j in range(3):
                self.assertTrue(
                    structure.sites[i]['position'][j] -
                    structure_2.sites[i]['position'][j] < 0.00000000001)
Beispiel #16
0
	def __init__(self, path, initial_structure=None, incar=None, kpoints=None, potcar=None, submission_script_file=None, contcar_path=None, wavecar_path=None, chargecar_path=None):
		"""
		"""

		if initial_structure and contcar_path:
			raise Exception("Both an initial initial_structure and a contcar path is given. Only one is allowed.")

		self.path = Path.clean(path)
		self.initial_structure = initial_structure
		self.initial_incar = incar
		self.initial_kpoints = kpoints
		self.initial_potcar = potcar
		self.submission_script_file = submission_script_file
		self.contcar_path = contcar_path
		self.wavecar_path = wavecar_path
		self.chargecar_path = chargecar_path
Beispiel #17
0
	def __init__(self, path, structure=None, incar=None, kpoints=None, potcar=None, submission_script_file=None, input_set=None, wavecar_path=None, chargecar_path=None):
		"""
		Cases for __init__:
		1. path does not exist or is empty => make the directory, enforce input file arguments all exists, write out input files to directory
		2. path exists and is not empty
			1. path/.job_id does not exist
				1. path has all 5 input files written to it already => do nothing if not all five input parameters exist, else overwrite current input files to directory
				2. path does not have all 5 input files (has some subset or none) => enforce input file arguments all exists, write out input files to directory
			2. path/.job_id exists => do nothing

		"""

		self.path = Path.clean(path)

		if input_set:
			structure = input_set.structure
			incar = input_set.incar
			kpoints = input_set.kpoints
			potcar = input_set.potcar
			submission_script_file = input_set.submission_script_file

		all_essential_input_parameters_exist = not bool(filter(lambda x: x == None, [structure, incar, potcar, submission_script_file]))

		if not Path.exists(self.path) or Path.is_empty(self.path):
			if not all_essential_input_parameters_exist:
				raise Exception("All five vasp input files must be input for run to be initialized.")
			else:
				Path.make(self.path)

				self.write_input_files_to_path(structure, incar, kpoints, potcar, submission_script_file, wavecar_path, chargecar_path) 
		else:
			if self.job_id_string:
				pass
			else:

				if self.all_input_files_are_present(): #all input files are written to directory
					if all_essential_input_parameters_exist: #overwrite what's there
						self.write_input_files_to_path(structure, incar, kpoints, potcar, submission_script_file, wavecar_path, chargecar_path)
					else:

						pass #do nothing - don't have the necessary inputs to start a run
				else: #not all input files currently exist - must have necessary input params to overwrite
					if not all_essential_input_parameters_exist:
						raise Exception("All five vasp input files must be input for run with incomplete inputs at path to be initialized.")
					else:
						self.write_input_files_to_path(structure, incar, kpoints, potcar, submission_script_file, wavecar_path)
Beispiel #18
0
def encut_converger(base_path, structure, encut_list, base_kpoints_scheme, base_kpoints_subdivisions_list, base_ediff):
    """Takes in a structure, set of encuts, and base params and runs set in base_path""" 
    encut_convergence_set_path = Path.clean(base_path)
    Path.make(encut_convergence_set_path)
    
    for encut in encut_list:
        run_path = Path.join(encut_convergence_set_path, str(encut))
        
        kpoints = Kpoints(scheme_string=base_kpoints_scheme, subdivisions_list=base_kpoints_subdivisions_list)
        incar = IncarMaker.get_static_incar({'ediff':base_ediff, 'encut':encut})
        input_set = VaspInputSet(structure, kpoints, incar)
        
        vasp_run = VaspRun(run_path, input_set=input_set, verbose=False)
        
        if vasp_run.update():
            print encut, round(vasp_run.outcar.energy_per_atom, 5), round(vasp_run.outcar.get_calculation_time_in_core_hours(), 2)
        else:
            pass
class Test(TestCase):

    class_title = 'Kpoints'
    data_dir_path = Path.clean(os.path.dirname(__file__),
                               'data_' + class_title)

    def setUp(self):
        self.data_path = Path.clean(self.__class__.data_dir_path)

    def test_init(self):
        file_path = Path.clean(self.data_path, "kpt_1")

        kpoints = Kpoints(file_path)

        self.assertEqual(kpoints.scheme, 'Gamma')

        kpoints.scheme = "monkhorst"

        self.assertEqual(kpoints.scheme, 'Monkhorst')

        self.assertEqual(kpoints.subdivisions_list, [4, 2, 4])

        kpoints.subdivisions_list = [6, 6, 8]

        self.assertEqual(kpoints.subdivisions_list, [6, 6, 8])

        new_path = Path.clean(self.data_path, "new_kpt_1")
        kpoints.write_to_path(new_path)

        kpoints_2 = Kpoints(new_path)

        self.assertEqual(kpoints_2.subdivisions_list, [6, 6, 8])
        self.assertEqual(kpoints.scheme, 'Monkhorst')

        with self.assertRaises(Exception):
            kpoints_2.scheme = "Lonkhorst"

        with self.assertRaises(Exception):
            kpoints_2.subdivisions_list = ['2', '4', '5', '6']

        kpoints_3 = Kpoints(scheme_string="Gamma", subdivisions_list=[4, 6, 8])
        self.assertEqual(str(kpoints_3),
                         'Kpoints File\n0\nGamma\n4 6 8\n0 0 0\n')
class Test(TestCase):

    class_title = 'Potcar'
    data_dir_path = Path.clean(os.path.dirname(__file__),
                               'data_' + class_title)

    def setUp(self):
        self.data_path = Path.clean(self.__class__.data_dir_path)

    def test_init(self):
        potcar = Potcar(elements_list=['Ba'])

        self.assertEqual(potcar.get_titles(), ['PAW Ba_sv 17Apr2000'])
        self.assertEqual(potcar.get_elements_list(), ['Ba'])

        potcar_2 = Potcar(elements_list=['O', 'Ti', 'Ba'])
        self.assertEqual(
            potcar_2.get_titles(),
            ['PAW O 22Mar2012', 'PAW Ti_sv 26Sep2005', 'PAW Ba_sv 17Apr2000'])
        self.assertEqual(potcar_2.get_elements_list(), ['O', 'Ti', 'Ba'])
Beispiel #21
0
def kpoints_converger(base_path, structure, kpoints_lists, base_kpoints_scheme, base_encut, base_ediff, incar_modification_dictionary=None):
    convergence_set_path = Path.clean(base_path)
    Path.make(convergence_set_path)

    for kpoints_list in kpoints_lists:
        run_path = Path.join(convergence_set_path, "_".join(str(kpoints) for kpoints in kpoints_list))

        kpoints = Kpoints(scheme_string=base_kpoints_scheme, subdivisions_list=kpoints_list)
        incar_mod = {'ediff':base_ediff, 'encut':base_encut}
        
        if incar_modification_dictionary:
            for key, value in incar_modification_dictionary.items():
                incar_mod[key] = value
                
        incar = IncarMaker.get_static_incar(incar_mod)
        
        input_set = VaspInputSet(structure, kpoints, incar)

        vasp_run = VaspRun(run_path, input_set=input_set, verbose=False)

        if vasp_run.update():
            print "_".join(str(kpoints) for kpoints in kpoints_list), round(vasp_run.outcar.energy_per_atom, 5), round(vasp_run.outcar.get_calculation_time_in_core_hours(), 2)
        else:
            vasp_run.view(['kpoints','_job_output.txt'])
Beispiel #22
0
	def outcar(self):
		outcar_path = Path.clean(self.path, 'OUTCAR')
		if Path.exists(outcar_path):
			return Outcar(outcar_path)
		else:
			return None
Beispiel #23
0
	def potcar(self):
		potcar_path = Path.clean(self.path, 'POTCAR')
		if Path.exists(potcar_path):
			return Potcar(potcar_path)
		else:
			return None
Beispiel #24
0
	def kpoints(self):
		kpoints_path = Path.clean(self.path, 'KPOINTS')
		if Path.exists(kpoints_path):
			return Kpoints(kpoints_path)
		else:
			return None
Beispiel #25
0
	def incar(self):
		incar_path = Path.clean(self.path, 'INCAR')
		if Path.exists(incar_path):
			return Incar(incar_path)
		else:
			return None
Beispiel #26
0
class Test(TestCase):

    class_title = 'File'
    data_dir_path = Path.clean(os.path.dirname(__file__),
                               'data_' + class_title)

    def setUp(self):
        self.data_path = Path.clean(self.__class__.data_dir_path)

    def test_init(self):
        with self.assertRaises(IOError):
            file = File(Path.clean(self.data_path, 'file.txt'))

        file = File()
        self.assertEqual(file.lines, [])
        self.assertEqual(file.load_path, None)

        with self.assertRaises(IOError):
            file.write_to_path()

        file_path = Path.clean(self.data_path, 'file1.txt')
        file = File(file_path)
        self.assertEqual(file.lines[0], "This is a test file")
        self.assertEqual(file.lines[4], "line 5")
        self.assertEqual(file.lines[6], "end of testing file")
        with self.assertRaises(IndexError):
            file.lines[7]

        self.assertEqual(file.load_path, file_path)

        file_path = Path.clean(self.data_path, 'small_file.txt')
        file = File(file_path)
        self.assertEqual(file.lines, ['Small file', '  Very small  ', ''])

        file_path = Path.clean(self.data_path, 'empty.txt')
        file = File(file_path)
        self.assertEqual(file.lines, [])

        file_path = Path.clean(self.data_path, 'almost_empty.txt')
        file = File(file_path)  #this file contains: line 1: '\n' line 2: ''
        self.assertEqual(file.lines, [''])

    def test_str(self):
        file = File(Path.clean(self.data_path, 'small_file.txt'))
        self.assertEqual(str(file), "Small file\n  Very small  \n\n")

        file = File(Path.clean(self.data_path, 'empty.txt'))
        self.assertEqual(str(file), "")

        file = File(Path.clean(
            self.data_path,
            'almost_empty.txt'))  #this file contains: line 1: '\n' line 2: ''
        self.assertEqual(str(file), "\n")

    def test_add(self):
        file_path = Path.clean(self.data_path, 'small_file.txt')
        file = File(file_path)
        add_str = "string to add"
        right_full_str = file + add_str
        self.assertEqual(right_full_str,
                         "Small file\n  Very small  \n\nstring to add")

        l_add_str = "  left string to add"
        left_full_str = l_add_str + file

        self.assertEqual(left_full_str,
                         "  left string to addSmall file\n  Very small  \n\n")

        file_path_1 = Path.clean(self.data_path, 'small_file.txt')
        file_path_2 = Path.clean(self.data_path, 'small_file_2.txt')
        first_file = File(file_path_1)
        second_file = File(file_path_2)

        final_file = first_file + second_file

        self.assertEqual(final_file.lines, [
            'Small file', '  Very small  ', '', '', 'Small file 2',
            '  Not as small  ', ''
        ])

    def test_overrides(self):
        file = File()
        self.assertFalse(file)
        file[2] = '  inserted line   '
        self.assertEqual(file.lines, ['', '', '  inserted line   '])
        file[1] = 'add this line\n and this one where index 1 was'
        self.assertEqual(file.lines, [
            '', 'add this line', ' and this one where index 1 was',
            '  inserted line   '
        ])
        file[1] = 'replaced add this line'
        self.assertEqual(file.lines, [
            '', 'replaced add this line', ' and this one where index 1 was',
            '  inserted line   '
        ])
        self.assertEqual(
            file.lines[1:3],
            ['replaced add this line', ' and this one where index 1 was'])
        del file[1]
        del file[0:2]
        self.assertEqual(file.lines, ['  inserted line   '])

        self.assertFalse("home is where the heart is" in file)
        self.assertTrue("line" in file)

        file += "new line added"
        self.assertEqual(file.lines, ['  inserted line   ', 'new line added'])

        file.insert(0, 'inserted at beginning')
        file.insert(2, 'right before new line added line')

        self.assertEqual(file.lines, [
            'inserted at beginning', '  inserted line   ',
            'right before new line added line', 'new line added'
        ])

        self.assertTrue(file)

        self.assertEqual(len(file), 4)

        l = [
            'inserted at beginning', '  inserted line   ',
            'right before new line added line', 'new line added'
        ]

        for x, item in enumerate(file):
            self.assertEqual(item, l[x])

    def test_write_to_path(self):
        file_path = Path.clean(self.data_path, 'small_file.txt')
        file = File(file_path)

        file[0] += " for line 0"
        file[3] = "line 3"
        file += ""
        file += "here\nand here"
        file += ""

        self.assertEqual(file.lines, [
            'Small file for line 0', '  Very small  ', '', 'line 3', '',
            'here', 'and here', ''
        ])

        file.write_to_path(
            Path.clean(self.data_path, 'small_file_ammended.txt'))

        file_2 = File(Path.clean(self.data_path, 'small_file_ammended.txt'))

        file_2[2] = "no more"
        file_2.write_to_path()

        file_3 = File(Path.clean(self.data_path, 'small_file_ammended.txt'))

        self.assertEqual(file_3.lines, [
            'Small file for line 0', '  Very small  ', 'no more', 'line 3', '',
            'here', 'and here', ''
        ])
Beispiel #27
0
    def __init__(self, vasp_calculation_input_dictionary):

        vasp_calculation_input_dictionary = copy.deepcopy(
            vasp_calculation_input_dictionary)

        vasp_calculation_input_dictionary = {
            k.lower(): v
            for k, v in vasp_calculation_input_dictionary.items()
        }  #enforce all keys lowercase

        path = Path.clean(vasp_calculation_input_dictionary.pop('path'))

        information_structure = None  #used for number of nodes and potcar
        if isinstance(vasp_calculation_input_dictionary['structure'],
                      Structure):
            initial_structure = vasp_calculation_input_dictionary.pop(
                'structure')
            information_structure = initial_structure
            contcar_path = None
        else:
            initial_structure = None
            contcar_path = vasp_calculation_input_dictionary.pop('structure')
            information_structure = Structure(contcar_path)

        wavecar_path = vasp_calculation_input_dictionary.pop(
            'wavecar_path'
        ) if 'wavecar_path' in vasp_calculation_input_dictionary else None
        chargecar_path = vasp_calculation_input_dictionary.pop(
            'chargecar_path'
        ) if 'chargecar_path' in vasp_calculation_input_dictionary else None
        incar_template = vasp_calculation_input_dictionary.pop(
            'incar_template'
        ) if 'incar_template' in vasp_calculation_input_dictionary else None
        kpoints_scheme = vasp_calculation_input_dictionary.pop(
            'kpoints_scheme'
        ) if 'kpoints_scheme' in vasp_calculation_input_dictionary else None
        kpoints_list = [
            int(x) for x in vasp_calculation_input_dictionary.pop(
                'kpoints_list').split(' ')
        ] if ('kpoints_list' in vasp_calculation_input_dictionary
              and vasp_calculation_input_dictionary['kpoints_list'] != None
              ) else None
        potcar_type = vasp_calculation_input_dictionary.pop(
            'potcar_type'
        ) if 'potcar_type' in vasp_calculation_input_dictionary else 'lda_paw'
        vasp_code_type = vasp_calculation_input_dictionary.pop(
            'vasp_code_type'
        ) if 'vasp_code_type' in vasp_calculation_input_dictionary else 'standard'
        node_count = vasp_calculation_input_dictionary.pop(
            'node_count'
        ) if 'node_count' in vasp_calculation_input_dictionary else None
        use_mp_hubbard_u = vasp_calculation_input_dictionary.pop(
            'use_mp_hubbard_u'
        ) if 'use_mp_hubbard_u' in vasp_calculation_input_dictionary else None

        for file_path in [wavecar_path, chargecar_path]:
            if file_path != None and not Path.exists(file_path):
                print "Warning: Path " + str(
                    file_path) + " specified does not exist. Not using."
                #raise Exception("Path " + str(file_path) + " specified does not exist.")

        if kpoints_scheme != None and kpoints_list != None:
            kpoints = Kpoints(scheme_string=kpoints_scheme,
                              subdivisions_list=kpoints_list)

            if 'kspacing' in vasp_calculation_input_dictionary:
                raise Exception(
                    "kpoints are being specified by more than one method.")
        elif 'kspacing' not in vasp_calculation_input_dictionary:
            raise Exception(
                "If kpoints aren't explicitly defined through a scheme and a list, the kspacing tag must be present in the incar."
            )
        else:
            kpoints = None

        potcar = Potcar(elements_list=information_structure.get_species_list(),
                        calculation_type=potcar_type)

        submission_script_file = QueueAdapter.get_submission_file()

        if os.environ['QUEUE_ADAPTER_HOST'] != 'Savio':
            if node_count == None:
                submission_script_file = QueueAdapter.modify_number_of_cores_from_num_atoms(
                    submission_script_file, information_structure.site_count)
            else:
                submission_script_file = QueueAdapter.set_number_of_nodes(
                    submission_script_file, node_count)

            submission_script_file = QueueAdapter.modify_submission_script(
                submission_script_file, modification_key=vasp_code_type)

        incar_modifiers = vasp_calculation_input_dictionary  #whatever is left should only be incar modifiers - we popped all other keys

        for key, value in incar_modifiers.items(
        ):  #make sure there are no None values - these should not be put in INCAR
            if value in [None, 'None']:
                del incar_modifiers[key]

        if 'encut' in incar_modifiers and (
                0.1 < incar_modifiers['encut']) and (
                    incar_modifiers['encut'] <
                    10.0):  #Should use this as a multiplier times enmax
            enmax = potcar.get_enmax()

            incar_modifiers['encut'] = int(incar_modifiers['encut'] * enmax)

        if incar_template == 'static':
            incar = IncarMaker.get_static_incar(
                custom_parameters_dictionary=incar_modifiers)
        elif incar_template == 'external_relaxation':
            incar = IncarMaker.get_external_relaxation_incar(
                custom_parameters_dictionary=incar_modifiers)
        elif incar_template != None:
            raise Exception("Incar template " + str(incar_template) +
                            " not valid")
        else:
            incar = Incar()
            incar.modify_from_dictionary(incar_modifiers)

        if 'lreal' not in incar:
            if information_structure.site_count > 20:
                incar['lreal'] = 'Auto'
            else:
                incar['lreal'] = False

        if 'npar' not in incar:
            if os.environ['QUEUE_ADAPTER_HOST'] == 'Savio':
                incar['npar'] = 4
            else:
                incar['npar'] = QueueAdapter.get_optimal_npar(
                    submission_script_file)
        elif incar['npar'] in ['Remove', 'remove']:
            del incar['npar']

        ###################TEMPORARILY HARDCODED FOR PEROVSKITES##########################################
        if use_mp_hubbard_u:
            u_species = initial_structure.get_species_list()[1]
            mp_hubbard_u_values = {
                'Co': 3.32,
                'Cr': 3.7,
                'Fe': 5.3,
                'Mn': 3.9,
                'Mo': 4.38,
                'Ni': 6.2,
                'V': 3.25,
                'W': 6.2
            }

            if u_species in mp_hubbard_u_values.keys():

                u_value = mp_hubbard_u_values[u_species]

                incar['LDAU'] = True
                incar['LDAUJ'] = '0 0 0'
                incar['LDAUL'] = '0 2 0'
                incar['LDAUPRINT'] = 1
                incar['LDAUTYPE'] = 2
                incar['LDAUU'] = '0 ' + str(u_value) + ' 0'
                incar['LMAXMIX'] = 4
                incar['LORBIT'] = 11

        super(VaspCalculationGenerator,
              self).__init__(path=path,
                             initial_structure=initial_structure,
                             incar=incar,
                             kpoints=kpoints,
                             potcar=potcar,
                             submission_script_file=submission_script_file,
                             contcar_path=contcar_path,
                             wavecar_path=wavecar_path,
                             chargecar_path=chargecar_path)
 def setUp(self):
     self.data_path = Path.clean(self.__class__.data_dir_path)
Beispiel #29
0
class Potcar(File):
	"""
	Can initialize from an existing potcar file (Potcar('./POTCAR'))
	Can initialize from a string of elements and whether or not to use LDA or GGA (Potcar(['Ba','Ti','O'], lda=False))
		In this case, set of predefined potcars will be used
		Assumes lda = True if calculation type is not specified
	Can initialize from a list of basenames which might look like ['Ba_sv', 'Ti_sv', 'O']
	Can initialize from a minimal_form which looks like {'basenames':['Ba_sv', 'Ti_sv', 'O'], 'calculation_type':'lda'}
	"""

	element_mapping_path = Path.clean(os.path.dirname(__file__),'potcar_element_mapping.json')

	def __init__(self, file_path=None, elements_list=None, basenames_list=None, calculation_type='lda_paw', minimal_form=None):

		super(Potcar, self).__init__(file_path)

		if file_path:
			if self.get_lines_containing_string("PAW_PBE"): #be careful if potcars different than used to in future
				self.calculation_type = 'gga_paw_pbe'
			else:
				self.calculation_type = 'lda_paw'

		if minimal_form:
			calculation_type = minimal_form['calculation_type']
			basenames_list = minimal_form['basenames']

		if elements_list or basenames_list:
			self.calculation_type = calculation_type

			element_mapping_file = File(Potcar.element_mapping_path)
			element_mapping_string = str(element_mapping_file)
			potcar_dict = json.loads(element_mapping_string)

			base_path = potcar_dict[calculation_type]['path']

			if elements_list:
				potcar_paths = [Path.clean(base_path, potcar_dict[calculation_type][element], 'POTCAR') for element in elements_list]
			elif basenames_list:
				potcar_paths = [Path.clean(base_path, basename, 'POTCAR') for basename in basenames_list]

			concatenated_file = File()
			for path in potcar_paths:
				concatenated_file = concatenated_file + File(path)

			self.lines = concatenated_file.lines

	def get_titles(self):
		"""Returns list like ['PAW Ba_sv 17Apr2000', 'PAW Ti_sv 26Sep2005', 'PAW O 22Mar2012']"""

		titles_list = self.get_lines_containing_string('TITEL')
		
		return [x.split("= ")[1].rstrip() for x in titles_list]

	def get_elements_list(self):
		"""Returns list like ['Ba', 'Ti', 'O']"""

		return [x.split(" ")[1].split("_")[0] for x in self.get_titles()]

	def get_basenames_list(self):
		"""Returns list like ['Ba_sv', 'Ti_sv', 'O']"""

		return [x.split(" ")[1] for x in self.get_titles()]

	def get_minimal_form(self):
		"""Returns minimal form (a dict like {'basenames':['Ba_sv', 'Ti_sv', 'O'], 'calculation_type':'lda'])"""

		return {'basenames':self.get_basenames_list(), 'calculation_type':self.calculation_type}

	def get_enmax(self):
		"""Returns maximum enmax out of all species' enmax values"""

		enmax_lines_list = self.get_lines_containing_string('ENMAX')

		enmax_values_list = []

		for enmax_line in enmax_lines_list:
			enmax_line = su.remove_extra_spaces(enmax_line)

			enmax_values_list.append(float(enmax_line.split(' = ')[1].split(';')[0]))

		return max(enmax_values_list)
class Test(TestCase):

    class_title = 'Structure'
    data_dir_path = Path.clean(os.path.dirname(__file__),
                               'data_' + class_title)

    def setUp(self):
        self.data_path = Path.clean(self.__class__.data_dir_path)

    def test_init(self):
        site = Site()
        site['position'] = [0.1, 0.2, 0.4, "dir"]
        site['type'] = 'Ba'
        site_2 = Site()
        site_2['position'] = [0.6, 0.22, 0.44, "cart"]
        site_2['type'] = 'Ti'

        structure = Structure(lattice=Lattice(a=[3.4, 0.1, 0.2],
                                              b=[2.3, 5.0, 0.0],
                                              c=[0.0, 0.0, 1.0]),
                              sites=SiteCollection([site, site_2]))

        self.assertEqual(structure.lattice.to_array(),
                         [[3.4, 0.1, 0.2], [2.3, 5.0, 0.0], [0.0, 0.0, 1.0]])
        self.assertEqual(structure.sites.get_sorted_list()[0]['type'], 'Ba')
        self.assertEqual(structure.sites.get_coordinates_list(),
                         [[0.1, 0.2, 0.4], [0.6, 0.22, 0.44]])

        file_path = Path.clean(self.data_path, "poscar_small")
        structure = Structure(file_path)

        self.assertEqual(structure.lattice.to_array(),
                         [[5.0, 0.2, 0.1], [0.4, 6.0, 0.7], [-0.2, 0.0, 7.7]])
        self.assertEqual(
            structure.sites.get_sorted_list()[1]['coordinate_mode'], 'Direct')
        self.assertEqual(
            structure.get_coordinates_list(),
            [[0.11, 0.22, 0.33], [0.33, 0.22, 0.11], [0.22, 0.33, 0.11]])

        write_file_path = Path.clean(self.data_path, "poscar_small_rewritten")
        structure.to_poscar_file_path(write_file_path)

        structure = Structure(write_file_path)

        self.assertEqual(structure.lattice.to_array(),
                         [[5.0, 0.2, 0.1], [0.4, 6.0, 0.7], [-0.2, 0.0, 7.7]])
        self.assertEqual(
            structure.sites.get_sorted_list()[1]['coordinate_mode'], 'Direct')
        self.assertEqual(
            structure.get_coordinates_list(),
            [[0.11, 0.22, 0.33], [0.33, 0.22, 0.11], [0.22, 0.33, 0.11]])

    def test_conversion(self):
        file_path = Path.clean(self.data_path, "big_posc")

        structure = Structure(file_path)
        structure_2 = Structure(file_path)

        structure_2.convert_sites_to_cartesian_coordinates()
        structure_2.convert_sites_to_direct_coordinates()
        print structure

        for i in range(len(structure.sites)):
            for j in range(3):
                self.assertTrue(
                    structure.sites[i]['position'][j] -
                    structure_2.sites[i]['position'][j] < 0.00000000001)