Esempio n. 1
0
    def _checkNameIndex(self, name, index):
        """check the validity of the name and index passed to set/get/remove constraints
        
        name   -- the parameter name
        index -- the index in the parameter list  
      
        raise: RietError if name or index is not right.
        """
        if self.ParamDict.has_key(name):
            if index is not None:
                raise RietError('The parameter "%s" is not a list.' % name)
            return

        if self.ParamListDict.has_key(name):
            if not isinstance(index, int):
                raise RietError(
                    'The parameter list needs an int for index, but "%s"=%s is received.'
                    % (type(index), str(index)))

            return

        # otherwise, there is no key.
        raise RietError(
            "Class %s does not have a  parameter or parameter list: %s" %
            (self.__class__.__name__, name))

        return
Esempio n. 2
0
    def linkConstraint(self):
        """Link all the constraints to the fit object.
        called after duplicate() when a new-object is added to the Fit regime

        refine:  Refine object 
        """
        from diffpy.pyfullprof.fit import Fit
        if isinstance(self, Fit):
            _fit = self
        else:
            _fit = self.getFit()
        if _fit:
            refine = _fit.get("Refine")
        else:
            # Should not happen, this is checked in the "set" function
            # which is the only one calling this function.
            raise RietError("No Fit is created.")

        for constraint in self.constraints.values():
            constraint.refine = refine
            constraint.apply()

        for name in self.ObjectDict.keys():
            o = self.__dict__[name]
            if o:  # it may be None
                o.linkConstraint()

        for name in self.ObjectListDict.keys():
            for o in self.__dict__[name]._list:
                o.linkConstraint()

        return
Esempio n. 3
0
    def adaptPyFullProftoSrRietveld(self,
                                    srtype,
                                    processdir,
                                    weightscheme="standard"):
        """ Change some setting to FullProf from SrRietveld """
        if srtype == "l":
            # Lebail:  set Jbt -> Profile Matching Mode, and Auto-calculate
            # FIXME  In advanced mode, if Fit can capture mult-step refine, Irf=2 in step>1 refine
            for phase in self.get("Phase"):
                phase.set("Jbt", 2)
                self.Jbt = 2
            for contr in self.get("Contribution"):
                contr.set("Irf", 0)

        elif srtype == "r":
            # Rietveld
            for phase in self.get("Phase"):
                phase.set("Jbt", 0)
                self.Jbt = 0
        # END-IF:   if srtype

        for pattern in self.get("Pattern"):
            if weightscheme[0] == "s":
                pattern.set("Iwg", 0)
            elif weightscheme[0] == "u":
                pattern.set("Iwg", 2)
            else:
                errmsg = "Weighting Scheme %-10s Is Not Supported" % (
                    weightscheme)
                raise RietError(errmsg)

        return
Esempio n. 4
0
    def validate(self):
        """
        validating before refinement
        """
        rvalue = BackgroundUserDefined.validate(self)

        if self.size() < 4:
            errmsg = "BackgroundUserDefinedCubic  number of background point = %-5s < 4"% \
                (self.size())
            raise RietError(errmsg)

        return rvalue
Esempio n. 5
0
    def importUncertaintyOutFile(self):
        """
        parse the .out file and put the data information to a database

        Return  :   None
        """
        lineslist = self.readFile(self._outfilename)

        # 1. File Flag Line
        startlinenum = -1
        for lindex in xrange(len(lineslist)):
            if lineslist[lindex].count(self._FLAG2) == 1:
                startlinenum = lindex
                break

        if startlinenum < 0:
            raise RietError()

        # 2. Get Informative Lines:
        infolineslist = []
        for lindex in xrange(startlinenum + 1, len(lineslist)):
            candline = lineslist[lindex]
            # 1. Find stop line
            if candline[0] == "=" and candline[1] == ">":
                break

            # 2. Judge
            if candline.count(self._FLAG3) > 0:
                infolineslist.append(candline)

        # LOOP-OVER: for lindex in xrange( startlinenum+1, len(lineslist) )

        # 3. Parse to standard database
        for line in infolineslist:
            terms = line.split(":")[1].split("+/-")
            tp1 = terms[0].split()
            tp2 = terms[1].split()

            name = tp1[0]
            valstr = tp1[1].split("(")[0]
            val = float(valstr)
            sigstr = tp2[0]
            sig = float(sigstr)

            nameinfotuple = self.parseNameOutFile(name)

            self._ParameterList.append((nameinfotuple, val, sig))

        # LOOP-OVER:  for line in infolineslist

        return
