Beispiel #1
0
    def run(self, verbose=0, single_recipe=0, single_ingred=0):
        """Run the MAST monitor.
        """
        if (single_ingred == 0) and ("dagman" in dirutil.get_mast_platform()):
            return None #Do not auto-run from __init__ method for CHTC/DAGMan
        curdir = os.getcwd()
        try:
            os.chdir(self.scratch)    
        except:
            os.chdir(curdir)
            errorstr = "Could not change directories to MAST_SCRATCH at %s" % self.scratch
            raise MASTError(self.__class__.__name__, errorstr)
        
        #dirutil.lock_directory(self.scratch, 1) # Wait 5 seconds
        #Directory is now locked by mast initially, but gets
        #unlocked at the end of the mastmon run.
        if single_ingred == 0: 
            recipe_dirs = dirutil.walkdirs(self.scratch,1,1)
        else:
            recipe_dirs = list()
            recipe_dirs.append(single_recipe)

        if verbose == 1:
            self.logger.info("================================")
            self.logger.info("Recipe directories:")
            for recipe_dir in recipe_dirs:
                self.logger.info(recipe_dir)
            self.logger.info("================================")

        for recipe_dir in recipe_dirs:
            self.check_recipe_dir(recipe_dir, verbose, single_ingred)
                
        dirutil.unlock_directory(self.scratch) #unlock directory
        os.chdir(curdir)
Beispiel #2
0
    def run(self, verbose=0, single_recipe=0, single_ingred=0):
        """Run the MAST monitor.
        """
        if (single_ingred == 0) and ("dagman" in dirutil.get_mast_platform()):
            return None  #Do not auto-run from __init__ method for CHTC/DAGMan
        curdir = os.getcwd()
        try:
            os.chdir(self.scratch)
        except:
            os.chdir(curdir)
            errorstr = "Could not change directories to MAST_SCRATCH at %s" % self.scratch
            raise MASTError(self.__class__.__name__, errorstr)

        #dirutil.lock_directory(self.scratch, 1) # Wait 5 seconds
        #Directory is now locked by mast initially, but gets
        #unlocked at the end of the mastmon run.
        if single_ingred == 0:
            recipe_dirs = dirutil.walkdirs(self.scratch, 1, 1)
        else:
            recipe_dirs = list()
            recipe_dirs.append(single_recipe)

        if verbose == 1:
            self.logger.info("================================")
            self.logger.info("Recipe directories:")
            for recipe_dir in recipe_dirs:
                self.logger.info(recipe_dir)
            self.logger.info("================================")

        for recipe_dir in recipe_dirs:
            self.check_recipe_dir(recipe_dir, verbose, single_ingred)

        dirutil.unlock_directory(self.scratch)  #unlock directory
        os.chdir(curdir)
Beispiel #3
0
 def copy_a_file(self, childpath, pfname, cfname):
     """Copy a parent file to an arbitrary name in the child folder.
         Args:
             childpath <str>: path to child ingredient
             pfname <str>: file name in parent folder (e.g. "CONTCAR")
             cfname <str>: file name for child folder (e.g. "POSCAR")
     """
     parentpath = self.keywords['name']
     dirutil.lock_directory(childpath)
     self.logger.info("Attempting copy of %s/%s into %s/%s" %
                      (parentpath, pfname, childpath, cfname))
     if os.path.isfile("%s/%s" % (parentpath, pfname)):
         if not os.path.isfile("%s/%s" % (childpath, cfname)):
             shutil.copy("%s/%s" % (parentpath, pfname),
                         "%s/%s" % (childpath, cfname))
         else:
             self.logger.warning(
                 "%s already exists in %s. Parent file %s not copied from %s into child %s."
                 % (cfname, childpath, pfname, parentpath, cfname))
     else:
         raise MASTError(
             self.__class__.__name__,
             "No file in parent path %s named %s. Cannot copy into child path as %s."
             % (parentpath, pfname, cfname))
     dirutil.unlock_directory(childpath)
