Exemplo n.º 1
0
    def Ts2(self, srcName, reoptimize=False, approx=True,
            tol=None, MaxIterations=10, verbosity=0):

        srcName = str(srcName)

        if verbosity > 0:
            print("*** Start Ts_dl ***")
        source_attributes = self.components[0].getExtraSourceAttributes()
        self.syncSrcParams()
        freeParams = pyLike.DoubleVector()
        self.components[0].logLike.getFreeParamValues(freeParams)
        logLike1 = -self()
        for comp in self.components:
            comp.scaleSource(srcName, 1E-10)
            comp._ts_src = comp.logLike.getSource(srcName)
            free_flag = comp._ts_src.spectrum().normPar().isFree()

            if reoptimize:
                comp._ts_src.spectrum().normPar().setFree(False)
                self.syncSrcParams()

        logLike0 = -self()
        if tol is None:
            tol = self.tol
        if reoptimize:
            if verbosity > 0:
                print("** Do reoptimize")
            optFactory = pyLike.OptimizerFactory_instance()
            myOpt = optFactory.create(self.optimizer, self.composite)
            Niter = 1
            while Niter <= MaxIterations:
                try:
                    myOpt.find_min(0, tol)
                    break
                except RuntimeError as e:
                    print(e)
                if verbosity > 0:
                    print("** Iteration :", Niter)
                Niter += 1
        else:
            if approx:
                try:
                    self._renorm()
                except ZeroDivisionError:
                    pass
        self.syncSrcParams()
        logLike0 = max(-self(), logLike0)
        Ts_value = 2 * (logLike1 - logLike0)
        for comp in self.components:
            comp.scaleSource(srcName, 1E10)
            if reoptimize:
                comp._ts_src.spectrum().normPar().setFree(free_flag)
            self.syncSrcParams(srcName)
            comp.logLike.setFreeParamValues(freeParams)
            comp.model = SourceModel(comp.logLike)
            for src in source_attributes:
                comp.model[src].__dict__.update(source_attributes[src])
        self.model = self.components[0].model

        return Ts_value
Exemplo n.º 2
0
    def __init__(self,
                 binnedData,
                 srcModel=None,
                 optimizer='Drmngb',
                 use_bl2=False,
                 verbosity=0,
                 psfcorr=True,
                 convolve=True,
                 resample=True,
                 resamp_fact=2,
                 minbinsz=0.1,
                 wmap=None,
                 edisp_bins=-1):
        AnalysisBase.__init__(self)
        if srcModel is None:
            srcModel, optimizer = self._srcDialog()
        self.binnedData = binnedData
        self.srcModel = srcModel
        self.optimizer = optimizer
        if use_bl2:
            raise ValueError("BinnedLikelilihood2 is not longer supported")

        if wmap is None or wmap == "none":
            self._wmap = None
        else:
            self._wmap = pyLike.WcsMapLibrary.instance().wcsmap(wmap, "")
            self._wmap.setInterpolation(False)
            self._wmap.setExtrapolation(True)

        try:
            self.binned_config = ba.BinnedConfig(use_edisp=edisp_bins != 0,
                                                 applyPsfCorrections=psfcorr,
                                                 performConvolutiion=convolve,
                                                 resample=resample,
                                                 resamp_factor=resamp_fact,
                                                 minbinsz=minbinsz,
                                                 verbose=(verbosity > 0),
                                                 edisp_bins=edisp_bins)

            self.logLike = pyLike.BinnedLikelihood(binnedData.countsMap,
                                                   binnedData.observation,
                                                   self.binned_config,
                                                   binnedData.srcMaps,
                                                   self._wmap)
        except NotImplementedError as msg:
            print(
                "Failed to construct a BinnedLikelihood object because of a mismatch between fermipy and fermitools versions"
            )
            raise NotImplementedError(msg)

        self.verbosity = verbosity
        self.logLike.initOutputStreams()
        self.logLike.readXml(srcModel, _funcFactory, False, True, False)
        self.model = SourceModel(self.logLike, srcModel)
        self.energies = np.array(self.logLike.energies())
        self.e_vals = np.sqrt(self.energies[:-1] * self.energies[1:])
        self.nobs = self.logLike.countsSpectrum()
        self.sourceFitPlots = []
        self.sourceFitResids = []
Exemplo n.º 3
0
 def _set_errors(self, errors):
     source_attributes = self.components[0].getExtraSourceAttributes()
     my_errors = list(errors)
     self.composite.setErrors(my_errors)
     for component in self.components:
         component.model = SourceModel(component.logLike)
         for src in source_attributes:
             component.model[src].__dict__.update(source_attributes[src])