Esempio n. 6
0
    def importUncertainty(self):
        """
        Parse the input file and put the data information to a database

        Return  :   None
        """
        if self._outfilename is not None:
            self.importUncertaintyOutFile()

        elif self._sumfilename is not None:
            self.importUncertaintySumFile()

        else:
            raise RietError()

        return
Esempio n. 7
0
 def getRefineResult(self, fitsummary, srtype, pcrfullname):
     """ get out Refinement results
     """
     import diffpy.pyfullprof.fpoutputfileparsers as FPP
     newfit = fitsummary.getFit()
     if isinstance(newfit, Fit):
         self.updateFit(newfit)
     else:
         #FIXME: should change the refine status and let srr to handle the error
         raise RietError(self.__class__.__name__ + ".refine(): Fit Error!")
     self._readCalculatePattern(pcrfullname)
     # if mode=lebail, import reflections from RFL file
     if srtype == "l":
         patterns = self.get("Pattern")
         numpat = len(patterns)
         if numpat == 1:
             singlepattern = True
         else:
             singlepattern = False
         # b) Phase
         numpha = len(self.get("Phase"))
         # c) Read all reflections
         hklrange = {}
         for patid in range(numpat):
             tempreflects = []
             hklrange["min"] = patterns[patid].get("Thmin")
             hklrange["max"] = patterns[patid].get("Thmax")
             for phaseid in range(numpha):
                 # Only work on phase-pattern related case
                 corecontrib = self.getContribution(
                     self.get("Phase")[phaseid],
                     self.get("Pattern")[patid])
                 if corecontrib is not None:
                     reflectdict = FPP.parseHKLn(
                         pcrfullname,
                         phaseno=phaseid + 1,
                         singlepattern=singlepattern,
                         patno=patid + 1,
                         hklrange=hklrange)
                     tempreflects.append(reflectdict)
                 # END-IF
             # LOOP-OVER
             patterns[patid]._reflections[phaseid] = tempreflects
         # LOOP-OVER
     # turn all constraint refinement off
     #self.fixAll()
     return
Esempio n. 8
0
    def setCalculation(self):
        """
        set this instance to pattern calculation mode

        return  --  None
        """
        thisjob = self.get("Job")

        if thisjob == 0:
            self.set("Job", 2)
        elif thisjob == 1:
            self.set("Job", 3)
        elif thisjob == 2 or thisjob == 3:
            pass
        else:
            errmsg = "Job = %-10s Is Not In Class %-20s Object" % \
                    (self.get("Job"), self.__class__.__name__)
            raise RietError(errmsg)
        # END-IF-ELSE

        return
Esempio n. 9
0
    def duplicate(self):
        """
        duplicate self object to a exact copy
        (1) parameter...(copy)
        (2) subclass... (copy)
        (3) container... (copy)

        For Constraint object, only the pattern_range, phase_range and parname are copied;
        No link to Refine is established!

        scenario    --  After duplicate() and the corresponding linking work by Rietveld.set()
                        method 'RietveldClass.linkConstraint()' is always called

        return  --  the new generated twin object
        """
        try:
            newobject = self.__class__(None)
        except TypeError, err:
            errmsg = "RietveldClass.duplicate():  instantiated as %-20s\n" % (
                self.__class__.__name__)
            errmsg += str(err)
            raise RietError(errmsg)
Esempio n. 10
0
    def getConstraintByPath(self, path):
        """Get a constraint by path
        
        path -- a full path,  e.g., x.y.z[i].a
        return: a constraint object
        """
        if path.count('.') > 0:
            try:
                objpath, paramname = path.rsplit('.', 1)
            except:
                raise RietError('Invalid format for a parameter name: ' + path)

            objects = self.getByPath(objpath)
            if isinstance(objects, list):
                constraints = []
                for object in objects:
                    _constraints = object.getConstraintByPath(paramname)
                    if isinstance(_constraints, list):
                        constraints.extend(_constraints)
                    else:
                        constraints.append(_constraints)
                return constraints

            # else it is a single object
            return objects.getConstraintByPath(paramname)

        name, index = self._parseIndex(path)

        # If index is a slice, we need get constraint one by one
        if isinstance(index, slice):
            constraints = []
            indices = self._rangeParam(name, index)
            for i in indices:
                constraints.append(self.getConstraint(name, i))
            return constraints

        # else the index is an int or None
        return self.getConstraint(name, index)