Beispiel #4
0
    def run(self, verbose=0):
        """Run the MAST monitor.
        """
        curdir = os.getcwd()
        try:
            os.chdir(self.scratch)    
        except:
            os.chdir(curdir)
            errorstr = "Could not change directories to MAST_SCRATCH at %s" % self.scratch
            raise MASTError(self.__class__.__name__, errorstr)
        
        #dirutil.lock_directory(self.scratch, 1) # Wait 5 seconds
        #Directory is now locked by mast initially, but gets
        #unlocked at the end of the mastmon run.
        
        recipe_dirs = dirutil.walkdirs(self.scratch,1,1)
        if verbose == 1:
            self.logger.info("================================")
            self.logger.info("Recipe directories:")
            for recipe_dir in recipe_dirs:
                self.logger.info(recipe_dir)
            self.logger.info("================================")

        for recipe_dir in recipe_dirs:
            self.check_recipe_dir(recipe_dir, verbose)
                
        dirutil.unlock_directory(self.scratch) #unlock directory
        os.chdir(curdir)
Beispiel #5
0
 def softlink_a_file(self, childpath, filename):
     """Softlink a parent file to a matching name in the child folder.
         Args:
             childpath <str>: path to child ingredient
             filename <str>: file name (e.g. "CHGCAR")
     """
     parentpath = self.keywords['name']
     dirutil.lock_directory(childpath)
     import subprocess
     #print "cwd: ", os.getcwd()
     #print parentpath
     #print childpath
     if os.path.isfile("%s/%s" % (parentpath, filename)):
         if not os.path.isfile("%s/%s" % (childpath, filename)):
             curpath = os.getcwd()
             os.chdir(childpath)
             mylink = subprocess.Popen("ln -s %s/%s %s" %
                                       (parentpath, filename, filename),
                                       shell=True)
             mylink.wait()
             os.chdir(curpath)
         else:
             self.logger.warning(
                 "%s already exists in %s. Parent %s not softlinked." %
                 (filename, childpath, filename))
     else:
         raise MASTError(
             self.__class__.__name__,
             "No file in parent path %s named %s. Cannot create softlink." %
             (parentpath, filename))
     dirutil.unlock_directory(childpath)
Beispiel #6
0
    def _vasp_potcar_setup(self, my_poscar):
        """Set up the POTCAR file."""
        name = self.keywords['name']

        if 'mast_xc' in self.keywords['program_keys'].keys():
            myxc = self.keywords['program_keys']['mast_xc'].upper() #Uppercase
        else:
            raise MASTError("vasp_checker, _vasp_potcar_setup","Exchange correlation functional needs to be specified in ingredients keyword mast_xc")

        if ('mast_pp_setup' in self.keywords['program_keys'].keys()):
            sites = my_poscar.site_symbols
            setup = self.keywords['program_keys']['mast_pp_setup']
            pp_sites = list()
            for site in sites:
                try:
                    pp_sites.append(setup[site])
                except KeyError:
                    pp_sites.append(site)
            my_potcar = Potcar(symbols=pp_sites, functional=myxc, sym_potcar_map=None)
        else:
            my_potcar = Potcar(symbols=my_poscar.site_symbols, functional=myxc, sym_potcar_map=None)

        dirutil.lock_directory(name)
        my_potcar.write_file(name + "/POTCAR")
        dirutil.unlock_directory(name)
        return my_potcar
Beispiel #7
0
 def _vasp_poscar_setup(self):
     """Set up the POSCAR file for a single VASP run.
     """
     name = self.keywords['name']
     pospath = os.path.join(name, "POSCAR")
     if os.path.isfile(pospath):
         my_poscar = Poscar.from_file(pospath) 
         #parent should have given a structure
     else: #this is an originating run; mast should give it a structure
         if self.keywords['structure'] is not None:
             my_poscar = Poscar(self.keywords['structure'])
         else:
             pf = os.path.join(os.path.dirname(name),'POSCAR_%s'%os.path.basename(name))
             if os.path.isfile(pf):
                 my_poscar = Poscar.from_file(pf)
         workdir=os.path.dirname(name)
         sdir=os.path.join(workdir,"structure_index_files")
         if os.path.exists(sdir):
             mystr=my_poscar.structure
             manname="manifest___"
             myatomindex=AtomIndex(structure_index_directory=sdir)
             newstr=myatomindex.graft_new_coordinates_from_manifest(mystr, manname, "")
             self.logger.info("Getting original coordinates from manifest.")
             new_pos=Poscar(newstr)
             my_poscar=new_pos
         self.logger.info("No POSCAR found from a parent; base structure used for %s" % self.keywords['name'])
     if 'mast_coordinates' in self.keywords['program_keys'].keys():
         sxtend = StructureExtensions(struc_work1=my_poscar.structure, name=self.keywords['name'])
         coordstrucs=self.get_coordinates_only_structure_from_input()
         newstruc = sxtend.graft_coordinates_onto_structure(coordstrucs[0])
         my_poscar.structure=newstruc.copy()
     dirutil.lock_directory(name)
     my_poscar.write_file(pospath)
     dirutil.unlock_directory(name)
     return my_poscar