Exemplo n.º 4
0
    def Ts2(self, srcName, reoptimize=False, approx=True,
            tol=None, MaxIterations=10, verbosity=0):
        """Computes the TS value for a source indicated by "srcName."

        If "reoptimize=True" is selected this function will reoptimize
        the model up to "MaxIterations" given the tolerance "tol"
        (default is the tolerance selected for the overall fit).  If
        "appox=True" is selected (the default) it will renormalize the
        model (see _renorm).
        """

        saved_state = LikelihoodState(self)
        if verbosity > 0:
            print("*** Start Ts_dl ***")
        source_attributes = self.getExtraSourceAttributes()
        self.logLike.syncParams()
        src = self.logLike.getSource(srcName)
        self._ts_src = src
        freeParams = pyLike.DoubleVector()
        self.logLike.getFreeParamValues(freeParams)
        logLike1 = self.logLike.value()
        self.scaleSource(srcName, 1E-10)
        logLike0 = self.logLike.value()
        if tol is None:
            tol = self.tol
        if reoptimize:
            if verbosity > 0:
                print("** Do reoptimize")
            optFactory = pyLike.OptimizerFactory_instance()
            myOpt = optFactory.create(self.optimizer, self.logLike)
            Niter = 1
            while Niter <= MaxIterations:
                try:
                    myOpt.find_min(0, tol)
                    break
                except RuntimeError as e:
                    print(e)
                if verbosity > 0:
                    print("** Iteration :", Niter)
                Niter += 1
        else:
            if approx:
                try:
                    self._renorm()
                except ZeroDivisionError:
                    pass
        self.logLike.syncParams()
        logLike0 = max(self.logLike.value(), logLike0)
        Ts_value = 2 * (logLike1 - logLike0)
        self.scaleSource(srcName, 1E10)

        self.logLike.setFreeParamValues(freeParams)
        self.model = SourceModel(self.logLike)
        for src in source_attributes:
            self.model[src].__dict__.update(source_attributes[src])
        saved_state.restore()
        self.logLike.value()
        return Ts_value
Exemplo n.º 5
0
 def __init__(self,
              binnedData,
              srcModel=None,
              optimizer='Drmngb',
              use_bl2=False,
              verbosity=0,
              psfcorr=True,
              convolve=True,
              resample=True,
              resamp_fact=2,
              minbinsz=0.1,
              wmap=None):
     AnalysisBase.__init__(self)
     if srcModel is None:
         srcModel, optimizer = self._srcDialog()
     self.binnedData = binnedData
     self.srcModel = srcModel
     self.optimizer = optimizer
     if use_bl2:
         self.logLike = pyLike.BinnedLikelihood2(binnedData.countsMap,
                                                 binnedData.observation,
                                                 binnedData.srcMaps, True,
                                                 psfcorr, convolve,
                                                 resample, resamp_fact,
                                                 minbinsz)
     else:
         if wmap is None or wmap == "none":
             self.logLike = pyLike.BinnedLikelihood(binnedData.countsMap,
                                                    binnedData.observation,
                                                    binnedData.srcMaps,
                                                    True, psfcorr, convolve,
                                                    resample, resamp_fact,
                                                    minbinsz)
             self._wmap = None
         else:
             self._wmap = pyLike.WcsMapLibrary.instance().wcsmap(
                 wmap, "SKYMAP")
             self._wmap.setInterpolation(False)
             self._wmap.setExtrapolation(True)
             self.logLike = pyLike.BinnedLikelihood(
                 binnedData.countsMap, self._wmap, binnedData.observation,
                 binnedData.srcMaps, True, psfcorr, convolve, resample,
                 resamp_fact, minbinsz)
     self.verbosity = verbosity
     self.logLike.initOutputStreams()
     self.logLike.readXml(srcModel, _funcFactory, False, True, False)
     self.model = SourceModel(self.logLike, srcModel)
     self.energies = np.array(self.logLike.energies())
     self.e_vals = np.sqrt(self.energies[:-1] * self.energies[1:])
     self.nobs = self.logLike.countsSpectrum()
     self.sourceFitPlots = []
     self.sourceFitResids = []