Esempio n. 11
0
    def addBackgroundPoints(self, bkgdpointlist):
        """
        add Background point (x, intensity) to this InterpolatedBackground instance

        Arguments:
        bkgdpointlist   --  list of 2-tuple(x, intensity) for pre-selected background points

        Return          --  None
        """
        background = self.get("Background")
        for bkgdtup in bkgdpointlist:
            # 1. verify the input list term
            try: 
                pos = bkgdtup[0]
                bck = bkgdtup[1]
            except IndexError, err:
                errmsg = "%-30s:  Input Error!  Element in input bkgdpointlist is not 2-tuple\n"% \
                    (self.__class__.__name__+"addBackgroundPoints()")
                errmsg += "Error message:  %-40s"% (err)
                raise RietError(errmsg)

            # 2. make Core objects 
            background.set("POS", pos)
            background.set("BCK", bck)
Esempio n. 12
0
def locateParameterByPath(rietobj, parfullname, srtype="r"):
    """
    according to the parameter's name and path and input Rietveld instance reference,
    locate the Rietveld class instance has this parameter and the name of the parameter

    return  --  2-tuple (RietveldClass_Instance_Refernece, Parameter_Name)

    Arguments:
    - rietobj       :   reference to a RietveldClass object
    - parfullname   :   string of the parameter with full path to locate this parameter from rietobj
    - srtype        :   string, "r" for Rietveld, "l" for Lebail

    Exception
    (1) If cannot find the  next RietveldClass to hold the parameter
    """

    # get path-list
    pathlist = GetPathListFromString(parfullname)

    parName = pathlist[-1]
    retObj = rietobj

    index = 0
    Continue = True

    returntuple = None

    while Continue:

        # progress
        name = pathlist[index]
        index += 1

        if name == parName and retObj.ParamDict.has_key(parName):
            # ending case
            returntuple = (retObj, parName)
            Continue = False

        elif index == len(pathlist):
            # error case 1:  cannot find parName in the final RietveldClass object
            estring = "utilfunction.locateParameterByPath()   cannot locate parameter " + parfullname
            raise RietError(estring)

        elif retObj.ObjectDict.has_key(name):
            # progress case: subclass
            retObj = retObj.get(name)

        elif retObj.ObjectListDict.has_key(name):
            # progress case: container
            try:
                seq = int(pathlist[index])
                retObj = retObj.get(name)[seq]
                index += 1
            except IndexError, err:
                estring = "utilfunction.locateParameterByPath() Locate parameter " + parfullname + " Error!"
                estring += "RietveldClass " + retObj.__class__.__name__ + " has no " + str(
                    seq) + "-th " + name
                estring += str(err)
                raise RietError(estring)
        else:
            print "Parameter with Path and Name:  " + str(parfullname)
            print retObj.ParamDict.keys()
            print "Parameter Name: " + name + "    doesn't match input parameter name " + parName
            print "Last object: " + retObj.__class__.__name__ + "  name = " + str(
                name)
            #print retObj
            raise NotImplementedError, "path_list: " + str(
                pathlist) + " incorrect"
Esempio n. 13
0
    def readFPOutput(lines):
        """ read the output of FullProf output file
          1. Last line contains "=> END"
            - check Chi2: is last Chi2 = "NaN"? "Chi2:-NaN, 
            - refined output 
          2. otherwise to 1
            a) "Error During Opening File" + file_name :  terminate the program
            b) "NO REFLECTIONS FOUND":  as Chi2 = NaN
        algorithm:
        (1) split Chi2 line with ":"

        return  1:  good refinement
                0   not refined
                -1: setup error
                -2: excessive peak overlap 
                -3: singular matrix
        """
        result = 0

        # 1. Exception!
        if len(lines) == 1:
            raise RietError("Fullprof fp2k Does Not Work")

        lastline = lines[-1]
        if lastline.count("=> END") >= 1:

            # 1. collect Chi2
            chi2lines = []
            for line in lines:
                if line.count("Chi2") == 1 and line.count("Rp")==1:
                    chi2lines.append(line)

            # 2. process last chi2 line
            # lastchi2line = chi2lines[len(chi2lines)-1]
            if len(chi2lines) > 1:
                # refinement mode
                lastchi2line = chi2lines[-1]
                if lastchi2line.count("NaN") > 0:
                    # NaN appears in statistic:  refine not done
                    result = 0
                else:
                    # good refinement
                    result = 1
            else:
                # calcuation mode
                result = -1

        else:   # not a normal end
            
            if lastline.count("Error") > 0:
                # Error 
                result = -1
                print "Exception!  FullProf set up error!   " + lastline + "\n"

            elif lastline.count("Excessive peak overlap") == 1:
                # Excessive peak overlap error
                result = -2

            elif lastline.count("Singular Matrix") == 1:
                # Singular Matrix Error
                result = -3

            elif lastline.count("NO REFLECTIONS FOUND") == 1:
                # Singular Matrix Error
                result = -4
        
            else:
                # intial value error
                result = 0

        return result
