def initDRM(self):
        """Initializes the DRM optimizer (either binned or unbinned).
        This is usually the second function that you run when using
        this module.  You need to run makeObs before you run this
        function.  If it hasn't been run, this function will exit."""

        try:
            self.obs
        except AttributeError:
            self.logger.critical(
                "Obs object does not exist.  Create it first with the makeObs function"
            )
            return

        try:
            qU.checkForFiles(self.logger, [self.likelihoodConf['model']])
            if (self.commonConf['binned']):
                self.DRM = BAn.BinnedAnalysis(self.obs,
                                              self.likelihoodConf['model'],
                                              optimizer="DRMNGB")
            else:
                self.DRM = UbAn.UnbinnedAnalysis(self.obs,
                                                 self.likelihoodConf['model'],
                                                 optimizer="DRMNGB")
                self.DRM.tol = float(self.likelihoodConf['drmtol'])
                self.logger.info(self.ret.subn(', ', str(self.DRM))[0])
        except (qU.FileNotFound):
            self.logger.critical("One or more needed files do not exist")
            return
    def initAltFit(self, opt="MINUIT"):
        """Initiallizes a minuit optimizer to use as a backup to the
        DRM optimizer.  This function is used internally in the fitDRM
        function so you probably will never use it.  You need to run
        makeObs before you run this function.  If it hasn't been run,
        this function will exit."""

        try:
            self.obs
        except AttributeError:
            self.logger.critical(
                "Obs object does not exist.  Create it first with the makeObs function"
            )
            return

        try:
            qU.checkForFiles(self.logger, [self.likelihoodConf['model']])
            if (self.commonConf['binned']):
                self.ALTFIT = BAn.BinnedAnalysis(self.obs,
                                                 self.likelihoodConf['model'],
                                                 optimizer=opt)
            else:
                self.ALTFIT = UbAn.UnbinnedAnalysis(
                    self.obs, self.likelihoodConf['model'], optimizer=opt)
            self.ALTFIT.tol = float(self.likelihoodConf['drmtol'])
            self.ALTFITobj = pyLike.Minuit(self.ALTFIT.logLike)
            self.logger.info(self.ret.subn(', ', str(self.ALTFIT))[0])
        except (qU.FileNotFound):
            self.logger.critical("One or more needed files do not exist")
            return
    def makeObs(self):
        
        """Creates either a binned or unbinned observation object for
        use in the likelihood analysis.  This function checks for all
        of the needed files first.  If you do not have a needed file,
        see the quickAnalysis module for creation.  This function
        should be run before any of the init or fit functions."""

        if(self.commonConf['binned']):
            try:
                qU.checkForFiles(self.logger,[self.commonConf['base']+'_srcMaps.fits',
                                          self.commonConf['base']+'_ltcube.fits',
                                          self.commonConf['base']+'_BinnedExpMap.fits'])
                self.obs = BAn.BinnedObs(srcMaps=self.commonConf['base']+'_srcMaps.fits',
                                         expCube=self.commonConf['base']+'_ltcube.fits',
                                         binnedExpMap=self.commonConf['base']+'_BinnedExpMap.fits',
                                         irfs=self.commonConf['irfs'])
            except(qU.FileNotFound):
                self.logger.critical("One or more needed files do not exist")
                sys.exit()
        else:
            try:
                qU.checkForFiles(self.logger,[self.commonConf['base']+'_filtered_gti.fits',
                                              self.commonConf['base']+'_SC.fits',
                                              self.commonConf['base']+'_expMap.fits',
                                              self.commonConf['base']+'_ltcube.fits'])
                self.obs = UbAn.UnbinnedObs(self.commonConf['base']+'_filtered_gti.fits',
                                       self.commonConf['base']+'_SC.fits',
                                       expMap=self.commonConf['base']+'_expMap.fits',
                                       expCube=self.commonConf['base']+'_ltcube.fits',
                                       irfs=self.commonConf['irfs'])
            except(qU.FileNotFound):
                self.logger.critical("One or more needed files do not exist")
                sys.exit()
        self.logger.info(self.ret.subn(', ',str(self.obs))[0])
    def initAltFit(self,opt="MINUIT"):

        """Initiallizes a minuit optimizer to use as a backup to the
        DRM optimizer.  This function is used internally in the fitDRM
        function so you probably will never use it.  You need to run
        makeObs before you run this function.  If it hasn't been run,
        this function will exit."""

        try:
            self.obs
        except AttributeError:
            self.logger.critical("Obs object does not exist.  Create it first with the makeObs function")
            return

        try:
            qU.checkForFiles(self.logger,[self.likelihoodConf['model']])
            if(self.commonConf['binned']):
                self.ALTFIT = BAn.BinnedAnalysis(self.obs,self.likelihoodConf['model'],optimizer=opt)
            else:
                self.ALTFIT = UbAn.UnbinnedAnalysis(self.obs,self.likelihoodConf['model'],optimizer=opt)
            self.ALTFIT.tol = float(self.likelihoodConf['drmtol'])
            self.ALTFITobj = pyLike.Minuit(self.ALTFIT.logLike)
            self.logger.info(self.ret.subn(', ',str(self.ALTFIT))[0])
        except(qU.FileNotFound):
            self.logger.critical("One or more needed files do not exist")
            return
    def runAll(self, run=True):

        """Does a full event selection and exposure calculation.  This
        is the function called when this module is run from the
        command line.  You need to have two files to start with:
        <basename>.list and <basename>_SC.fits.  The first one is just
        a text file with a list of the raw data files (one per line)
        and the other is the spacecraft file.  <basename> is a user
        defined prefix (usually the source name but not necissarily).
        Returns an exception if any of the files are not found."""

        self.logger.info("***Checking for files***")
        try:
            qU.checkForFiles(self.logger,[self.commonConf['base']+".list",self.commonConf['base']+"_SC.fits"])
        except(qU.FileNotFound):
            self.logger.critical("One or more needed files do not exist")
            sys.exit()
        self.logger.info("***Running gtselect***")
        self.runSelect(run)
        self.logger.info("***Running gtmktime***")
        self.runGTI(run)
        self.logger.info("***Running gtltcube***")
        self.runLTCube(run)

        if(self.commonConf['binned']):
            self.logger.info("***Running gtbin***")
            self.runCCUBE(run)
            self.logger.info("***Running gtexpcube2***")
            self.runExpCube(run)
            self.logger.info("***Running gtsrcMaps***")
            self.runSrcMaps(run)
        else:
            self.logger.info("***Running gtexpmap***")
            self.runExpMap(run)
    def runSrcMaps(self, run=True):

        """Generates a source map for your region.  Checks to make
        sure that there's an XML model to be had and if not, creates
        one from the 2FGL."""

        self.generateXMLmodel()

        try:
            qU.checkForFiles(self.logger,[self.commonConf['base']+"_CCUBE.fits",
                                       self.commonConf['base']+"_ltcube.fits",
                                       self.commonConf['base']+"_BinnedExpMap.fits",
                                       self.commonConf['base']+"_SC.fits",])
        except(qU.FileNotFound):
            self.logger.critical("One or more needed files do not exist")
            sys.exit()

        srcMaps['scfile'] = self.commonConf['base']+"_SC.fits"
        srcMaps['expcube'] = self.commonConf['base']+"_ltcube.fits"
        srcMaps['cmap'] = self.commonConf['base']+"_CCUBE.fits"
        srcMaps['srcmdl'] = self.commonConf['base']+"_model.xml"
        srcMaps['bexpmap'] = self.commonConf['base']+"_BinnedExpMap.fits"
        srcMaps['outfile'] = self.commonConf['base']+"_srcMaps.fits"
        srcMaps['irfs'] = self.commonConf['irfs']
        srcMaps['rfactor'] = 4
        srcMaps['emapbnds'] = "yes"

        qU.runCommand(srcMaps,self.logger,run)
    def runAll(self, run=True):

        """Does a full event selection and exposure calculation.  This
        is the function called when this module is run from the
        command line.  You need to have two files to start with:
        <basename>.list and <basename>_SC.fits.  The first one is just
        a text file with a list of the raw data files (one per line)
        and the other is the spacecraft file.  <basename> is a user
        defined prefix (usually the source name but not necissarily).
        Returns an exception if any of the files are not found."""

        self.logger.info("***Checking for files***")
        try:
            qU.checkForFiles(self.logger,[self.commonConf['base']+".list",self.commonConf['base']+"_SC.fits"])
        except(qU.FileNotFound):
            self.logger.critical("One or more needed files do not exist")
            sys.exit()
        self.logger.info("***Running gtselect***")
        self.runSelect(run)
        self.logger.info("***Running gtmktime***")
        self.runGTI(run)
        self.logger.info("***Running gtltcube***")
        self.runLTCube(run)

        if(self.commonConf['binned']):
            self.logger.info("***Running gtbin***")
            self.runCCUBE(run)
            self.logger.info("***Running gtexpcube2***")
            self.runExpCube(run)
            self.logger.info("***Running gtsrcMaps***")
            self.runSrcMaps(run)
        else:
            self.logger.info("***Running gtexpmap***")
            self.runExpMap(run)
    def runSrcMaps(self, run=True):

        """Generates a source map for your region.  Checks to make
        sure that there's an XML model to be had and if not, creates
        one from the 2FGL."""

        self.generateXMLmodel()

        try:
            qU.checkForFiles(self.logger,[self.commonConf['base']+"_CCUBE.fits",
                                       self.commonConf['base']+"_ltcube.fits",
                                       self.commonConf['base']+"_BinnedExpMap.fits",
                                       self.commonConf['base']+"_SC.fits",])
        except(qU.FileNotFound):
            self.logger.critical("One or more needed files do not exist")
            sys.exit()

        srcMaps['scfile'] = self.commonConf['base']+"_SC.fits"
        srcMaps['expcube'] = self.commonConf['base']+"_ltcube.fits"
        srcMaps['cmap'] = self.commonConf['base']+"_CCUBE.fits"
        srcMaps['srcmdl'] = self.commonConf['base']+"_model.xml"
        srcMaps['bexpmap'] = self.commonConf['base']+"_BinnedExpMap.fits"
        srcMaps['outfile'] = self.commonConf['base']+"_srcMaps.fits"
        srcMaps['irfs'] = self.commonConf['irfs']
        srcMaps['rfactor'] = 4
        srcMaps['emapbnds'] = "yes"

        qU.runCommand(srcMaps,self.logger,run)
    def initMIN(self, useBadFit=False, modelFile="", useEdisp=False):
        """Initiallizes a New Minuit optimizer to use as a backup to
        the DRM optimizer.  This is usually run after you have
        initially run fitDRM and created a <basename>_likeDRM.xml
        model file which is used a seed for the New Minuit optimizer.
        You can skip the DRM process if you like but you need to have
        the proper model file (<basename>_likeDRM.xml) present in the
        working directory. You need to run makeObs before you run this
        function.  If it hasn't been run, this function will exit.  If
        you want to use the non convergant fit from fitDRM, set
        useBadFit to True.  You can also pass a custom model file name
        via the modelFile parameter."""

        try:
            self.obs
        except AttributeError:
            self.logger.critical(
                "Obs object does not exist.  Create it first with the makeObs function."
            )
            return

        if (useBadFit):
            model = self.commonConf['base'] + '_badDRMFit.xml'
        else:
            model = self.commonConf['base'] + '_likeDRM.xml'

        if (modelFile):
            model = modelFile

        try:
            qU.checkForFiles(self.logger, [model])
            if (self.commonConf['binned']):
                self.MIN = BAn.BinnedAnalysis(self.obs,
                                              model,
                                              optimizer='NewMinuit')
            else:
                self.MIN = UbAn.UnbinnedAnalysis(self.obs,
                                                 model,
                                                 optimizer='NewMinuit')
            self.MIN.tol = float(self.likelihoodConf['mintol'])
            self.MINobj = pyLike.NewMinuit(self.MIN.logLike)
            self.pristine = LikelihoodState(self.MIN)
            self.logger.info(self.ret.subn(', ', str(self.MIN))[0])
            if (useEdisp):
                self.MIN.logLike.set_edisp_flag(useEdisp)
        except (qU.FileNotFound):
            self.logger.critical("One or more needed files do not exist")
            return
    def initMIN(self, useBadFit=False, modelFile="",useEdisp=False):

        """Initiallizes a New Minuit optimizer to use as a backup to
        the DRM optimizer.  This is usually run after you have
        initially run fitDRM and created a <basename>_likeDRM.xml
        model file which is used a seed for the New Minuit optimizer.
        You can skip the DRM process if you like but you need to have
        the proper model file (<basename>_likeDRM.xml) present in the
        working directory. You need to run makeObs before you run this
        function.  If it hasn't been run, this function will exit.  If
        you want to use the non convergant fit from fitDRM, set
        useBadFit to True.  You can also pass a custom model file name
        via the modelFile parameter."""

        try:
            self.obs
        except AttributeError:
            self.logger.critical("Obs object does not exist.  Create it first with the makeObs function.")
            return

        if(useBadFit):
            model = self.commonConf['base']+'_badDRMFit.xml'
        else:
            model = self.commonConf['base']+'_likeDRM.xml'

        if(modelFile):
            model = modelFile

        try:
            qU.checkForFiles(self.logger,[model])
            if(self.commonConf['binned']):
                self.MIN = BAn.BinnedAnalysis(self.obs,model,optimizer='NewMinuit')
            else:
                self.MIN = UbAn.UnbinnedAnalysis(self.obs,model,optimizer='NewMinuit')
            self.MIN.tol = float(self.likelihoodConf['mintol'])
            self.MINobj = pyLike.NewMinuit(self.MIN.logLike)
            self.pristine = LikelihoodState(self.MIN)
            self.logger.info(self.ret.subn(', ',str(self.MIN))[0])
            if(useEdisp):
                self.MIN.logLike.set_edisp_flag(useEdisp)
        except(qU.FileNotFound):
            self.logger.critical("One or more needed files do not exist")
            return
    def makeObs(self):
        """Creates either a binned or unbinned observation object for
        use in the likelihood analysis.  This function checks for all
        of the needed files first.  If you do not have a needed file,
        see the quickAnalysis module for creation.  This function
        should be run before any of the init or fit functions."""

        if (self.commonConf['binned']):
            try:
                qU.checkForFiles(self.logger, [
                    self.commonConf['base'] + '_srcMaps.fits',
                    self.commonConf['base'] + '_ltcube.fits',
                    self.commonConf['base'] + '_BinnedExpMap.fits'
                ])
                self.obs = BAn.BinnedObs(
                    srcMaps=self.commonConf['base'] + '_srcMaps.fits',
                    expCube=self.commonConf['base'] + '_ltcube.fits',
                    binnedExpMap=self.commonConf['base'] +
                    '_BinnedExpMap.fits',
                    irfs=self.commonConf['irfs'])
            except (qU.FileNotFound):
                self.logger.critical("One or more needed files do not exist")
                sys.exit()
        else:
            try:
                qU.checkForFiles(self.logger, [
                    self.commonConf['base'] + '_filtered_gti.fits',
                    self.commonConf['base'] + '_SC.fits',
                    self.commonConf['base'] + '_expMap.fits',
                    self.commonConf['base'] + '_ltcube.fits'
                ])
                self.obs = UbAn.UnbinnedObs(
                    self.commonConf['base'] + '_filtered_gti.fits',
                    self.commonConf['base'] + '_SC.fits',
                    expMap=self.commonConf['base'] + '_expMap.fits',
                    expCube=self.commonConf['base'] + '_ltcube.fits',
                    irfs=self.commonConf['irfs'])
            except (qU.FileNotFound):
                self.logger.critical("One or more needed files do not exist")
                sys.exit()
        self.logger.info(self.ret.subn(', ', str(self.obs))[0])
    def initDRM(self):

        """Initializes the DRM optimizer (either binned or unbinned).
        This is usually the second function that you run when using
        this module.  You need to run makeObs before you run this
        function.  If it hasn't been run, this function will exit."""
        
        try:
            self.obs
        except AttributeError:
            self.logger.critical("Obs object does not exist.  Create it first with the makeObs function")
            return

        try:
            qU.checkForFiles(self.logger,[self.likelihoodConf['model']])
            if(self.commonConf['binned']):
                self.DRM = BAn.BinnedAnalysis(self.obs,self.likelihoodConf['model'],optimizer="DRMNGB")
            else:
                self.DRM = UbAn.UnbinnedAnalysis(self.obs,self.likelihoodConf['model'],optimizer="DRMNGB")
                self.DRM.tol = float(self.likelihoodConf['drmtol'])
                self.logger.info(self.ret.subn(', ',str(self.DRM))[0])
        except(qU.FileNotFound):
            self.logger.critical("One or more needed files do not exist")
            return