Beispiel #8
0
    def _vasp_kpoints_setup(self):
        """Parse mast_kpoints string, which should take the format:
            number, number, number designation
            examples: "3x3x3 M", "1x1x1 G". If no designation is given,
            Monkhorst-Pack is assumed.
        """
        name = self.keywords['name']
        tryname = os.path.join(name, "KPOINTS")
        if os.path.isfile(tryname):
            #KPOINTS already exists. Do not overwrite.
            my_kpoints = Kpoints.from_file(tryname)
            return my_kpoints
        if not (self.metafile.read_data('kpoints')==None):
            kpoints = self.metafile.read_data('kpoints').split()
            kmesh = (int(kpoints[0].split('x')[0]),int(kpoints[0].split('x')[1]),int(kpoints[0].split('x')[2]))
            try: desig = kpoints[1].upper()
            except IndexError: desig = 'M'
            try: kshift = (float(kpoints[2]),float(kpoints[3]),float(kpoints[4]))
            except IndexError: kshift = (0.0,0.0,0.0)
        else:
            if 'mast_kpoints' in self.keywords['program_keys'].keys():
                kpoints = self.keywords['program_keys']['mast_kpoints']
            else:
                raise MASTError(self.__class__.__name__,"k-point instructions need to be set either in ingredients keyword mast_kpoints or scaling section in structure ingredient: No k-point settings for the ingredient %s"% name)
            if len(kpoints) == 3:
                desig = "M"
            elif 'line' in str(kpoints[1]):
                desig = 'L'
            else:
                desig = kpoints[3].upper()
            if not desig == 'L':
                kmesh = (int(kpoints[0]),int(kpoints[1]),int(kpoints[2]))
                kshift = (0,0,0)
        if desig == "M":
            my_kpoints = Kpoints.monkhorst_automatic(kpts=kmesh,shift=kshift)
        elif desig == "G":
            my_kpoints = Kpoints.gamma_automatic(kpts=kmesh,shift=kshift)
        elif desig == 'L':
            my_kpoints='Line Mode\n'+'\n'.join(' '.join(kpoints).split(','))+'\n'
            fp=open(name+'/KPOINTS','w')
            fp.write(my_kpoints)
        else:
            raise MASTError(self.__class__.__name__,"kpoint designation " + desig + " not recognized.")

        dirutil.lock_directory(name)
        if not desig=='L':
            my_kpoints.write_file(name + "/KPOINTS")
        dirutil.unlock_directory(name)
        return my_kpoints
Beispiel #9
0
 def to_file(self, file_path):
     """Writes data to a file (overwrites existing file)."""
     #TTM+2 10/7/11 add error checking in case of no path
     if (file_path == "") or (file_path == None):
         raise MASTError(self.__class__.__name__,
                         "Refusing to copy to empty path.")
     if self.data == []:
         raise MASTError(self.__class__.__name__,
                         "Empty file not copied to " + file_path)
     dirutil.lock_directory(os.path.dirname(file_path))
     writef = open(file_path, 'wb')
     for line in self.data:
         writef.write(line)
     writef.close()
     dirutil.unlock_directory(os.path.dirname(file_path))