Esempio n. 14
0
def runFullProf(fit, pcrfilename, mode="refine", srtype="r", processdir=dir, userinfo=None, exportsub=False):
    """
    convert fit to FullProf pcr file
    execute Rietveld refinement by FullProf,

    Arguments:
    - fit           :   a fit object to convert to a pcr file and run by FullProf
    - pcrfilename   :   the name of the pcr file that is to write on the disk
    - mode          :   string, for mode.. options = 
                        1. "Refine"     least square refine 
                        2. "Calculate"  just calculate the pattern as the forward calculator
                        3. "pcr"        just print out pcr file
    - srtype        :   string, structure solution type, "r" for "Rietveld", "l" for Lebail
    - userinfo:     :   string, user information to add to pcr file
    - exportsub     :   Boolean (export result in .sub in calculation mode)

    Return          :   1. Refine Mode      FitSummary object
                        2. Calculate Mode   list of list of 2-tuple (or list) for a phase or None
    """
    from diffpy.pyfullprof.fit import Fit
    from diffpy.pyfullprof.pcrfilewriter import pcrFileWriter
    from diffpy.pyfullprof.pcrfilereader import ImportFitFromFullProf
    from diffpy.pyfullprof.fpoutputfileparsers import FPOutFileParser
    from diffpy.pyfullprof.fpuncertaintyreader import FPUncertainty

    # FIXME in 'Calculate' mode, only 1 pattern is allowed NOW!

    def ProcessOutput(infile):
        """
        processing an file thread
        (1) each line in intfile will be stored into a list as string without EOF
        (2) all lines are ordered according to the original order in infile

        infile: an file object
        """
        OutLines = []
        InLines  = infile.readlines()
        for line in InLines:
            newline = line.split("\n")[0]
            OutLines.append(newline)

        return OutLines

    # END FUNCTION:  def ProcessOutput(infile)

    def readFPOutput(lines):
        """ read the output of FullProf output file
          1. Last line contains "=> END"
            - check Chi2: is last Chi2 = "NaN"? "Chi2:-NaN, 
            - refined output 
          2. otherwise to 1
            a) "Error During Opening File" + file_name :  terminate the program
            b) "NO REFLECTIONS FOUND":  as Chi2 = NaN
        algorithm:
        (1) split Chi2 line with ":"

        return  1:  good refinement
                0   not refined
                -1: setup error
                -2: excessive peak overlap 
                -3: singular matrix
        """
        result = 0

        # 1. Exception!
        if len(lines) == 1:
            raise RietError("Fullprof fp2k Does Not Work")

        lastline = lines[-1]
        if lastline.count("=> END") >= 1:

            # 1. collect Chi2
            chi2lines = []
            for line in lines:
                if line.count("Chi2") == 1 and line.count("Rp")==1:
                    chi2lines.append(line)

            # 2. process last chi2 line
            # lastchi2line = chi2lines[len(chi2lines)-1]
            if len(chi2lines) > 1:
                # refinement mode
                lastchi2line = chi2lines[-1]
                if lastchi2line.count("NaN") > 0:
                    # NaN appears in statistic:  refine not done
                    result = 0
                else:
                    # good refinement
                    result = 1
            else:
                # calcuation mode
                result = -1

        else:   # not a normal end
            
            if lastline.count("Error") > 0:
                # Error 
                result = -1
                print "Exception!  FullProf set up error!   " + lastline + "\n"

            elif lastline.count("Excessive peak overlap") == 1:
                # Excessive peak overlap error
                result = -2

            elif lastline.count("Singular Matrix") == 1:
                # Singular Matrix Error
                result = -3

            elif lastline.count("NO REFLECTIONS FOUND") == 1:
                # Singular Matrix Error
                result = -4
        
            else:
                # intial value error
                result = 0

        return result

    # END FUNCTION:  def readFPOutput(lines)
    
    # -1: process input argument
    if userinfo is None:
        userinfo = []
    verifyType(userinfo, list)

    # 0. mandatory setup
    fit.set("Pcr", 1)
    fit.set("Aut", True)

    # 1.  check fit object:
    isvalid = fit.validate(mode)

    if not isvalid:
        dbtag = "1721"
        refine = fit.get("Refine")
        print "Debug Tag: %-20s" % (dbtag)
        print str(refine)
        errmsg = "runFullProf() Fit object is not valid. Abort!"
        raise RietError(errmsg)

    if mode == "calculate":
        # in this mode, data file is not used, but FullProf needs it!
        from diffpy.pyfullprof.utilfunction import checkFileExistence
        pattern   = fit.get("Pattern")[0]
        datafname = pattern.get("Datafile")
        isexist = checkFileExistence(datafname)
        if isexist is not True:
            fakedatafile = True
            fakefilename = datafname
            cmd = "touch %-10s"% (fakefilename)
            os.system(cmd)
        else:
            fakedatafile = False

    # 2. write out the pcr file and run FullProf
    pcrFileWriter(fit, pcrfilename, userinfo, srtype=srtype)
    # get the root name and ext name of the pcr file
    rootName, extname= os.path.splitext(os.path.basename(pcrfilename))
    baseName = os.path.basename(pcrfilename)
    if mode=="pcr":
        return
    shutil.copyfile(pcrfilename, rootName + '.prefit')

    cmd = 'fp2k ' + baseName

    import subprocess
    from diffpy.pyfullprof.environment import FullProfSubprocessArgs
    fp2kArgs = FullProfSubprocessArgs(cwd=processdir, stdout=subprocess.PIPE,
             stderr=subprocess.PIPE, stdin=open(os.devnull))
    
    
    output = subprocess.Popen(('fp2k', baseName ), **fp2kArgs)
    # 3. process output
    CodeOutput = ProcessOutput(output.stdout)
    #print '\n'.join(CodeOutput)
    CodeError  = ProcessOutput(output.stderr)

    output.stdout.close()
    output.stderr.close()
    output.wait()

    if mode == "refine":
        # 4. process fit result
        newfit = Fit(None)
        try:
            importfile   = ImportFitFromFullProf(pcrfilename)
            importresult = importfile.ImportFile(newfit)    
        except RietPCRError, err:
            print "Error Message:  %-30s"% (err)
            importresult = False

        # 5. pass the parameter and constraint information
        summary = FitSummary()

        if importresult is True:
            # 6. build output
            result = readFPOutput(CodeOutput)
            
            outfname = rootName +".out"

            # 6.2 Judge refine result
            # Note:  result > 0 is a more robust flag than refinesuccess
            if result == 0:
                refinesuccess = False
                errmsg = "NAN"
            elif result == -1:
                outparser = FPOutFileParser(newfit, outfname)
                refinesuccess = outparser.getStatus()
                errmsg = outparser.getErrorReason()
            elif result == -2:
                refinesuccess = False
                errmsg = "Excessive Peak Overlap"
            elif result == -3:
                refinesuccess = False
                errmsg = "Singular Matrix"
            elif result == -4:
                refinesuccess = False
                errmsg = "NO REFLECTIONS FOUND"
            else:
                refinesuccess = True
                errmsg = None
                if result < 0:
                    quitmessage = "result = %-5s < 0 means a failure error" % result
                    raise ValueError, quitmessage
            # END-IF-ELSE

            # 6.3 read uncertainty and phase fraction if refine is good 
            if refinesuccess is True: 
                # a) Uncertainty
                fpsigma = FPUncertainty(outfname)
                fpsigma.importUncertainty()
                fpsigma.exportToFit(newfit)

                # b) Phase Fraction
                sumfilename = rootName + ".sum"
                sumparse = FPSumFileParser(sumfilename)
                sumparse.parsePhaseFraction(newfit)
            # END-IF
            # 6.4 Construct Summary
            if result > 0:
                outparser = FPOutFileParser(newfit, outfname)
                summary.set(newfit, outparser, refinesuccess, srtype, errmsg, CodeOutput, CodeError)
            else:
                summary.setRefineStatus(False)
        else:
            # Bad refinement
            summary.setRefineStatus(False)
        # END-IF-ELSE 
        # 7. Process fp2k remainder
        os.rename(pcrfilename, rootName+".posfit")

        # 8. return
        return summary