Exemplo n.º 6
0
 def __init__(self, observation, srcModel=None,  optimizer='Minuit'):
     if srcModel is None:
         srcModel, optimizer = self._srcDialog()
     self._inputs = srcModel, observation, optimizer
     self.observation = observation
     self.optimizer = optimizer
     self.events = self.observation.eventCont().events();
     self.logLike = pyLike.LogLike(self.observation())
     self.logLike.readXml(srcModel, _funcFactory)
     self.logLike.computeEventResponses()
     self.model = SourceModel(self.logLike)
     eMin, eMax = self.observation.roiCuts().getEnergyCuts()
     nee = 21
     estep = num.log(eMax/eMin)/(nee-1)
     self.energies = eMin*num.exp(estep*num.arange(nee, type=num.Float))
     self.disp = None
     self.resids = None
     self.tolType = pyLike.ABSOLUTE
Exemplo n.º 7
0
    def __init__(self,
                 binnedData,
                 srcModel=None,
                 optimizer='Drmngb',
                 use_bl2=False,
                 verbosity=0,
                 psfcorr=True,
                 wmap=None,
                 config=None,
                 delete_local_fixed=False):
        AnalysisBase.__init__(self)
        if srcModel is None:
            srcModel, optimizer = self._srcDialog()
        self.binnedData = binnedData
        self.srcModel = srcModel
        self.optimizer = optimizer
        if wmap and wmap != "none":
            self.wmap = pyLike.WcsMapLibrary.instance().wcsmap(wmap, "")
            self.wmap.setInterpolation(False)
            self.wmap.setExtrapolation(True)
        else:
            self.wmap = None

        if use_bl2:
            raise ValueError("BinnedLikelihood2 is no longer supported")

        if config is None:
            config = BinnedConfig(applyPsfCorrections=psfcorr,
                                  delete_local_fixed=delete_local_fixed)

        self.logLike = pyLike.BinnedLikelihood(binnedData.countsMap,
                                               binnedData.observation, config,
                                               binnedData.srcMaps, self.wmap)

        self.verbosity = verbosity
        self.logLike.initOutputStreams()
        self.logLike.readXml(srcModel, _funcFactory, False, True, False)
        self.model = SourceModel(self.logLike, srcModel)
        self.energies = num.array(self.logLike.energies())
        self.e_vals = num.sqrt(self.energies[:-1] * self.energies[1:])
        self.nobs = self.logLike.countsSpectrum()
        self.nobs_wt = self.logLike.countsSpectrum(True)
        self.sourceFitPlots = []
        self.sourceFitResids = []
Exemplo n.º 8
0
 def __init__(self, observation, srcModel=None, optimizer='Drmngb', nee=21):
     AnalysisBase.__init__(self)
     if srcModel is None:
         srcModel, optimizer = self._srcDialog()
     self.observation = observation
     self.srcModel = srcModel
     self.optimizer = optimizer
     self.logLike = pyLike.LogLike(self.observation.observation)
     self.logLike.initOutputStreams()
     self.logLike.readXml(srcModel, _funcFactory, True, True, False)
     self.logLike.computeEventResponses()
     self.model = SourceModel(self.logLike, srcModel)
     eMin, eMax = self.observation.roiCuts().getEnergyCuts()
     estep = num.log(eMax/eMin)/(nee-1)
     self.energies = eMin*num.exp(estep*num.arange(nee, dtype=num.float))
     self.energies[-1] = eMax
     self.e_vals = num.sqrt(self.energies[:-1]*self.energies[1:])
     self.nobs = self._Nobs()
     self.nobs_wt = self.nobs
     self.disp = None
     self.resids = None
     self.sourceFitPlots = []
     self.sourceFitResids  = []
Exemplo n.º 9
0
 def _set_errors(self, errors):
     my_errors = list(errors)
     self.composite.setErrors(my_errors)
     for component in self.components:
         component.model = SourceModel(component.logLike)
Exemplo n.º 10
0
                if verbosity > 0:
                    print "** Iteration :", Niter
                Niter += 1
        else:
            if approx and n_free_base > 0:
                try:
                    self._renorm()
                except ZeroDivisionError:
                    pass
        self.syncSrcParams()
        logLike0 = max(-self(), logLike0)
        Ts_value = 2 * (logLike1 - logLike0)
        for ts_src, comp in zip(self._ts_src, self.components):
            comp.logLike.addSource(ts_src)
            comp.logLike.setFreeParamValues(freeParams)
            comp.model = SourceModel(comp.logLike)
            for src in source_attributes:
                comp.model[src].__dict__.update(source_attributes[src])
        self.model = self.components[0].model
        return Ts_value

    def _renorm(self, factor=None):
        if factor is None:
            freeNpred, totalNpred = self._npredValues()
            deficit = self.total_nobs() - totalNpred
            self.renormFactor = 1. + deficit / freeNpred
        else:
            self.renormFactor = factor
        if self.renormFactor < 1:
            self.renormFactor = 1
        srcNames = self.sourceNames()