Beispiel #10
0
 def to_file(self,file_path):
     """Writes data to a file (overwrites existing file)."""
     #TTM+2 10/7/11 add error checking in case of no path
     if (file_path == "") or (file_path == None):
         raise MASTError(self.__class__.__name__,
             "Refusing to copy to empty path.")
     if self.data == []:
         raise MASTError(self.__class__.__name__,
             "Empty file not copied to " + file_path)
     dirutil.lock_directory(os.path.dirname(file_path))
     writef = open(file_path,'wb')
     for line in self.data:
         writef.write(line)
     writef.close()
     dirutil.unlock_directory(os.path.dirname(file_path))
Beispiel #11
0
 def _vasp_incar_setup(self, my_potcar, my_poscar):
     """Set up the INCAR, including MAGMOM string, ENCUT, and NELECT."""
     name=self.keywords['name']
     myd = dict()
     myd = self._vasp_incar_get_non_mast_keywords()
     try:
         myd.pop("IMAGES")
     except KeyError:
         pass
     if 'mast_multiplyencut' in self.keywords['program_keys'].keys():
         mymult = float(self.keywords['program_keys']['mast_multiplyencut'])
     else:
         mymult = 1.5
     if 'ENCUT' in myd.keys():
         pass
     else:
         myd['ENCUT']=self._get_max_enmax_from_potcar(my_potcar)*mymult
     if 'mast_setmagmom' in self.keywords['program_keys'].keys():
         magstr = str(self.keywords['program_keys']['mast_setmagmom'])
         magmomstr=""
         maglist = magstr.split()
         numatoms = sum(my_poscar.natoms)
         if len(maglist) < numatoms:
             magct=0
             while magct < len(maglist):
                 magmomstr = magmomstr + str(my_poscar.natoms[magct]) + "*" + maglist[magct] + " " 
                 magct = magct + 1
         else:
             magmomstr = magstr
         myd['MAGMOM']=magmomstr
     if 'mast_charge' in self.keywords['program_keys'].keys():
         myelectrons = self.get_total_electrons(my_poscar, my_potcar)
         newelectrons=0.0
         try:
             adjustment = float(self.keywords['program_keys']['mast_charge'])
         except (ValueError, TypeError):
             raise MASTError("vasp_checker, vasp_incar_setup","Could not parse adjustment")
         #newelectrons = myelectrons + adjustment
         newelectrons = myelectrons - adjustment
         myd['NELECT']=str(newelectrons)
     if self.metafile.read_data('nbands'):
         myd['NBANDS']=self.metafile.read_data('nbands')
     my_incar = Incar(myd)
     dirutil.lock_directory(name)
     my_incar.write_file(name + "/INCAR")
     dirutil.unlock_directory(name)
     return my_incar
Beispiel #12
0
 def set_up_neb_folders(self, image_structures):
     """Set up NEB folders.
         Args:
            image_structures <list of Structure>: List
                of image structures
     """
     imct = 0
     myname = self.keywords['name']
     if 'mast_coordinates' in self.keywords['program_keys'].keys():
         coordstrucs = self.get_coordinates_only_structure_from_input()
         newstrucs = list()
         sidx = 0  #ex. coordstrucs 0, 1, 2 for 3 images
         while sidx < self.keywords['program_keys']['mast_neb_settings'][
                 'images']:
             sxtend = StructureExtensions(
                 struc_work1=image_structures[sidx + 1].copy(),
                 name=self.keywords['name'])
             newstrucs.append(
                 sxtend.graft_coordinates_onto_structure(coordstrucs[sidx]))
             sidx = sidx + 1
     while imct < len(image_structures):
         imposcar = Poscar(image_structures[imct])
         num_str = str(imct).zfill(2)
         impath = os.path.join(myname, num_str)
         impospath = os.path.join(myname, "POSCAR_" + num_str)
         if 'mast_coordinates' in self.keywords['program_keys'].keys():
             if imct == 0:  #skip endpoint
                 pass
             elif imct == len(image_structures) - 1:  #skip other endpt
                 pass
             else:
                 imposcar.structure = newstrucs[imct - 1].copy()
         dirutil.lock_directory(myname)
         self.write_poscar_with_zero_velocities(imposcar, impospath)
         dirutil.unlock_directory(myname)
         try:
             os.makedirs(impath)
         except OSError:
             self.logger.warning("Directory at %s already exists." % impath)
             return None
         dirutil.lock_directory(impath)
         self.write_poscar_with_zero_velocities(
             imposcar, os.path.join(impath, "POSCAR"))
         dirutil.unlock_directory(impath)
         imct = imct + 1
     return