Esempio n. 15
0
            simpatternslist = []
            for phaseid in xrange(1, len(phases)+1):
                # FIXME  This is not good for multiple pattern simulation
                if len(patterns) > 1:
                    raise NotImplementedError("See FIXME")
                pat = patterns[0]
                thmin = pat.get("Thmin")
                thmax = pat.get("Thmax")
                step  = pat.get("Step")
                dataset = subParser(rootname, phaseid, thmin=thmin, thmax=thmax, step=step) 
                simpatternslist.append(dataset)

            # 5. clean
            if fakedatafile is True:
                cmd = "rm %-10s"% (fakefilename)
                os.system(cmd)

            # 5. return
            return simpatternslist

        else:
            return
        # END-IF-ELSE

    else:
        errmsg = "run-FullProf:  mode = %-10s is NOT supported"% (mode)
        raise RietError(errmsg)

    return
Esempio n. 16
0
    def validate(self):
        """
        validate the parameters, subclass and container to meet the refinement requirement of 
        class Pattern

        Return  --  bool
        """
        from diffpy.pyfullprof.utilfunction import checkFileExistence
        rvalue = RietveldClass.validate(self)

        errmsg = ""

        # type check: virtual base class
        name = self.__class__.__name__
        if name == "Pattern":
            errmsg += "%-30s: %-40s"%("Pattern.validate()", "virtual base Pattern")
            print errmsg
            rvalue = False

        # FullProf Parameter Synchronization
        # 1. Excluded Region
        nex = len(self.get("ExcludedRegion"))
        self.set("Nex", nex)

        # 2. Scttering Factor
        nsc = len(self.get("ScatterFactor"))
        self.set("Nsc", nsc)

        # 3. background
        background = self.get("Background")

        if isinstance(background, BackgroundUserDefinedLinear):
            #NOTE: avoid using self.set('Nba', 2)
            self.Nba = 2
        elif isinstance(background, BackgroundUserDefinedCubic):
            #NOTE: avoid using self.set('Nba', -5)
            self.Nba = -5
        elif isinstance(background, BackgroundFourierwindow):
            #NOTE: avoid using self.set('Nba', -2)
            self.Nba = -2

        elif isinstance(background, BackgroundPolynomial):
            if background.get("Order") == 6:
                #NOTE: avoid using self.set('Nba', 0)
                self.Nba = 0
            elif background.get("Order") == 12:
                #NOTE: avoid using self.set('Nba', -4)
                self.Nba = -4
            else:
                errmsg = "Polynomial Order = %-4s Is Not Supported"% (background.get("Order"))
                raise NotImplementedError(errmsg)
        else:
            pass       

        if self.get("Nba") <= -5 or self.get("Nba") >= 2:
            self.set('NbaPoint', self.get("Background").size())

        if background.ParamDict.has_key("Bkpos"):
            self.set('Bkpos', self.get("Background").get("Bkpos"))

        # 4. output 
        self.set("Ipr", 3)
        if self.get("Prf") == 0:
            self.set("Prf", 3)

        # 5. peak profile Npr
        for contribution in self._contributionlist:
            npr = contribution.get("Npr")
            self.set("Npr", npr)

        # WZ: this section (item 6) is removed as all wdt from fit should be trustful
        # 6. Peak range
        # for contribution in self._contributionlist:
        #     wdt = contribution.get("Profile").get("PeakRange")
        #     if wdt > 0.0:
        #         self.set("Wdt", wdt)
        wdt = self.get("Wdt")
        if wdt <= 0.0:
            errmsg = String.Format("Pattern has Wdt (peak range) = %f <= 0") % (wdt)
            raise RietError(errmsg)

        # Check Valid
        # 1. resolution file
        if self.get("Res") != 0:
            exist = checkFileExistence(self.get("Resofile"))
            if not exist:
                rvalue = False
                errmsg += "Resolution File %-10s Cannot Be Found\n"% (self.get("Resofile"))

        # 2. data file.... ->  moved to Fit.validate()
        
        if rvalue is not True:
            print "Invalidity Detected In %-10s: %-60s"% (self.__class__.__name__, errmsg)

        return rvalue