Beispiel #13
0
 def add_selective_dynamics_to_structure_file(self, sdarray):
     """Add selective dynamics to a structure file.
         In the case of VASP, the structure file is 
         POSCAR-like
         Args:
             sdarray <numpy array of bool>: Numpy array of
                 booleans for T F F etc.
     """
     name = self.keywords['name']
     pname = os.path.join(name,"POSCAR")
     phposcar = Poscar.from_file(pname)
     phposcar.selective_dynamics = sdarray
     dirutil.lock_directory(name)
     os.rename(pname, pname + "_no_sd")
     phposcar.write_file(pname)
     dirutil.unlock_directory(name)
     return
Beispiel #14
0
 def copy_a_file(self, childpath, pfname, cfname):
     """Copy a parent file to an arbitrary name in the child folder.
         Args:
             childpath <str>: path to child ingredient
             pfname <str>: file name in parent folder (e.g. "CONTCAR")
             cfname <str>: file name for child folder (e.g. "POSCAR")
     """
     parentpath = self.keywords['name']
     dirutil.lock_directory(childpath)
     self.logger.info("Attempting copy of %s/%s into %s/%s" % (parentpath, pfname, childpath, cfname))
     if os.path.isfile("%s/%s" % (parentpath, pfname)):
         if not os.path.isfile("%s/%s" % (childpath, cfname)):
             shutil.copy("%s/%s" % (parentpath, pfname),"%s/%s" % (childpath, cfname))
         else:
             self.logger.warning("%s already exists in %s. Parent file %s not copied from %s into child %s." % (cfname,childpath,pfname,parentpath,cfname))
     else:
         raise MASTError(self.__class__.__name__,"No file in parent path %s named %s. Cannot copy into child path as %s." % (parentpath, pfname, cfname))
     dirutil.unlock_directory(childpath)
Beispiel #15
0
 def set_up_neb_folders(self, image_structures):
     """Set up NEB folders.
         Args:
            image_structures <list of Structure>: List
                of image structures
     """
     imct=0
     myname = self.keywords['name']
     if 'mast_coordinates' in self.keywords['program_keys'].keys():
         coordstrucs=self.get_coordinates_only_structure_from_input()
         newstrucs=list()
         sidx = 0 #ex. coordstrucs 0, 1, 2 for 3 images
         while sidx < self.keywords['program_keys']['mast_neb_settings']['images']:
             sxtend = StructureExtensions(struc_work1=image_structures[sidx+1].copy(), name=self.keywords['name'])
             newstrucs.append(sxtend.graft_coordinates_onto_structure(coordstrucs[sidx]))
             sidx = sidx + 1
     while imct < len(image_structures):
         imposcar = Poscar(image_structures[imct])
         num_str = str(imct).zfill(2)
         impath = os.path.join(myname, num_str)
         impospath = os.path.join(myname, "POSCAR_" + num_str)
         if 'mast_coordinates' in self.keywords['program_keys'].keys():
             if imct == 0: #skip endpoint
                 pass 
             elif imct == len(image_structures)-1: #skip other endpt
                 pass
             else:
                 imposcar.structure=newstrucs[imct-1].copy()
         dirutil.lock_directory(myname)
         imposcar.write_file(impospath)
         dirutil.unlock_directory(myname)
         try:
             os.makedirs(impath)
         except OSError:
             self.logger.warning("Directory at %s already exists." % impath)
             return None
         dirutil.lock_directory(impath)
         imposcar.write_file(os.path.join(impath, "POSCAR"))
         dirutil.unlock_directory(impath)
         imct = imct + 1
     return