Esempio n. 17
0
    def exportToFit(self, myfit):
        """
        Export the current information to a Fit object

        Argument:
        - myfit :   diffpy.pyfullprof.Fit instance

        Return  :   None
        """
        import diffpy.pyfullprof.pattern as PTN

        for nameinfotuple, val, sig in self._ParameterList:

            # 1. From the suffix of the name, determine if the parameter
            #    belongs to pattern, phase, or contribution
            ispattern = False
            isphase = False
            iscontribution = False
            if nameinfotuple.count("pat") > 0:
                ispattern = True
            if nameinfotuple.count("ph") > 0:
                isphase = True
            if ispattern and isphase:
                iscontribution = True
                ispattern = False
                isphase = False

            # 2. Get parameter and its index
            parname = None
            index = None

            if ispattern:
                # background
                patnum = nameinfotuple[1]
                pattern = myfit.get("Pattern")[patnum - 1]
                if nameinfotuple[-1] == "Bck":
                    rietobj = pattern.get("Background")
                    bcknum = nameinfotuple[-2] + 1
                    if isinstance(rietobj, PTN.BackgroundPolynomial):
                        parname = "BACK"
                        index = bcknum - 1
                    elif isinstance(rietobj, PTN.BackgroundUserDefined):
                        parname = "BCK"
                        index = bcknum - 1
                    else:
                        errmsg = "1045-1:  Object Instance %-10s Unrecoganizable" % (
                            rietobj.__class__.__name__)
                        print errmsg
                else:
                    iname = nameinfotuple[-1]
                    if FPUncertainty._NAMEMAPDICT.has_key(iname):
                        iname = FPUncertainty._NAMEMAPDICT[iname]
                    rietobj, parname = pattern.locateParameter(iname)
            elif isphase:
                phanum = nameinfotuple[1]
                phase = myfit.get("Phase")[phanum - 1]
                # a. get all atom's name
                atomindexmap = {}
                for atom in phase.get("Atom"):
                    atomname = atom.get("Name")
                    atomindexmap[atomname] = atom

                # b. see whether belonging to Atom's property
                atomnameslist = atomindexmap.keys()
                if atomnameslist.count(nameinfotuple[-2]) == 1:
                    atom = atomindexmap[nameinfotuple[-2]]
                    rietobj, parname = atom.locateParameter(nameinfotuple[-1])

                # c. if not atom's
                if rietobj is None:
                    iname = nameinfotuple[-1]
                    if FPUncertainty._NAMEMAPDICT.has_key(iname):
                        iname = FPUncertainty._NAMEMAPDICT[iname]
                    rietobj, parname = phase.locateParameter(iname)
            elif iscontribution:
                patnum = nameinfotuple[1]
                phanum = nameinfotuple[3]
                pattern = myfit.get("Pattern")[patnum - 1]
                phase = myfit.get("Phase")[phanum - 1]
                contrib = myfit.getContribution(pattern, phase)
                # a. Lattice
                if nameinfotuple[-1] == "Cell":
                    rietobj, parname = phase.locateParameter(nameinfotuple[-2])
                else:
                    iname = nameinfotuple[-1]
                    if FPUncertainty._NAMEMAPDICT.has_key(iname):
                        iname = FPUncertainty._NAMEMAPDICT[iname]
                    rietobj, parname = contrib.locateParameter(iname)
            else:
                raise RietError(
                    "Parameter %s does not belong to a known case." %
                    str(nameinfotuple))

            if parname is None:
                rstring = "%-20s ispat = %-10s ispha = %-10s iscon = %-10s"% \
                    (nameinfotuple, ispat, ispha, iscon)
                print "# 1045-Warning:  Implement this case! %-50s" % (rstring)
            else:
                if rietobj is None:
                    raise RietError(
                        "Parameter %s can not be found in the fit object." %
                        parname)
                constraint = rietobj.getConstraint(parname, index)
                if constraint:
                    constraint.sigma = sig
                else:
                    raise RietError(
                        "No constraint is bound to the parameter '%s'" %
                        parname)

            if 0:  # 1501
                print "1501:Par = %-10s  Val = %-15s  vs. input Val = %-15s  Sig = %-15s"% \
                    (parname, rietobj.get(parname).value(), val, sig)
            # END-DEBUG

        # LOOP-OVER: for nameinfotuple, val, sig in self._ParameterList

        return
Esempio n. 18
0
import sys
import subprocess
from diffpy.pyfullprof.which import whichall
from diffpy.pyfullprof.exception import RietError

# copy the system environment
FULLPROF_ENV = dict(os.environ)

_mswindows = sys.platform.startswith("win")

# make sure "gsas" variable exists in FULLPROF_ENV and is not empty
if not FULLPROF_ENV.get('FullProf'):
    _gsas_executables = whichall('fp2k')
    if not _gsas_executables:
        emsg = "Fullprof can not find the excutable, please check the system path"
        raise RietError(emsg, errorId="CANNOT_FIND_EXECUTABLE")

    _gsas_real_path = os.path.realpath(_gsas_executables[0])
    FULLPROF_ENV['FullProf'] = os.path.dirname(_gsas_real_path)
FULLPROF_ENV['FULLPROF'] = FULLPROF_ENV['FullProf']

# make sure its exe directory is first in the path
FULLPROF = FULLPROF_ENV['FullProf']

_path_org = FULLPROF_ENV.get('PATH', '').split(os.pathsep)
_path_new = [FULLPROF] + filter(lambda d: d != FULLPROF, _path_org)

FULLPROF_ENV['PATH'] = os.pathsep.join(_path_new)
FULLPROF_PATH = FULLPROF_ENV['PATH']