Beispiel #16
0
 def forward_extra_restart_files(self, childpath):
     """Forward extra restart files: 
         For VASP, this entails a softlink to WAVECAR and 
         CHGCAR.
         Args:
             childpath <str>: path to child ingredient
     """
     raise MASTError(self.__class__.__name__,"This function is obsolete. Use softlink_charge_density_file, softlink_wavefunction_file, forward_charge_density_file, and/or forward_wavefunction_file")
     parentpath = self.keywords['name']
     dirutil.lock_directory(childpath)
     import subprocess
     #print "cwd: ", os.getcwd()
     curpath = os.getcwd()
     os.chdir(childpath)
     #print parentpath
     #print childpath
     mylink=subprocess.Popen("ln -s %s/WAVECAR WAVECAR" % parentpath, shell=True)
     mylink.wait()
     mylink2=subprocess.Popen("ln -s %s/CHGCAR CHGCAR" % parentpath, shell=True)
     mylink2.wait()
     os.chdir(curpath)
     dirutil.unlock_directory(childpath)
Beispiel #17
0
 def _phon_poscar_setup(self):
     """Set up a PHON POSCAR file. Strip out the "elements" line (that is,
         use VASP version 4 format. Also strip out anything beneath the atoms
         line.
     """
     name = self.keywords['name']
     pospath = os.path.join(name, "POSCAR")
     prepath = os.path.join(name, "POSCAR_prePHON")
     if os.path.isfile(pospath): #Already done. Return.
         return
     my_poscar = Poscar.from_file(prepath) 
     my_poscar.selective_dynamics=None #unset SD if it is set
     my_poscar.velocities=None #unset velocities
     dirutil.lock_directory(name)
     my_poscar.write_file(pospath)
     dirutil.unlock_directory(name)
     #pick up a copy and strip out the elements line.
     mypfile = MASTFile(pospath)
     myline6=mypfile.get_line_number(6)
     if myline6.strip().split()[0].isalpha:
         mypfile.modify_file_by_line_number(6,"D")
     mypfile.to_file(pospath)
     return
Beispiel #18
0
 def _phon_poscar_setup(self):
     """Set up a PHON POSCAR file. Strip out the "elements" line (that is,
         use VASP version 4 format. Also strip out anything beneath the atoms
         line.
     """
     name = self.keywords["name"]
     pospath = os.path.join(name, "POSCAR")
     prepath = os.path.join(name, "POSCAR_prePHON")
     if os.path.isfile(pospath):  # Already done. Return.
         return
     my_poscar = Poscar.from_file(prepath)
     my_poscar.selective_dynamics = None  # unset SD if it is set
     my_poscar.velocities = None  # unset velocities
     dirutil.lock_directory(name)
     my_poscar.write_file(pospath)
     dirutil.unlock_directory(name)
     # pick up a copy and strip out the elements line.
     mypfile = MASTFile(pospath)
     myline6 = mypfile.get_line_number(6)
     if myline6.strip().split()[0].isalpha:
         mypfile.modify_file_by_line_number(6, "D")
     mypfile.to_file(pospath)
     return
Beispiel #19
0
 def softlink_a_file(self, childpath, filename):
     """Softlink a parent file to a matching name in the child folder.
         Args:
             childpath <str>: path to child ingredient
             filename <str>: file name (e.g. "CHGCAR")
     """
     parentpath = self.keywords['name']
     dirutil.lock_directory(childpath)
     import subprocess
     #print "cwd: ", os.getcwd()
     #print parentpath
     #print childpath
     if os.path.isfile("%s/%s" % (parentpath, filename)):
         if not os.path.isfile("%s/%s" % (childpath, filename)):
             curpath = os.getcwd()
             os.chdir(childpath)
             mylink=subprocess.Popen("ln -s %s/%s %s" % (parentpath,filename,filename), shell=True)
             mylink.wait()
             os.chdir(curpath)
         else:
             self.logger.warning("%s already exists in %s. Parent %s not softlinked." % (filename,childpath,filename))
     else:
         raise MASTError(self.__class__.__name__,"No file in parent path %s named %s. Cannot create softlink." % (parentpath, filename))
     dirutil.unlock_directory(childpath)
Beispiel #20
0
 def unlock_directory(self):
     return dirutil.unlock_directory(self.keywords['name'])
Beispiel #21
0
 def unlock_directory(self):
     return dirutil.unlock_directory(self.keywords['name'])