if _mswindows:
Esempio n. 19
0
    def extend(self, baseobj):
        """
        extend a base-object to 'self', and replace base-object with 'self' in 
        Rietveld-class hierachy
        baseobj = base object
        """
        def class_in_list(classname, classnamelist):
            """
            identify whether a class_name is one in classnamelist
            class_name can be extended class while the name in classnamelist is base class
            classname -
            classnamelist -
            """
            for basename in classnamelist:
                if classname.count(basename) == 1:
                    return True

            return False

        def getClassName(classname, classnamelist):
            """
            if classname is an extended class name, then return the base class name

            class_name can be extended class while the name in classnamelist is base class
            classname -
            classnamelist -
            """
            for basename in classnamelist:
                if classname.count(basename) == 1:
                    return basename

            raise RietError, "rietveldclass.extend - getClassName"
            return

        from diffpy.pyfullprof.contribution import Contribution
        if isinstance(baseobj, Contribution):
            errmsg = "Contribution should extend this function because of its dual parent"
            raise RietError(errmsg)

        # 1 check
        if not isinstance(self, baseobj.__class__):
            return False

        # 2 copy
        for name in baseobj.ParamDict.keys():
            self.__dict__[name] = baseobj.__dict__[name]

        for name in baseobj.ParamListDict.keys():
            for i in range(len(baseobj.__dict__[name])):
                self.__dict__[name].set(baseobj.__dict__[name].get(i))

        for name in baseobj.ObjectDict.keys():
            self.__dict__[name] = baseobj.__dict__[name]
            # set parent
            self.__dict__[name].parent = self
            self.__dict__[name].parent = self

        for name in baseobj.ObjectListDict.keys():
            self.__dict__[name] = baseobj.__dict__[name]
            # set parent
            self.__dict__[name].parent = self
            for objref in self.get(name):
                objref.parent = self

        # 3 find and set parent
        parentobj = baseobj.parent
        self.parent = parentobj

        # 4 replace from the parent class view
        # if baseobj.__class__.__name__ in parentobj.ObjectDict.keys():
        if class_in_list(baseobj.__class__.__name__,
                         parentobj.ObjectDict.keys()):
            classname = getClassName(baseobj.__class__.__name__,
                                     parentobj.ObjectDict.keys())
            parentobj.set(classname, self)
        # elif baseobj.__class__.__name__ in parentobj.ObjectListDict.keys():
        elif class_in_list(baseobj.__class__.__name__,
                           parentobj.ObjectListDict.keys()):
            classname = getClassName(baseobj.__class__.__name__,
                                     parentobj.ObjectListDict.keys())
            for i, obj in enumerate(parentobj.get(classname)):
                if baseobj == obj:
                    parentobj.set(classname, self, i)
                    break
            else:
                raise RietError("RietveldClass.extend(): Can not find the ")
        else:
            print "base obj:\t" + baseobj.__class__.__name__
            print "parent obj:\t" + str(parentobj.ObjectDict.keys())
            raise RietError(
                "RietveldClass.extend(): Parent Class Cannot Locate Object")

        return True
Esempio n. 20
0
    def setConstraintByPath(self,
                            path,
                            formula,
                            value=None,
                            damping=None,
                            varIndex=None):
        """Constrain a parameter by path

        path  -- a full path,  e.g., x.y.z[i].a
        formula -- a formula to be applied to the parameter
        value   -- the initial value of the constrained parameter.
        damping -- damping    
        varIndex -- if it is not None, append it to the formula; if the path 
                    corresponds to multiple parameters, varIndex will increase
                    by one for each parameter. 
 
        return: the newly created constraint object
        """
        if path.count('.') > 0:
            try:
                objpath, paramname = path.rsplit('.', 1)
            except:
                raise RietError('Invalid format for a parameter name: ' + path)

            objects = self.getByPath(objpath)

            # There are multiple objects
            if isinstance(objects, list):
                constraints = []
                for i, object in enumerate(objects):
                    _constraints = object.setConstraintByPath(
                        paramname, formula, value, damping, varIndex)
                    # Append results to the result constraint list,
                    # and increase the varIndex accordingly if it is not None.
                    if isinstance(_constraints, list):
                        constraints.extend(_constraints)
                        if varIndex is not None:
                            varIndex += len(_constraints)
                    else:
                        constraints.append(_constraints)
                        if varIndex is not None:
                            varIndex += 1
                return constraints

            # else it is a single object
            return objects.setConstraintByPath(paramname, formula, value,
                                               damping, varIndex)

        name, index = self._parseIndex(path)

        # If index is a slice, we need set constraint one by one
        if isinstance(index, slice):
            constraints = []
            indices = self._rangeParam(name, index)
            for i in indices:
                if varIndex is not None:
                    _formula = formula + '%i' % (varIndex + i)
                else:
                    _formula = formula
                constraints.append(
                    self.setConstraint(name, _formula, value, damping,
                                       index=i))
            return constraints

        # else the index is an int or None
        if varIndex is not None:
            formula = formula + '%i' % varIndex
        return self.setConstraint(name,
                                  formula,
                                  value=value,
                                  damping=damping,
                                  index=index)