Instruction:
Create a Python 3 function for
returning a dictionary for a source with the current best - fit parameters.

Response:
def get_src_model(self, name, paramsonly=False, reoptimize=False,
                      npts=None, **kwargs):
        """Compose a dictionary for a source with the current best-fit
        parameters.

        Parameters
        ----------

        name : str

        paramsonly : bool
           Skip computing TS and likelihood profile.

        reoptimize : bool
           Re-fit background parameters in likelihood scan.

        npts : int
           Number of points for likelihood scan.

        Returns
        -------
        src_dict : dict

        """

        self.logger.debug('Generating source dict for ' + name)

        optimizer = kwargs.get('optimizer', self.config['optimizer'])
        if npts is None:
            npts = self.config['gtlike']['llscan_npts']

        name = self.get_source_name(name)
        source = self.like[name].src
        spectrum = source.spectrum()
        normPar = self.like.normPar(name)

        src_dict = defaults.make_default_dict(defaults.source_flux_output)
        src_dict.update({'name': name,
                         'pivot_energy': 1000.,
                         'ts': np.nan,
                         'loglike': np.nan,
                         'npred': 0.0,
                         'npred_wt': 0.0,
                         'loglike_scan': np.nan * np.ones(npts),
                         'dloglike_scan': np.nan * np.ones(npts),
                         'eflux_scan': np.nan * np.ones(npts),
                         'flux_scan': np.nan * np.ones(npts),
                         'norm_scan': np.nan * np.ones(npts),
                         })

        src_dict.update(gtutils.gtlike_spectrum_to_vectors(spectrum))
        src_dict['spectral_pars'] = gtutils.get_function_pars_dict(spectrum)

        # Get Counts Spectrum
        src_dict['model_counts'] = self.model_counts_spectrum(
            name, summed=True)
        src_dict['model_counts_wt'] = self.model_counts_spectrum(
            name, summed=True, weighted=True)

        # Get NPred
        src_dict['npred'] = self.like.NpredValue(str(name))
        # EAC, we need this b/c older version of the ST don't have the right signature
        try:
            src_dict['npred_wt'] = self.like.NpredValue(str(name), True)
        except (TypeError, NotImplementedError):
            src_dict['npred_wt'] = src_dict['npred']

        # Get the Model Fluxes
        try:
            thesrc = self.like[name]
            src_dict['flux'] = self.like.flux(name, self.energies[0],
                                              self.energies[-1])
            src_dict['flux100'] = self.like.flux(name, 100., 10 ** 5.5)
            src_dict['flux1000'] = self.like.flux(name, 1000., 10 ** 5.5)
            src_dict['flux10000'] = self.like.flux(name, 10000., 10 ** 5.5)
            src_dict['eflux'] = self.like.energyFlux(name,
                                                     self.energies[0],
                                                     self.energies[-1])
            src_dict['eflux100'] = self.like.energyFlux(name, 100.,
                                                        10 ** 5.5)
            src_dict['eflux1000'] = self.like.energyFlux(name, 1000.,
                                                         10 ** 5.5)
            src_dict['eflux10000'] = self.like.energyFlux(name, 10000.,
                                                          10 ** 5.5)
            src_dict['dnde'] = self.like[name].spectrum()(
                pyLike.dArg(src_dict['pivot_energy']))
            src_dict['dnde100'] = self.like[name].spectrum()(
                pyLike.dArg(100.))
            src_dict['dnde1000'] = self.like[name].spectrum()(
                pyLike.dArg(1000.))
            src_dict['dnde10000'] = self.like[name].spectrum()(
                pyLike.dArg(10000.))
            if normPar.getValue() == 0:
                normPar.setValue(1.0)

                dnde_index = -get_spectral_index(self.like[name],
                                                 src_dict['pivot_energy'])

                dnde100_index = -get_spectral_index(self.like[name],
                                                    100.)
                dnde1000_index = -get_spectral_index(self.like[name],
                                                     1000.)
                dnde10000_index = -get_spectral_index(self.like[name],
                                                      10000.)

                normPar.setValue(0.0)
            else:
                dnde_index = -get_spectral_index(self.like[name],
                                                 src_dict['pivot_energy'])

                dnde100_index = -get_spectral_index(self.like[name],
                                                    100.)
                dnde1000_index = -get_spectral_index(self.like[name],
                                                     1000.)
                dnde10000_index = -get_spectral_index(self.like[name],
                                                      10000.)
            src_dict['dnde_index'] = dnde_index
            src_dict['dnde100_index'] = dnde100_index
            src_dict['dnde1000_index'] = dnde1000_index
            src_dict['dnde10000_index'] = dnde10000_index

        except Exception:
            self.logger.error('Failed to update source parameters.',
                              exc_info=True)

        # Only compute TS, errors, and ULs if the source was free in
        # the fit
        if not self.get_free_source_params(name) or paramsonly:
            return src_dict

        emax = 10 ** 5.5

        try:
            src_dict['flux_err'] = self.like.fluxError(name,
                                                       self.energies[0],
                                                       self.energies[-1])
            src_dict['flux100_err'] = self.like.fluxError(name, 100., emax)
            src_dict['flux1000_err'] = self.like.fluxError(name, 1000., emax)
            src_dict['flux10000_err'] = self.like.fluxError(name, 10000., emax)
            src_dict['eflux_err'] = \
                self.like.energyFluxError(name, self.energies[0],
                                          self.energies[-1])
            src_dict['eflux100_err'] = self.like.energyFluxError(name, 100.,
                                                                 emax)
            src_dict['eflux1000_err'] = self.like.energyFluxError(name, 1000.,
                                                                  emax)
            src_dict['eflux10000_err'] = self.like.energyFluxError(name, 10000.,
                                                                   emax)

        except Exception:
            pass
        # self.logger.error('Failed to update source parameters.',
        #  exc_info=True)
        lnlp = self.profile_norm(name, savestate=True,
                                 reoptimize=reoptimize, npts=npts,
                                 optimizer=optimizer)

        src_dict['loglike_scan'] = lnlp['loglike']
        src_dict['dloglike_scan'] = lnlp['dloglike']
        src_dict['eflux_scan'] = lnlp['eflux']
        src_dict['flux_scan'] = lnlp['flux']
        src_dict['norm_scan'] = lnlp['xvals']
        src_dict['loglike'] = np.max(lnlp['loglike'])

        flux_ul_data = utils.get_parameter_limits(
            lnlp['flux'], lnlp['dloglike'])
        eflux_ul_data = utils.get_parameter_limits(
            lnlp['eflux'], lnlp['dloglike'])

        if normPar.getValue() == 0:
            normPar.setValue(1.0)
            flux = self.like.flux(name, self.energies[0], self.energies[-1])
            flux100 = self.like.flux(name, 100., emax)
            flux1000 = self.like.flux(name, 1000., emax)
            flux10000 = self.like.flux(name, 10000., emax)
            eflux = self.like.energyFlux(name, self.energies[0],
                                         self.energies[-1])
            eflux100 = self.like.energyFlux(name, 100., emax)
            eflux1000 = self.like.energyFlux(name, 1000., emax)
            eflux10000 = self.like.energyFlux(name, 10000., emax)

            flux100_ratio = flux100 / flux
            flux1000_ratio = flux1000 / flux
            flux10000_ratio = flux10000 / flux
            eflux100_ratio = eflux100 / eflux
            eflux1000_ratio = eflux1000 / eflux
            eflux10000_ratio = eflux10000 / eflux
            normPar.setValue(0.0)
        else:
            flux100_ratio = src_dict['flux100'] / src_dict['flux']
            flux1000_ratio = src_dict['flux1000'] / src_dict['flux']
            flux10000_ratio = src_dict['flux10000'] / src_dict['flux']

            eflux100_ratio = src_dict['eflux100'] / src_dict['eflux']
            eflux1000_ratio = src_dict['eflux1000'] / src_dict['eflux']
            eflux10000_ratio = src_dict['eflux10000'] / src_dict['eflux']

        src_dict['flux_ul95'] = flux_ul_data['ul']
        src_dict['flux100_ul95'] = flux_ul_data['ul'] * flux100_ratio
        src_dict['flux1000_ul95'] = flux_ul_data['ul'] * flux1000_ratio
        src_dict['flux10000_ul95'] = flux_ul_data['ul'] * flux10000_ratio

        src_dict['eflux_ul95'] = eflux_ul_data['ul']
        src_dict['eflux100_ul95'] = eflux_ul_data['ul'] * eflux100_ratio
        src_dict['eflux1000_ul95'] = eflux_ul_data['ul'] * eflux1000_ratio
        src_dict['eflux10000_ul95'] = eflux_ul_data['ul'] * eflux10000_ratio

        # Extract covariance matrix
        fd = None
        try:
            fd = FluxDensity.FluxDensity(self.like, name)
            src_dict['covar'] = fd.covar
        except RuntimeError:
            pass
        # if ex.message == 'Covariance matrix has not been
        # computed.':

        # Extract bowtie
        if fd and len(src_dict['covar']) and src_dict['covar'].ndim >= 1:
            loge = np.linspace(self.log_energies[0],
                               self.log_energies[-1], 50)
            src_dict['model_flux'] = self.bowtie(name, fd=fd, loge=loge)
            src_dict['dnde100_err'] = fd.error(100.)
            src_dict['dnde1000_err'] = fd.error(1000.)
            src_dict['dnde10000_err'] = fd.error(10000.)

            src_dict['pivot_energy'] = src_dict['model_flux']['pivot_energy']

            e0 = src_dict['pivot_energy']
            src_dict['dnde'] = self.like[name].spectrum()(pyLike.dArg(e0))
            src_dict['dnde_err'] = fd.error(e0)

        if not reoptimize:
            src_dict['ts'] = self.like.Ts2(name, reoptimize=reoptimize)
        else:
            src_dict['ts'] = -2.0 * lnlp['dloglike'][0]

        return src_dict


Instruction:
Can you tell what is the following Python 3 function doing
def compute_srcprob(self,xmlfile=None, overwrite=False):

        for i,c in enumerate(self.components):
            # compute diffuse response, necessary for srcprob
            c._diffrsp_app(xmlfile=xmlfile)
            # compute srcprob
            c._srcprob_app(xmlfile = xmlfile, overwrite = overwrite)

Response: Run the gtsrcprob app with the current model or a user provided xmlfile


Instruction:
How would you code a function in Python 3 to
add a new source to the model.

Response:
def add_source(self, name, src_dict, free=None, save_source_maps=True,
                   use_pylike=True, use_single_psf=False):
        """Add a new source to the model.  Source properties
        (spectrum, spatial model) are set with the src_dict argument.

        Parameters
        ----------

        name : str
            Source name.

        src_dict : dict or `~fermipy.roi_model.Source` object
            Dictionary or Source object defining the properties of the
            source.

        free : bool
            Initialize the source with the normalization parameter free.

        save_source_maps : bool
            Write the source map for this source to the source maps file.

        use_pylike : bool

        use_single_psf : bool

        """

        # if self.roi.has_source(name):
        #    msg = 'Source %s already exists.' % name
        #    self.logger.error(msg)
        #    raise Exception(msg)

        srcmap_utils.delete_source_map(self.files['srcmap'], name)

        src = self.roi[name]
        if self.config['gtlike']['expscale'] is not None and \
                name not in self._src_expscale:
            self._src_expscale[name] = self.config['gtlike']['expscale']

        if self._like is None:
            return

        if not use_pylike:
            self._update_srcmap_file([src], True)

        pylike_src = self._create_source(src)

        # Initialize source as free/fixed
        if free is not None:
            pylike_src.spectrum().normPar().setFree(free)

        if hasattr(pyLike, 'PsfIntegConfig') and \
                hasattr(pyLike.PsfIntegConfig, 'set_use_single_psf'):
            config = pyLike.BinnedLikeConfig(self.like.logLike.config())
            config.psf_integ_config().set_use_single_psf(use_single_psf)
            self.like.addSource(pylike_src, config)
        else:
            self.like.addSource(pylike_src)

        self.like.syncSrcParams(str(name))
        self.like.logLike.buildFixedModelWts()
        if save_source_maps and \
                not self.config['gtlike']['use_external_srcmap']:
            self.like.logLike.saveSourceMaps(str(self.files['srcmap']))

        self.set_exposure_scale(name)


Instruction:
Can you create a Python 3 function that
creates a pyLikelihood Source object from a single source object.

Response:
def _create_source(self, src):
        """Create a pyLikelihood Source object from a
        `~fermipy.roi_model.Model` object."""

        if src['SpatialType'] == 'SkyDirFunction':
            pylike_src = pyLike.PointSource(self.like.logLike.observation())
            pylike_src.setDir(src.skydir.ra.deg, src.skydir.dec.deg, False,
                              False)
        elif src['SpatialType'] == 'SpatialMap':
            filepath = str(utils.path_to_xmlpath(src['Spatial_Filename']))
            sm = pyLike.SpatialMap(filepath)
            pylike_src = pyLike.DiffuseSource(sm,
                                              self.like.logLike.observation(),
                                              False)
        elif src['SpatialType'] == 'RadialProfile':
            filepath = str(utils.path_to_xmlpath(src['Spatial_Filename']))
            sm = pyLike.RadialProfile(filepath)
            sm.setCenter(src['ra'], src['dec'])
            pylike_src = pyLike.DiffuseSource(sm,
                                              self.like.logLike.observation(),
                                              False)
        elif src['SpatialType'] == 'RadialGaussian':
            sm = pyLike.RadialGaussian(src.skydir.ra.deg, src.skydir.dec.deg,
                                       src.spatial_pars['Sigma']['value'])
            pylike_src = pyLike.DiffuseSource(sm,
                                              self.like.logLike.observation(),
                                              False)

        elif src['SpatialType'] == 'RadialDisk':
            sm = pyLike.RadialDisk(src.skydir.ra.deg, src.skydir.dec.deg,
                                   src.spatial_pars['Radius']['value'])
            pylike_src = pyLike.DiffuseSource(sm,
                                              self.like.logLike.observation(),
                                              False)

        elif src['SpatialType'] == 'MapCubeFunction':
            filepath = str(utils.path_to_xmlpath(src['Spatial_Filename']))
            mcf = pyLike.MapCubeFunction2(filepath)
            pylike_src = pyLike.DiffuseSource(mcf,
                                              self.like.logLike.observation(),
                                              False)
        else:
            raise Exception('Unrecognized spatial type: %s',
                            src['SpatialType'])

        if src['SpectrumType'] == 'FileFunction':
            fn = gtutils.create_spectrum_from_dict(src['SpectrumType'],
                                                   src.spectral_pars)

            file_function = pyLike.FileFunction_cast(fn)
            filename = str(os.path.expandvars(src['Spectrum_Filename']))
            file_function.readFunction(filename)
        elif src['SpectrumType'] == 'DMFitFunction':

            fn = pyLike.DMFitFunction()
            fn = gtutils.create_spectrum_from_dict(src['SpectrumType'],
                                                   src.spectral_pars, fn)
            filename = str(os.path.expandvars(src['Spectrum_Filename']))
            fn.readFunction(filename)
        else:
            fn = gtutils.create_spectrum_from_dict(src['SpectrumType'],
                                                   src.spectral_pars)

        pylike_src.setSpectrum(fn)
        pylike_src.setName(str(src.name))

        return pylike_src


Instruction:
Make a summary of the following Python 3 code
def set_exposure_scale(self, name, scale=None):
        name = self.roi.get_source_by_name(name).name
        if scale is None and name not in self._src_expscale:
            return
        elif scale is None:
            scale = self._src_expscale.get(name, 1.0)
        else:
            self._src_expscale[name] = scale
        self._scale_srcmap({name: scale})

Response: Set the exposure correction of a source.


Instruction:
Can you generate the documentation for the following Python 3 function
def set_edisp_flag(self, name, flag=True):
        src = self.roi.get_source_by_name(name)
        name = src.name
        self.like[name].src.set_edisp_flag(flag)

Response: Enable or disable the energy dispersion correction for a specific source.


Instruction:
Given the following Python 3 function, write the documentation
def set_energy_range(self, logemin, logemax):

        if logemin is None:
            logemin = self.log_energies[0]

        if logemax is None:
            logemax = self.log_energies[-1]

        imin = int(utils.val_to_edge(self.log_energies, logemin)[0])
        imax = int(utils.val_to_edge(self.log_energies, logemax)[0])

        if imin - imax == 0:
            imin = int(len(self.log_energies) - 1)
            imax = int(len(self.log_energies) - 1)

        klims = self.like.logLike.klims()
        if imin != klims[0] or imax != klims[1]:
            self.like.selectEbounds(imin, imax)

        return np.array([self.log_energies[imin], self.log_energies[imax]])

Response: Set the energy range of the analysis.


Instruction:
Given the following Python 3 function, write the documentation
def counts_map(self):
        try:
            if isinstance(self.like, gtutils.SummedLikelihood):
                cmap = self.like.components[0].logLike.countsMap()
                p_method = cmap.projection().method()
            else:
                cmap = self.like.logLike.countsMap()
                p_method = cmap.projection().method()
        except Exception:
            p_method = 0

        if p_method == 0:  # WCS
            z = cmap.data()
            z = np.array(z).reshape(self.enumbins, self.npix, self.npix)
            return WcsNDMap(copy.deepcopy(self.geom), z)
        elif p_method == 1:  # HPX
            z = cmap.data()
            z = np.array(z).reshape(self.enumbins, np.max(self.geom.npix))
            return HpxNDMap(copy.deepcopy(self.geom), z)
        else:
            self.logger.error('Did not recognize CountsMap type %i' % p_method,
                              exc_info=True)
        return None

Response: Return 3 - D counts map for this component as a Map object.


Instruction:
Implement a function in Python 3 to
return 3 - D weights map for this component as a Map object.

Response:
def weight_map(self):
        """Return 3-D weights map for this component as a Map object.

        Returns
        -------
        map : `~fermipy.skymap.MapBase`

        """
        # EAC we need the try blocks b/c older versions of the ST don't have some of these functions
        if isinstance(self.like, gtutils.SummedLikelihood):
            cmap = self.like.components[0].logLike.countsMap()
            try:
                p_method = cmap.projection().method()
            except AttributeError:
                p_method = 0
            try:
                if self.like.components[0].logLike.has_weights():
                    wmap = self.like.components[0].logLike.weightMap()
                else:
                    wmap = None
            except Exception:
                wmap = None
        else:
            cmap = self.like.logLike.countsMap()
            try:
                p_method = cmap.projection().method()
            except AttributeError:
                p_method = 0
            try:
                if self.like.logLike.has_weights():
                    wmap = self.like.logLike.weightMap()
                else:
                    wmap = None
            except Exception:
                wmap = None

        if p_method == 0:  # WCS
            if wmap is None:
                z = np.ones((self.enumbins, self.npix, self.npix))
            else:
                z = wmap.model()
                z = np.array(z).reshape(self.enumbins, self.npix, self.npix)
            return WcsNDMap(copy.deepcopy(self._geom), z)
        elif p_method == 1:  # HPX
            nhpix = np.max(self.geom.npix)
            if wmap is None:
                z = np.ones((self.enumbins, nhpix))
            else:
                z = wmap.model()
                z = np.array(z).reshape(self.enumbins, nhpix)
            return HpxNDMap(self.geom, z)
        else:
            self.logger.error('Did not recognize CountsMap type %i' % p_method,
                              exc_info=True)
        return None


Instruction:
How would you explain what the following Python 3 function does
def model_counts_map(self, name=None, exclude=None, use_mask=False):
        if self.projtype == "WCS":
            v = pyLike.FloatVector(self.npix ** 2 * self.enumbins)
        elif self.projtype == "HPX":
            v = pyLike.FloatVector(np.max(self.geom.npix) * self.enumbins)
        else:
            raise Exception("Unknown projection type %s", self.projtype)

        exclude = utils.arg_to_list(exclude)
        names = utils.arg_to_list(name)

        excluded_names = []
        for i, t in enumerate(exclude):
            srcs = self.roi.get_sources_by_name(t)
            excluded_names += [s.name for s in srcs]

        if not hasattr(self.like.logLike, 'loadSourceMaps'):
            # Update fixed model
            self.like.logLike.buildFixedModelWts()
            # Populate source map hash
            self.like.logLike.buildFixedModelWts(True)
        elif (name is None or name == 'all') and not exclude:
            self.like.logLike.loadSourceMaps()

        src_names = []
        if (name is None) or (name == 'all'):
            src_names = [src.name for src in self.roi.sources]
        elif name == 'diffuse':
            src_names = [src.name for src in self.roi.sources if
                         src.diffuse]
        else:
            srcs = [self.roi.get_source_by_name(t) for t in names]
            src_names = [src.name for src in srcs]

        # Remove sources in exclude list
        src_names = [str(t) for t in src_names if t not in excluded_names]

        # EAC we need the try blocks b/c older versions of the ST don't have some of these functions
        if len(src_names) == len(self.roi.sources):
            try:
                self.like.logLike.computeModelMap(v, use_mask)
            except (TypeError, NotImplementedError):
                self.like.logLike.computeModelMap(v)
        elif not hasattr(self.like.logLike, 'setSourceMapImage'):
            for s in src_names:
                model = self.like.logLike.sourceMap(str(s))
                try:
                    self.like.logLike.updateModelMap(v, model, use_mask)
                except (TypeError, NotImplementedError):
                    self.like.logLike.updateModelMap(v, model)
        else:
            try:
                if hasattr(self.like.logLike, 'has_weights'):
                    self.like.logLike.computeModelMap(src_names, v, use_mask)
                else:
                    self.like.logLike.computeModelMap(src_names, v)
            except:
                vsum = np.zeros(v.size())
                for s in src_names:
                    vtmp = pyLike.FloatVector(v.size())
                    if hasattr(self.like.logLike, 'has_weights'):
                        self.like.logLike.computeModelMap(
                            str(s), vtmp, use_mask)
                    else:
                        self.like.logLike.computeModelMap(str(s), vtmp)
                    vsum += vtmp
                v = pyLike.FloatVector(vsum)

        if self.projtype == "WCS":
            z = np.array(v).reshape(self.enumbins, self.npix, self.npix)
            return WcsNDMap(copy.deepcopy(self._geom), z)
        elif self.projtype == "HPX":
            z = np.array(v).reshape(self.enumbins, np.max(self._geom.npix))
            return HpxNDMap(copy.deepcopy(self._geom), z)
        else:
            raise Exception(
                "Did not recognize projection type %s", self.projtype)

Response: Returns the model expectation map for a single source a set of sources or all sources in the ROI.


Instruction:
Can you tell what is the following Python 3 function doing
def model_counts_spectrum(self, name, logemin, logemax, weighted=False):
        # EAC, we need this b/c older version of the ST don't have the right signature
        try:
            cs = np.array(self.like.logLike.modelCountsSpectrum(
                str(name), weighted))
        except (TypeError, NotImplementedError):
            cs = np.array(self.like.logLike.modelCountsSpectrum(str(name)))
        imin = utils.val_to_edge(self.log_energies, logemin)[0]
        imax = utils.val_to_edge(self.log_energies, logemax)[0]
        if imax <= imin:
            raise Exception('Invalid energy range.')
        return cs[imin:imax]

Response: Return the model counts spectrum of a source.


Instruction:
Write a Python 3 script for
running pre-processing step for this component. This will generate all of the auxiliary files needed to instantiate a likelihood object. By default this function will skip any steps for which the output file already exists. Parameters ---------- overwrite : bool Run all pre-processing steps even if the output file of that step is present in the working directory.

Response:
def setup(self, overwrite=False, **kwargs):
        """Run pre-processing step for this component.  This will
        generate all of the auxiliary files needed to instantiate a
        likelihood object.  By default this function will skip any
        steps for which the output file already exists.

        Parameters
        ----------
        overwrite : bool

            Run all pre-processing steps even if the output file of
            that step is present in the working directory.
        """

        loglevel = kwargs.get('loglevel', self.loglevel)

        self.logger.log(loglevel, 'Running setup for component %s',
                        self.name)

        use_external_srcmap = self.config['gtlike']['use_external_srcmap']

        # Run data selection
        if not use_external_srcmap:
            self._select_data(overwrite=overwrite, **kwargs)

        # Create LT Cube
        if self._ext_ltcube is not None:
            self.logger.log(loglevel, 'Using external LT cube.')
        else:
            self._create_ltcube(overwrite=overwrite, **kwargs)

        self.logger.debug('Loading LT Cube %s', self.files['ltcube'])
        self._ltc = LTCube.create(self.files['ltcube'])

        # Extract tmin, tmax from LT cube
        self._tmin = self._ltc.tstart
        self._tmax = self._ltc.tstop

        self.logger.debug('Creating PSF model')
        self._psf = irfs.PSFModel.create(self.roi.skydir, self._ltc,
                                         self.config['gtlike']['irfs'],
                                         self.config['selection']['evtype'],
                                         self.energies)

        # Bin data and create exposure cube
        if not use_external_srcmap:
            self._bin_data(overwrite=overwrite, **kwargs)
            self._create_expcube(overwrite=overwrite, **kwargs)

        # This is needed in case the exposure map is in HEALPix
        hpxhduname = "HPXEXPOSURES"
        try:
            self._bexp = Map.read(self.files['bexpmap'], hdu=hpxhduname)
        except KeyError:
            self._bexp = Map.read(self.files['bexpmap'])

        # Write ROI XML
        self.roi.write_xml(self.files['srcmdl'], self.config['model'])

        # Create source maps file
        if not use_external_srcmap:
            self._create_srcmaps(overwrite=overwrite)

        if not self.config['data']['cacheft1'] and os.path.isfile(self.files['ft1']):
            self.logger.debug('Deleting FT1 file.')
            os.remove(self.files['ft1'])

        self.logger.log(loglevel, 'Finished setup for component %s',
                        self.name)


Instruction:
Explain what the following Python 3 code does
def _scale_srcmap(self, scale_map, check_header=True, names=None):

        srcmap = fits.open(self.files['srcmap'])

        for hdu in srcmap[1:]:
            if hdu.name not in scale_map:
                continue
            if names is not None and hdu.name not in names:
                continue

            scale = scale_map[hdu.name]
            if scale < 1e-20:
                self.logger.warning(
                    "The expscale parameter was zero, setting it to 1e-8")
                scale = 1e-8
            if 'EXPSCALE' in hdu.header and check_header:
                old_scale = hdu.header['EXPSCALE']
            else:
                old_scale = 1.0
            hdu.data *= scale / old_scale
            hdu.header['EXPSCALE'] = (scale,
                                      'Exposure correction applied to this map')

        srcmap.writeto(self.files['srcmap'], overwrite=True)
        srcmap.close()

        # Force reloading the map from disk
        for name in scale_map.keys():
            self.like.logLike.eraseSourceMap(str(name))
        self.like.logLike.buildFixedModelWts()

Response: Apply exposure corrections to the source map file.


Instruction:
How would you implement a function in Python 3 that
makes an exposure cube with the same binning as the counts map.

Response:
def _make_scaled_srcmap(self):
        """Make an exposure cube with the same binning as the counts map."""

        self.logger.info('Computing scaled source map.')

        bexp0 = fits.open(self.files['bexpmap_roi'])
        bexp1 = fits.open(self.config['gtlike']['bexpmap'])
        srcmap = fits.open(self.config['gtlike']['srcmap'])

        if bexp0[0].data.shape != bexp1[0].data.shape:
            raise Exception('Wrong shape for input exposure map file.')

        bexp_ratio = bexp0[0].data / bexp1[0].data

        self.logger.info(
            'Min/Med/Max exposure correction: %f %f %f' % (np.min(bexp_ratio),
                                                           np.median(
                                                               bexp_ratio),
                                                           np.max(bexp_ratio)))

        for hdu in srcmap[1:]:

            if hdu.name == 'GTI':
                continue
            if hdu.name == 'EBOUNDS':
                continue
            hdu.data *= bexp_ratio

        srcmap.writeto(self.files['srcmap'], overwrite=True)


Instruction:
Create a Python 3 function for
simulating the whole ROI or inject a simulation of one or more model components into the data.

Response:
def simulate_roi(self, name=None, clear=True, randomize=True):
        """Simulate the whole ROI or inject a simulation of one or
        more model components into the data.

        Parameters
        ----------
        name : str
           Name of the model component to be simulated.  If None then
           the whole ROI will be simulated.

        clear : bool
           Zero the current counts map before injecting the simulation.

        randomize : bool
           Fill with each pixel with random values drawn from a
           poisson distribution.  If false then fill each pixel with
           the counts expectation value.

        """
        cm = self.counts_map()
        data = cm.data
        m = self.model_counts_map(name)

        if clear:
            data.fill(0.0)

        if randomize:
            if m.data.min()<0.:
                self.logger.warning('At least on negative value found in model map.'
                                    ' Changing it/them to 0')
                indexcond = np.where( m.data <0. )
                m.data[indexcond]=np.zeros(len(m.data[indexcond]))

            data += np.random.poisson(m.data).astype(float)
        else:
            data += m.data

        if hasattr(self.like.logLike, 'setCountsMap'):
            self.like.logLike.setCountsMap(np.ravel(data))

        srcmap_utils.update_source_maps(self.files['srcmap'],
                                        {'PRIMARY': data},
                                        logger=self.logger)
        cm.write(self.files['ccubemc'], overwrite=True, conv='fgst-ccube')


Instruction:
Can you tell what is the following Python 3 function doing
def write_model_map(self, model_name=None, name=None):

        if model_name is None:
            suffix = self.config['file_suffix']
        else:
            suffix = '_%s%s' % (model_name, self.config['file_suffix'])

        self.logger.info('Generating model map for component %s.', self.name)

        outfile = os.path.join(self.config['fileio']['workdir'],
                               'mcube%s.fits' % (suffix))

        cmap = self.model_counts_map(name, use_mask=False)
        cmap.write(outfile, overwrite=True, conv='fgst-ccube')
        return cmap

Response: Save counts model map to a FITS file.


Instruction:
Create a Python 3 function for
saving counts model map to a FITS file.

Response:
def write_weight_map(self, model_name=None):
        """Save counts model map to a FITS file.

        """

        if model_name is None:
            suffix = self.config['file_suffix']
        else:
            suffix = '_%s%s' % (model_name, self.config['file_suffix'])

        self.logger.info('Generating model map for component %s.', self.name)

        outfile = os.path.join(self.config['fileio']['workdir'],
                               'wcube%s.fits' % (suffix))

        wmap = self.weight_map()
        wmap.write(outfile, overwrite=True, conv='fgst-ccube')
        return wmap


Instruction:
How would you code a function in Python 3 to
update the contents of the source map file and generate source maps for any components that are not present.

Response:
def _update_srcmap_file(self, sources, overwrite=True):
        """Check the contents of the source map file and generate
        source maps for any components that are not present."""

        if not os.path.isfile(self.files['srcmap']):
            return

        hdulist = fits.open(self.files['srcmap'])
        hdunames = [hdu.name.upper() for hdu in hdulist]

        srcmaps = {}

        for src in sources:

            if src.name.upper() in hdunames and not overwrite:
                continue
            self.logger.debug('Creating source map for %s', src.name)
            srcmaps[src.name] = self._create_srcmap(src.name, src)

        if srcmaps:
            self.logger.debug(
                'Updating source map file for component %s.', self.name)
            srcmap_utils.update_source_maps(self.files['srcmap'], srcmaps,
                                            logger=self.logger)
        hdulist.close()


Instruction:
Implement a function in Python 3 to
generate the source map for a source.

Response:
def _create_srcmap(self, name, src, **kwargs):
        """Generate the source map for a source."""

        psf_scale_fn = kwargs.get('psf_scale_fn', None)
        skydir = src.skydir
        spatial_model = src['SpatialModel']
        spatial_width = src['SpatialWidth']
        xpix, ypix = self.geom.to_image().coord_to_pix(skydir)
        exp = self._bexp.interp_by_coord(
            (skydir, self._bexp.geom.axes[0].center))
        cache = self._srcmap_cache.get(name, None)
        if cache is not None:
            k = cache.create_map([ypix, xpix])
        else:
            k = srcmap_utils.make_srcmap(self._psf, exp, spatial_model,
                                         spatial_width,
                                         npix=self.npix, xpix=xpix, ypix=ypix,
                                         cdelt=self.config['binning']['binsz'],
                                         psf_scale_fn=psf_scale_fn,
                                         sparse=True)

        return k


Instruction:
Write a Python 3 script to
update the source map for an existing source in memory.

Response:
def _update_srcmap(self, name, src, **kwargs):
        """Update the source map for an existing source in memory."""

        k = self._create_srcmap(name, src, **kwargs)
        scale = self._src_expscale.get(name, 1.0)
        k *= scale

        # Force the source map to be cached
        # FIXME: No longer necessary to force cacheing in ST after 11-05-02
        self.like.logLike.sourceMap(str(name)).model()
        self.like.logLike.setSourceMapImage(str(name), np.ravel(k))
        self.like.logLike.sourceMap(str(name)).model()

        normPar = self.like.normPar(name)
        if not normPar.isFree():
            self.like.logLike.buildFixedModelWts()


Instruction:
Write a Python 3 script for
generating a counts model map from an XML model file using the GT model.

Response:
def generate_model(self, model_name=None, outfile=None):
        """Generate a counts model map from an XML model file using
        gtmodel.

        Parameters
        ----------
        model_name : str
            Name of the model.  If no name is given it will use the
            baseline model.

        outfile : str
            Override the name of the output model file.
        """

        if model_name is not None:
            model_name = os.path.splitext(model_name)[0]

        if model_name is None or model_name == '':
            srcmdl = self.files['srcmdl']
        else:
            srcmdl = self.get_model_path(model_name)

        if not os.path.isfile(srcmdl):
            raise Exception("Model file does not exist: %s", srcmdl)

        if model_name is None:
            suffix = self.config['file_suffix']
        else:
            suffix = '_%s%s' % (model_name, self.config['file_suffix'])

        outfile = os.path.join(self.config['fileio']['workdir'],
                               'mcube%s.fits' % (suffix))

        # May consider generating a custom source model file
        if not os.path.isfile(outfile):

            kw = dict(srcmaps=self.files['srcmap'],
                      srcmdl=srcmdl,
                      bexpmap=self.files['bexpmap'],
                      outfile=outfile,
                      expcube=self.files['ltcube'],
                      irfs=self.config['gtlike']['irfs'],
                      evtype=self.config['selection']['evtype'],
                      edisp=bool(self.config['gtlike']['edisp']),
                      outtype='ccube',
                      chatter=self.config['logging']['chatter'])

            run_gtapp('gtmodel', self.logger, kw)
        else:
            self.logger.info('Skipping gtmodel')


Instruction:
Can you tell what is the following Python 3 function doing
def write_xml(self, xmlfile):

        xmlfile = self.get_model_path(xmlfile)
        self.logger.info('Writing %s...', xmlfile)
        self.like.writeXml(str(xmlfile))

Response: Write the XML model for this analysis component.


Instruction:
Create a Python 3 function to
infer the path to the XML model name.

Response:
def get_model_path(self, name):
        """Infer the path to the XML model name."""

        name, ext = os.path.splitext(name)
        ext = '.xml'
        xmlfile = name + self.config['file_suffix'] + ext
        xmlfile = utils.resolve_path(xmlfile,
                                     workdir=self.config['fileio']['workdir'])

        return xmlfile


Instruction:
How would you explain what the following Python 3 function does
def _tscube_app(self, xmlfile):

        xmlfile = self.get_model_path(xmlfile)

        outfile = os.path.join(self.config['fileio']['workdir'],
                               'tscube%s.fits' % (self.config['file_suffix']))

        kw = dict(cmap=self.files['ccube'],
                  expcube=self.files['ltcube'],
                  bexpmap=self.files['bexpmap'],
                  irfs=self.config['gtlike']['irfs'],
                  evtype=self.config['selection']['evtype'],
                  srcmdl=xmlfile,
                  nxpix=self.npix, nypix=self.npix,
                  binsz=self.config['binning']['binsz'],
                  xref=float(self.roi.skydir.ra.deg),
                  yref=float(self.roi.skydir.dec.deg),
                  proj=self.config['binning']['proj'],
                  stlevel=0,
                  coordsys=self.config['binning']['coordsys'],
                  outfile=outfile)

        run_gtapp('gttscube', self.logger, kw)

Response: Run gttscube as an application.


Instruction:
Create a Python 3 function to
compute the diffuse response

Response:
def _diffrsp_app(self,xmlfile=None, **kwargs):
        """
        Compute the diffuse response
        """
        loglevel = kwargs.get('loglevel', self.loglevel)

        self.logger.log(loglevel, 'Computing diffuse repsonce for component %s.',
                        self.name)

        # set the srcmdl
        srcmdl_file = self.files['srcmdl']
        if xmlfile is not None:
            srcmdl_file = self.get_model_path(xmlfile)

        kw = dict(evfile=self.files['ft1'],
            scfile=self.data_files['scfile'],
            irfs = self.config['gtlike']['irfs'],
            evtype = self.config['selection']['evtype'],
            srcmdl = srcmdl_file)

        run_gtapp('gtdiffrsp', self.logger, kw, loglevel=loglevel)
        return


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _srcprob_app(self,xmlfile=None, overwrite=False, **kwargs):

        loglevel = kwargs.get('loglevel', self.loglevel)

        self.logger.log(loglevel, 'Computing src probability for component %s.',
                        self.name)

        # set the srcmdl
        srcmdl_file = self.files['srcmdl']
        if xmlfile is not None:
            srcmdl_file = self.get_model_path(xmlfile)

        # set the outfile
        # it's defined here and not in self.files dict
        # so that it is copied with the stage_output module
        # even if savefits is False
        outfile = os.path.join(self.workdir,
                    'ft1_srcprob{0[file_suffix]:s}.fits'.format(self.config))

        kw = dict(evfile=self.files['ft1'],
            scfile=self.data_files['scfile'],
            outfile= outfile,
            irfs = self.config['gtlike']['irfs'],
            srcmdl = srcmdl_file)
        self.logger.debug(kw)

        # run gtapp for the srcprob
        if os.path.isfile(outfile) and not overwrite:
            self.logger.info('Skipping gtsrcprob')
        else:
            run_gtapp('gtsrcprob', self.logger, kw, loglevel=loglevel)

Response: Run srcprob for an analysis component as an application.


Instruction:
Implement a Python 3 function for
removing null items from a dictionary

Response:
def purge_dict(idict):
    """Remove null items from a dictionary """
    odict = {}
    for key, val in idict.items():
        if is_null(val):
            continue
        odict[key] = val
    return odict


Instruction:
Here you have a function in Python 3, explain what it does
def main(cls):
        chain = cls.create()
        args = chain._run_argparser(sys.argv[1:])
        chain._run_chain(sys.stdout, args.dry_run)
        chain._finalize(args.dry_run)

Response: Hook to run this Chain from the command line


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _latch_file_info(self):
        self._map_arguments(self.args)
        self.files.latch_file_info(self.args)
        self.sub_files.file_dict.clear()
        self.sub_files.update(self.files.file_dict)
        for link in self._links.values():
            self.sub_files.update(link.files.file_dict)
            self.sub_files.update(link.sub_files.file_dict)

Response: Internal function to update the dictionaries holding the input and output files and the output files.


Instruction:
Can you tell what is the following Python 3 function doing
def _set_link(self, linkname, cls, **kwargs):
        val_copy = purge_dict(kwargs.copy())
        sub_link_prefix = val_copy.pop('link_prefix', '')
        link_prefix = self.link_prefix + sub_link_prefix
        create_args = dict(linkname=linkname,
                           link_prefix=link_prefix,
                           job_archive=val_copy.pop('job_archive', None),
                           file_stage=val_copy.pop('file_stage', None))
        job_args = val_copy
        if linkname in self._links:
            link = self._links[linkname]
            link.update_args(job_args)
        else:
            link = cls.create(**create_args)
            self._links[link.linkname] = link
            logfile_default = os.path.join('logs', '%s.log' % link.full_linkname)
            logfile = kwargs.setdefault('logfile', logfile_default)
            link._register_job(JobDetails.topkey, job_args,
                               logfile, status=JobStatus.unknown)
        return link

Response: Transfer options kwargs to a Link object if needed.


Instruction:
How would you implement a function in Python 3 that
passes self. _job_archive along to links

Response:
def _set_links_job_archive(self):
        """Pass self._job_archive along to links"""
        for link in self._links.values():
            link._job_archive = self._job_archive


Instruction:
Write a Python 3 script to
run all the links in the chain and returns the base class of the base class.

Response:
def _run_chain(self,
                   stream=sys.stdout,
                   dry_run=False,
                   stage_files=True,
                   force_run=False,
                   resubmit_failed=False):
        """Run all the links in the chain

        Parameters
        -----------
        stream : `file`
            Stream to print to,
            Must have 'write' function

        dry_run : bool
            Print commands but do not run them

        stage_files : bool
            Stage files to and from the scratch area

        force_run : bool
            Run jobs, even if they are marked as done

        resubmit_failed : bool
            Resubmit failed jobs

        """
        self._set_links_job_archive()
        failed = False

        if self._file_stage is not None:
            input_file_mapping, output_file_mapping = self._map_scratch_files(
                self.sub_files)
            if stage_files:
                self._file_stage.make_scratch_dirs(input_file_mapping, dry_run)
                self._file_stage.make_scratch_dirs(
                    output_file_mapping, dry_run)
                self._stage_input_files(input_file_mapping, dry_run)

        for link in self._links.values():
            logfile = os.path.join('logs', "%s.log" % link.full_linkname)
            link._archive_self(logfile, status=JobStatus.unknown)
            key = JobDetails.make_fullkey(link.full_linkname)
            if hasattr(link, 'check_status'):
                link.check_status(stream, no_wait=True,
                                  check_once=True, do_print=False)
            else:
                pass
            link_status = link.check_job_status(key)
            if link_status in [JobStatus.done]:
                if not force_run:
                    print ("Skipping done link", link.full_linkname)
                    continue
            elif link_status in [JobStatus.running]:
                if not force_run and not resubmit_failed:
                    print ("Skipping running link", link.full_linkname)
                    continue
            elif link_status in [JobStatus.failed,
                                 JobStatus.partial_failed]:
                if not resubmit_failed:
                    print ("Skipping failed link", link.full_linkname)
                    continue
            print ("Running link ", link.full_linkname)
            link.run_with_log(dry_run=dry_run, stage_files=False,
                              resubmit_failed=resubmit_failed)
            link_status = link.check_jobs_status()
            link._set_status_self(status=link_status)
            if link_status in [JobStatus.failed, JobStatus.partial_failed]:
                print ("Stoping chain execution at failed link %s" %
                       link.full_linkname)
                failed = True
                break
#            elif link_status in [JobStatus.partial_failed]:
#                print ("Resubmitting partially failed link %s" %
#                       link.full_linkname)
#                link.run_with_log(dry_run=dry_run, stage_files=False,
#                                  resubmit_failed=resubmit_failed)
#                link_status = link.check_jobs_status()
#                link._set_status_self(status=link_status)
#                if link_status in [JobStatus.partial_failed]:
#                    print ("Stoping chain execution: resubmission failed %s" %
#                           link.full_linkname)
#                    failed = True
#                    break

        if self._file_stage is not None and stage_files and not failed:
            self._stage_output_files(output_file_mapping, dry_run)

        chain_status = self.check_links_status()
        print ("Chain status: %s" % (JOB_STATUS_STRINGS[chain_status]))
        if chain_status == 5:
            job_status = 0
        else:
            job_status = -1
        self._write_status_to_log(job_status, stream)
        self._set_status_self(status=chain_status)

        if self._job_archive:
            self._job_archive.file_archive.update_file_status()
            self._job_archive.write_table_file()


Instruction:
Can you implement a function in Python 3 that
clears all the jobs in this instance.

Response:
def clear_jobs(self, recursive=True):
        """Clear a dictionary with all the jobs

        If recursive is True this will include jobs from all internal `Link`
        """
        if recursive:
            for link in self._links.values():
                link.clear_jobs(recursive)
        self.jobs.clear()


Instruction:
How would you code a function in Python 3 to
return a dictionary with all the jobs in this instance.

Response:
def get_jobs(self, recursive=True):
        """Return a dictionary with all the jobs

        If recursive is True this will include jobs from all internal `Link`
        """
        if recursive:
            ret_dict = self.jobs.copy()
            for link in self._links.values():
                ret_dict.update(link.get_jobs(recursive))
            return ret_dict
        return self.jobs


Instruction:
How would you explain what the following Python 3 function does
def missing_input_files(self):
        ret_dict = OrderedDict()
        for link in self._links.values():
            link_dict = link.missing_input_files()
            for key, value in link_dict.items():
                try:
                    ret_dict[key] += value
                except KeyError:
                    ret_dict[key] = value
        return ret_dict

Response: Make and return a dictionary of the missing input files. This returns a dictionary mapping the filepath to list of Link that use the file as input.


Instruction:
Write a Python 3 script for
checking the status of all the jobs run from the ialog objects in this Chain and return a status flag that summarizes that.

Response:
def check_links_status(self,
                           fail_running=False,
                           fail_pending=False):
        """"Check the status of all the jobs run from the
        `Link` objects in this `Chain` and return a status
        flag that summarizes that.

        Parameters
        ----------

        fail_running : `bool`
            If True, consider running jobs as failed

        fail_pending : `bool`
            If True, consider pending jobs as failed

        Returns
        -------
        status : `JobStatus`
            Job status flag that summarizes the status of all the jobs,

        """
        status_vector = JobStatusVector()
        for link in self._links.values():
            key = JobDetails.make_fullkey(link.full_linkname)
            link_status = link.check_job_status(key,
                                                fail_running=fail_running,
                                                fail_pending=fail_pending)
            status_vector[link_status] += 1

        return status_vector.get_status()


Instruction:
Explain what the following Python 3 code does
def run(self, stream=sys.stdout, dry_run=False,
            stage_files=True, resubmit_failed=False):
        """Runs this `Chain`.

        Parameters
        -----------
        stream : `file`
            Stream that this `Link` will print to,
            Must have 'write' function

        dry_run : bool
            Print command but do not run it.

        stage_files : bool
            Copy files to and from scratch staging area.

        resubmit_failed : bool
            Flag for sub-classes to resubmit failed jobs.

        """
        self._run_chain(stream, dry_run, stage_files,
                        resubmit_failed=resubmit_failed)

Response:
Runs this `Chain`.

        Parameters
        -----------
        stream : `file`
            Stream that this `Link` will print to,
            Must have 'write' function

        dry_run : bool
            Print command but do not run it.

        stage_files : bool
            Copy files to and from scratch staging area.

        resubmit_failed : bool
            Flag for sub-classes to resubmit failed jobs.


Instruction:
Write a Python 3 function that can
update the argument used to invoke the application.

Response:
def update_args(self, override_args):
        """Update the argument used to invoke the application

        Note that this will also update the dictionary of input
        and output files.

        Parameters
        -----------
        override_args : dict
            dictionary passed to the links

        """
        self.args = extract_arguments(override_args, self.args)
        self._map_arguments(self.args)

        scratch_dir = self.args.get('scratch', None)
        if is_not_null(scratch_dir):
            self._file_stage = FileStageManager(scratch_dir, '.')
        for link in self._links.values():
            link._set_file_stage(self._file_stage)
        self._latch_file_info()


Instruction:
Can you generate a brief explanation for the following Python 3 code
def print_status(self, indent="", recurse=False):
        print ("%s%30s : %15s : %20s" %
               (indent, "Linkname", "Link Status", "Jobs Status"))
        for link in self._links.values():
            if hasattr(link, 'check_status'):
                status_vect = link.check_status(
                    stream=sys.stdout, no_wait=True, do_print=False)
            else:
                status_vect = None
            key = JobDetails.make_fullkey(link.full_linkname)
            link_status = JOB_STATUS_STRINGS[link.check_job_status(key)]
            if status_vect is None:
                jobs_status = JOB_STATUS_STRINGS[link.check_jobs_status()]
            else:
                jobs_status = status_vect
            print ("%s%30s : %15s : %20s" %
                   (indent, link.linkname, link_status, jobs_status))
            if hasattr(link, 'print_status') and recurse:
                print ("----------   %30s    -----------" % link.linkname)
                link.print_status(indent + "  ", recurse=True)
                print ("------------------------------------------------")

Response: Print a summary of the job status for each Link in this Chain


Instruction:
Explain what the following Python 3 code does
def print_summary(self, stream=sys.stdout, indent="", recurse_level=2):
        Link.print_summary(self, stream, indent, recurse_level)
        if recurse_level > 0:
            recurse_level -= 1
            indent += "  "
            for link in self._links.values():
                stream.write("\n")
                link.print_summary(stream, indent, recurse_level)

Response: Print a summary of the activity done by this Chain.


Instruction:
Given the following Python 3 function, write the documentation
def register_classes():
    Gtlink_exphpsun.register_class()
    Gtlink_suntemp.register_class()
    Gtexphpsun_SG.register_class()
    Gtsuntemp_SG.register_class()
    SunMoonChain.register_class()

Response: Register these classes with the LinkFactory


Instruction:
Here you have a function in Python 3, explain what it does
def build_job_configs(self, args):
        job_configs = {}

        components = Component.build_from_yamlfile(args['comp'])
        NAME_FACTORY.update_base_dict(args['data'])

        mktime = args['mktimefilter']

        base_config = dict(nxpix=args['nxpix'],
                           nypix=args['nypix'],
                           binsz=args['binsz'])

        for comp in components:
            zcut = "zmax%i" % comp.zmax
            key = comp.make_key('{ebin_name}_{evtype_name}')
            name_keys = dict(zcut=zcut,
                             ebin=comp.ebin_name,
                             psftype=comp.evtype_name,
                             irf_ver=NAME_FACTORY.irf_ver(),
                             coordsys=comp.coordsys,
                             mktime=mktime,
                             fullpath=True)
            outfile = NAME_FACTORY.bexpcube(**name_keys)
            ltcube = NAME_FACTORY.ltcube(**name_keys)
            full_config = base_config.copy()
            full_config.update(dict(infile=ltcube,
                                    outfile=outfile,
                                    irfs=NAME_FACTORY.irfs(**name_keys),
                                    evtype=comp.evtype,
                                    emin=comp.emin,
                                    emax=comp.emax,
                                    enumbins=comp.enumbins,
                                    logfile=make_nfs_path(outfile.replace('.fits', '.log'))))
            job_configs[key] = full_config

        return job_configs

Response: Hook to build job configurations from the arguments passed in.


Instruction:
Can you write a function in Python 3 where it
hooks to build job configurations from the given arguments

Response:
def build_job_configs(self, args):
        """Hook to build job configurations
        """
        job_configs = {}

        components = Component.build_from_yamlfile(args['comp'])
        NAME_FACTORY.update_base_dict(args['data'])

        mktime = args['mktimefilter']

        for comp in components:
            zcut = "zmax%i" % comp.zmax
            key = comp.make_key('{ebin_name}_{evtype_name}')
            name_keys = dict(zcut=zcut,
                             ebin=comp.ebin_name,
                             psftype=comp.evtype_name,
                             irf_ver=NAME_FACTORY.irf_ver(),
                             mktime=mktime,
                             fullpath=True)
            outfile = NAME_FACTORY.bexpcube_sun(**name_keys)
            ltcube_sun = NAME_FACTORY.ltcube_sun(**name_keys)
            job_configs[key] = dict(infile=NAME_FACTORY.ltcube_sun(**name_keys),
                                    outfile=outfile,
                                    irfs=NAME_FACTORY.irfs(**name_keys),
                                    evtype=comp.evtype,
                                    emin=comp.emin,
                                    emax=comp.emax,
                                    enumbins=comp.enumbins,
                                    logfile=make_nfs_path(outfile.replace('.fits', '.log')))

        return job_configs


Instruction:
Write a Python 3 script for
hooking to build job configurations from the arguments passed in.

Response:
def build_job_configs(self, args):
        """Hook to build job configurations
        """
        job_configs = {}

        components = Component.build_from_yamlfile(args['comp'])
        NAME_FACTORY.update_base_dict(args['data'])

        # FIXME
        mktime = args['mktimefilter']

        for comp in components:
            for sourcekey in args['sourcekeys']:
                zcut = "zmax%i" % comp.zmax
                key = comp.make_key('{ebin_name}_{evtype_name}') + "_%s" % sourcekey
                name_keys = dict(zcut=zcut,
                                 ebin=comp.ebin_name,
                                 psftype=comp.evtype_name,
                                 irf_ver=NAME_FACTORY.irf_ver(),
                                 sourcekey=sourcekey,
                                 mktime=mktime,
                                 coordsys=comp.coordsys,
                                 fullpath=True)
                outfile = NAME_FACTORY.template_sunmoon(**name_keys)
                job_configs[key] = dict(expsun=NAME_FACTORY.bexpcube_sun(**name_keys),
                                        avgexp=NAME_FACTORY.bexpcube(**name_keys),
                                        sunprof=NAME_FACTORY.angprofile(**name_keys),
                                        cmap='none',
                                        outfile=outfile,
                                        irfs=NAME_FACTORY.irfs(**name_keys),
                                        evtype=comp.evtype,
                                        emin=comp.emin,
                                        emax=comp.emax,
                                        enumbins=comp.enumbins,
                                        logfile=outfile.replace('.fits', '.log'))

        return job_configs


Instruction:
Write a Python 3 script for
mapping from the top - level arguments to the arguments provided to the indiviudal links

Response:
def _map_arguments(self, input_dict):
        """Map from the top-level arguments to the arguments provided to
        the indiviudal links """

        config_yaml = input_dict['config']
        config_dict = load_yaml(config_yaml)

        data = config_dict.get('data')
        comp = config_dict.get('comp')
        sourcekeys = config_dict.get('sourcekeys')

        mktimefilter = config_dict.get('mktimefilter')

        self._set_link('expcube2', Gtexpcube2wcs_SG,
                       comp=comp, data=data,
                       mktimefilter=mktimefilter)

        self._set_link('exphpsun', Gtexphpsun_SG,
                       comp=comp, data=data,
                       mktimefilter=mktimefilter)

        self._set_link('suntemp', Gtsuntemp_SG,
                       comp=comp, data=data,
                       mktimefilter=mktimefilter,
                       sourcekeys=sourcekeys)


Instruction:
Create a Python 3 function to
return the information about a particular sub - component

Response:
def get_component_info(self, comp):
        """Return the information about sub-component specific to a particular data selection

        Parameters
        ----------

        comp : `binning.Component` object
            Specifies the sub-component

        Returns `ModelComponentInfo` object
        """
        if self.components is None:
            raise ValueError(
                'Model component %s does not have sub-components' % self.sourcekey)
        if self.moving:
            comp_key = "zmax%i" % (comp.zmax)
        elif self.selection_dependent:
            comp_key = comp.make_key('{ebin_name}_{evtype_name}')
        else:
            raise ValueError(
                'Model component %s is not moving or selection dependent' % self.sourcekey)
        return self.components[comp_key]


Instruction:
How would you explain what the following Python 3 function does
def add_component_info(self, compinfo):
        if self.components is None:
            self.components = {}
        self.components[compinfo.comp_key] = compinfo

Response: Add sub - component specific information to a particular data selection.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def clone_and_merge_sub(self, key):
        new_comp = copy.deepcopy(self)
        #sub_com = self.components[key]
        new_comp.components = None
        new_comp.comp_key = key
        return new_comp

Response: Clones self and merges clone with sub - component specific information.


Instruction:
Here you have a function in Python 3, explain what it does
def add_columns(t0, t1):

    for colname in t1.colnames:
        col = t1.columns[colname]
        if colname in t0.columns:
            continue
        new_col = Column(name=col.name, length=len(t0), dtype=col.dtype)  # ,
        # shape=col.shape)
        t0.add_column(new_col)

Response: Add columns of table t1 to table t0.


Instruction:
Write a Python 3 function that can
perform a join of two tables.

Response:
def join_tables(left, right, key_left, key_right,
                cols_right=None):
    """Perform a join of two tables.

    Parameters
    ----------
    left : `~astropy.Table`
        Left table for join.

    right : `~astropy.Table`
        Right table for join.

    key_left : str
        Key used to match elements from ``left`` table.

    key_right : str
        Key used to match elements from ``right`` table.

    cols_right : list
        Subset of columns from ``right`` table that will be appended
        to joined table.

    """
    right = right.copy()

    if cols_right is None:
        cols_right = right.colnames
    else:
        cols_right = [c for c in cols_right if c in right.colnames]

    if key_left != key_right:
        right[key_right].name = key_left

    if key_left not in cols_right:
        cols_right += [key_left]

    out = join(left, right[cols_right], keys=key_left,
               join_type='left')

    for col in out.colnames:
        if out[col].dtype.kind in ['S', 'U']:
            out[col].fill_value = ''
        elif out[col].dtype.kind in ['i']:
            out[col].fill_value = 0
        else:
            out[col].fill_value = np.nan

    return out.filled()


Instruction:
Write a Python 3 function for
stripping whitespace from string columns.

Response:
def strip_columns(tab):
    """Strip whitespace from string columns."""
    for colname in tab.colnames:
        if tab[colname].dtype.kind in ['S', 'U']:
            tab[colname] = np.core.defchararray.strip(tab[colname])


Instruction:
Here you have a function in Python 3, explain what it does
def row_to_dict(row):
    o = {}
    for colname in row.colnames:

        if isinstance(row[colname], np.string_) and row[colname].dtype.kind in ['S', 'U']:
            o[colname] = str(row[colname])
        else:
            o[colname] = row[colname]

    return o

Response: Convert a table row to a dictionary.


Instruction:
Implement a Python 3 function for
hooking to build job configurations from the given arguments.

Response:
def build_job_configs(self, args):
        """Hook to build job configurations
        """
        job_configs = {}

        components = Component.build_from_yamlfile(args['comp'])
        NAME_FACTORY.update_base_dict(args['data'])
        ret_dict = make_catalog_comp_dict(sources=args['library'], basedir='.')
        comp_info_dict = ret_dict['comp_info_dict']

        for split_ver, split_dict in comp_info_dict.items():
            for source_key, source_dict in split_dict.items():
                full_key = "%s_%s" % (split_ver, source_key)
                merged_name = "%s_%s" % (source_dict.catalog_info.catalog_name, source_key)
                if source_dict.model_type != 'CompositeSource':
                    continue

                for comp in components:
                    zcut = "zmax%i" % comp.zmax
                    key = "%s_%s" % (full_key, comp.make_key('{ebin_name}_{evtype_name}'))
                    name_keys = dict(zcut=zcut,
                                     sourcekey=full_key,
                                     ebin=comp.ebin_name,
                                     psftype=comp.evtype_name,
                                     coordsys=comp.coordsys,
                                     mktime='none',
                                     irf_ver=NAME_FACTORY.irf_ver())
                    nested_name_keys = dict(zcut=zcut,
                                            sourcekey=source_dict.catalog_info.catalog_name,
                                            ebin=comp.ebin_name,
                                            psftype=comp.evtype_name,
                                            coordsys=comp.coordsys,
                                            mktime='none',
                                            irf_ver=NAME_FACTORY.irf_ver())
                    outfile = NAME_FACTORY.srcmaps(**name_keys)
                    logfile = make_nfs_path(outfile.replace('.fits', '.log'))
                    job_configs[key] = dict(srcmaps=NAME_FACTORY.srcmaps(**nested_name_keys),
                                            expcube=NAME_FACTORY.ltcube(**name_keys),
                                            irfs=NAME_FACTORY.irfs(**name_keys),
                                            bexpmap=NAME_FACTORY.bexpcube(**name_keys),
                                            srcmdl=NAME_FACTORY.srcmdl_xml(**name_keys),
                                            merged=merged_name,
                                            outfile=outfile,
                                            outxml=NAME_FACTORY.nested_srcmdl_xml(**name_keys),
                                            logfile=logfile)

        return job_configs


Instruction:
Can you generate the documentation for the following Python 3 function
def check_log(logfile, exited='Exited with exit code',
              successful='Successfully completed', exists=True):
    """ Often logfile doesn't exist because the job hasn't begun
    to run. It is unclear what you want to do in that case...

    Parameters
    ----------
    logfile : str
        String with path to logfile
    exists  : bool
        Is the logfile required to exist
    exited  : str
        String in logfile used to determine if a job exited.
    successful : str
        String in logfile used to determine if a job succeeded.

    """
    if not os.path.exists(logfile):
        return not exists

    if exited in open(logfile).read():
        return 'Exited'
    elif successful in open(logfile).read():
        return 'Successful'
    else:
        return 'None'

Response: Check if a log file exists and if it exists return None if it doesn t.


Instruction:
Explain what the following Python 3 code does
def dispatch_job(jobname, exe, args, opts, batch_opts, dry_run=True):

    batch_opts.setdefault('W', 300)
    batch_opts.setdefault('R', 'rhel60 && scratch > 10')

    cmd_opts = ''
    for k, v in opts.items():

        if isinstance(v, list):
            cmd_opts += ' '.join(['--%s=%s' % (k, t) for t in v])
        elif isinstance(v, bool) and v:
            cmd_opts += ' --%s ' % (k)
        elif isinstance(v, bool):
            continue
        elif v is not None:
            cmd_opts += ' --%s=\"%s\" ' % (k, v)

    bash_script = "{exe} {args} {opts}"
    scriptexe = jobname + '.sh'
    with open(os.path.join(scriptexe), 'wt') as f:
        f.write(bash_script.format(exe=exe, args=' '.join(args),
                                   opts=cmd_opts))

    batch_optstr = parse_lsf_opts(**batch_opts)
    batch_cmd = 'bsub %s ' % (batch_optstr)
    batch_cmd += ' bash %s' % scriptexe
    print(batch_cmd)
    if not dry_run:
        os.system(batch_cmd)

Response: Dispatch an LSF job.


Instruction:
Here you have a function in Python 3, explain what it does
def _make_input_file_list(binnedfile, num_files):
    outdir_base = os.path.abspath(os.path.dirname(binnedfile))
    outbasename = os.path.basename(binnedfile)
    filelist = ""
    for i in range(num_files):
        split_key = "%06i" % i
        output_dir = os.path.join(outdir_base, split_key)
        filepath = os.path.join(output_dir,
                                outbasename.replace('.fits', '_%s.fits' % split_key))
        filelist += ' %s' % filepath
    return filelist

Response: Make the list of input files for a particular energy bin X psf type


Instruction:
How would you code a function in Python 3 to
map from the top - level arguments to the arguments provided to the indiviudal links

Response:
def _map_arguments(self, args):
        """Map from the top-level arguments to the arguments provided to
        the indiviudal links """
        comp_file = args.get('comp', None)
        datafile = args.get('data', None)
        do_ltsum = args.get('do_ltsum', False)

        NAME_FACTORY.update_base_dict(datafile)
        outdir_base = os.path.join(NAME_FACTORY.base_dict['basedir'], 'counts_cubes')
        num_files = args.get('nfiles', 96)

        self.comp_dict = yaml.safe_load(open(comp_file))
        coordsys = self.comp_dict.pop('coordsys')

        for key_e, comp_e in sorted(self.comp_dict.items()):

            if 'mktimefilters' in comp_e:
                mktimelist = comp_e['mktimefilters']
            else:
                mktimelist = ['none']

            if 'evtclasses' in comp_e:
                evtclasslist_vals = comp_e['evtclasses']
            else:
                evtclasslist_vals = [NAME_FACTORY.base_dict['evclass']]

            for mktimekey in mktimelist:
                zcut = "zmax%i" % comp_e['zmax']
                kwargs_mktime = dict(zcut=zcut,
                                     ebin=key_e,
                                     psftype='ALL',
                                     coordsys=coordsys,
                                     mktime=mktimekey)

                if do_ltsum:
                    ltsum_listfile = 'ltsumlist_%s_%s' % (key_e, mktimekey)
                    ltsum_outfile = 'ltsum_%s_%s' % (key_e, mktimekey)
                    linkname = 'ltsum_%s_%s' % (key_e, mktimekey)
                    self._set_link(likname, Gtlink_ltsum,
                                   infile1=ltsum_listfile,
                                   infile2=None,
                                   outfile=ltsum_outfile,
                                   logfile=os.path.join(outdir_base, "%s.log" % linkname))

                for evtclassval in evtclasslist_vals:
                    for psf_type in sorted(comp_e['psf_types'].keys()):
                        fullkey = "%s_%s_%s_%s"%(key_e, mktimekey, evtclassval, psf_type)
                        linkname = 'coadd_%s' % (fullkey)
                        kwargs_bin = kwargs_mktime.copy()
                        kwargs_bin['psftype'] = psf_type
                        kwargs_bin['evclass'] = evtclassval
                        ccube_name =\
                            os.path.basename(NAME_FACTORY.ccube(**kwargs_bin))
                        outputfile = os.path.join(outdir_base, ccube_name)
                        args = _make_input_file_list(outputfile, num_files)

                        self._set_link(linkname,
                                       Link_FermipyCoadd,
                                       args=args,
                                       output=outputfile,
                                       logfile=os.path.join(outdir_base, "%s.log" % linkname))


Instruction:
Write a Python 3 function that can
hook to build job configurations from a YAML file.

Response:
def build_job_configs(self, args):
        """Hook to build job configurations
        """
        job_configs = {}

        components = Component.build_from_yamlfile(args['comp'])

        datafile = args['data']
        if datafile is None or datafile == 'None':
            return job_configs
        NAME_FACTORY.update_base_dict(args['data'])
        outdir_base = os.path.join(NAME_FACTORY.base_dict['basedir'], 'counts_cubes')

        inputfiles = create_inputlist(args['ft1file'])
        num_files = len(inputfiles)

        for comp in components:
            zcut = "zmax%i" % comp.zmax

            mktimelist = copy.copy(comp.mktimefilters)
            if not mktimelist:
                mktimelist.append('none')
            evtclasslist_keys = copy.copy(comp.evtclasses)
            if not evtclasslist_keys:
                evtclasslist_vals = [NAME_FACTORY.base_dict['evclass']]
            else:
                evtclasslist_vals = copy.copy(evtclasslist_keys)

            for mktimekey in mktimelist:
                for evtclassval in evtclasslist_vals:
                    fullkey = comp.make_key(
                        '%s_%s_{ebin_name}_%s_{evtype_name}' %
                        (evtclassval, zcut, mktimekey))

                    name_keys = dict(zcut=zcut,
                                     ebin=comp.ebin_name,
                                     psftype=comp.evtype_name,
                                     coordsys=comp.coordsys,
                                     irf_ver=NAME_FACTORY.irf_ver(),
                                     mktime=mktimekey,
                                     evclass=evtclassval,
                                     fullpath=True)

                    ccube_name = os.path.basename(NAME_FACTORY.ccube(**name_keys))
                    outfile = os.path.join(outdir_base, ccube_name)
                    infiles = _make_input_file_list(outfile, num_files)
                    logfile = make_nfs_path(outfile.replace('.fits', '.log'))
                    job_configs[fullkey] = dict(args=infiles,
                                                output=outfile,
                                                logfile=logfile)

        return job_configs


Instruction:
Explain what the following Python 3 code does
def create_from_flux(cls, params, emin, emax, flux, scale=1.0):
        params = params.copy()
        params[0] = 1.0
        params[0] = flux / cls.eval_flux(emin, emax, params, scale=scale)
        return cls(params, scale)

Response: Create a spectral function instance given its flux.


Instruction:
Can you tell what is the following Python 3 function doing
def create_from_eflux(cls, params, emin, emax, eflux, scale=1.0):
        params = params.copy()
        params[0] = 1.0
        params[0] = eflux / cls.eval_eflux(emin, emax, params, scale=scale)
        return cls(params, scale)

Response: Create a spectral function instance given its energy flux.


Instruction:
Implement a function in Python 3 to
fast numerical integration method using mid - point rule.

Response:
def _integrate(cls, fn, emin, emax, params, scale=1.0, extra_params=None,
                   npt=20):
        """Fast numerical integration method using mid-point rule."""

        emin = np.expand_dims(emin, -1)
        emax = np.expand_dims(emax, -1)

        params = copy.deepcopy(params)
        for i, p in enumerate(params):
            params[i] = np.expand_dims(params[i], -1)

        xedges = np.linspace(0.0, 1.0, npt + 1)
        logx_edge = np.log(emin) + xedges * (np.log(emax) - np.log(emin))
        logx = 0.5 * (logx_edge[..., 1:] + logx_edge[..., :-1])
        xw = np.exp(logx_edge[..., 1:]) - np.exp(logx_edge[..., :-1])
        dnde = fn(np.exp(logx), params, scale, extra_params)
        return np.sum(dnde * xw, axis=-1)


Instruction:
Can you implement a function in Python 3 that
evaluates E times differential flux.

Response:
def ednde(self, x, params=None):
        """Evaluate E times differential flux."""
        params = self.params if params is None else params
        return np.squeeze(self.eval_ednde(x, params, self.scale,
                                          self.extra_params))


Instruction:
Can you generate the documentation for the following Python 3 function
def e2dnde(self, x, params=None):
        params = self.params if params is None else params
        return np.squeeze(self.eval_e2dnde(x, params, self.scale,
                                           self.extra_params))

Response: Evaluate E^2 times differential flux.


Instruction:
How would you explain what the following Python 3 function does
def dnde_deriv(self, x, params=None):
        params = self.params if params is None else params
        return np.squeeze(self.eval_dnde_deriv(x, params, self.scale,
                                               self.extra_params))

Response: Evaluate derivative of the differential flux with respect to E.


Instruction:
Implement a Python 3 function for
evaluating derivative of E times differential flux with respect to E.

Response:
def ednde_deriv(self, x, params=None):
        """Evaluate derivative of E times differential flux with respect to
        E."""
        params = self.params if params is None else params
        return np.squeeze(self.eval_ednde_deriv(x, params, self.scale,
                                                self.extra_params))


Instruction:
Create a Python 3 function to
evaluate derivative of E^2 times differential flux with respect to E.

Response:
def e2dnde_deriv(self, x, params=None):
        """Evaluate derivative of E^2 times differential flux with
        respect to E."""
        params = self.params if params is None else params
        return np.squeeze(self.eval_e2dnde_deriv(x, params, self.scale,
                                                 self.extra_params))


Instruction:
How would you explain what the following Python 3 function does
def flux(self, emin, emax, params=None):
        params = self.params if params is None else params
        return np.squeeze(self.eval_flux(emin, emax, params, self.scale,
                                         self.extra_params))

Response: Evaluate the integral flux.


Instruction:
Can you tell what is the following Python 3 function doing
def eflux(self, emin, emax, params=None):
        params = self.params if params is None else params
        return np.squeeze(self.eval_eflux(emin, emax, params, self.scale,
                                          self.extra_params))

Response: Evaluate the integral energy flux.


Instruction:
Implement a function in Python 3 to
test this source for spatial extension with the likelihood ratio method.

Response:
def extension(self, name, **kwargs):
        """Test this source for spatial extension with the likelihood
        ratio method (TS_ext).  This method will substitute an
        extended spatial model for the given source and perform a
        one-dimensional scan of the spatial extension parameter over
        the range specified with the width parameters.  The 1-D
        profile likelihood is then used to compute the best-fit value,
        upper limit, and TS for extension.  The nuisance parameters
        that will be simultaneously fit when performing the spatial
        scan can be controlled with the ``fix_shape``,
        ``free_background``, and ``free_radius`` options.  By default
        the position of the source will be fixed to its current
        position.  A simultaneous fit to position and extension can be
        performed by setting ``fit_position`` to True.

        Parameters
        ----------
        name : str
            Source name.

        {options}

        optimizer : dict
            Dictionary that overrides the default optimizer settings.

        Returns
        -------
        extension : dict
            Dictionary containing results of the extension analysis.  The same
            dictionary is also saved to the dictionary of this source under
            'extension'.
        """
        timer = Timer.create(start=True)
        name = self.roi.get_source_by_name(name).name

        schema = ConfigSchema(self.defaults['extension'],
                              optimizer=self.defaults['optimizer'])
        schema.add_option('prefix', '')
        schema.add_option('outfile', None, '', str)
        config = utils.create_dict(self.config['extension'],
                                   optimizer=self.config['optimizer'])
        config = schema.create_config(config, **kwargs)

        self.logger.info('Running extension fit for %s', name)

        free_state = FreeParameterState(self)
        ext = self._extension(name, **config)
        free_state.restore()

        self.logger.info('Finished extension fit.')

        if config['make_plots']:
            self._plotter.make_extension_plots(ext, self.roi,
                                               prefix=config['prefix'])

        outfile = config.get('outfile', None)
        if outfile is None:
            outfile = utils.format_filename(self.workdir, 'ext',
                                            prefix=[config['prefix'],
                                                    name.lower().replace(' ', '_')])
        else:
            outfile = os.path.join(self.workdir,
                                   os.path.splitext(outfile)[0])

        if config['write_fits']:
            self._make_extension_fits(ext, outfile + '.fits')

        if config['write_npy']:
            np.save(outfile + '.npy', dict(ext))

        self.logger.info('Execution time: %.2f s', timer.elapsed_time)
        return ext


Instruction:
How would you explain what the following Python 3 function does
def plotNLL_v_Flux(nll, fluxType, nstep=25, xlims=None):
    import matplotlib.pyplot as plt

    if xlims is None:
        xmin = nll.interp.xmin
        xmax = nll.interp.xmax
    else:
        xmin = xlims[0]
        xmax = xlims[1]

    y1 = nll.interp(xmin)
    y2 = nll.interp(xmax)

    ymin = min(y1, y2, 0.0)
    ymax = max(y1, y2, 0.5)

    xvals = np.linspace(xmin, xmax, nstep)
    yvals = nll.interp(xvals)

    fig = plt.figure()
    ax = fig.add_subplot(111)

    ax.set_xlim((xmin, xmax))
    ax.set_ylim((ymin, ymax))

    ax.set_xlabel(NORM_LABEL[fluxType])
    ax.set_ylabel(r'$-\Delta \log\mathcal{L}$')
    ax.plot(xvals, yvals)
    return fig, ax

Response: Plot the negative log - likelihood as a function of normalization


Instruction:
Can you implement a function in Python 3 that
plots a color plot of the Subject log - likelihood v.

Response:
def plotCastro_base(castroData, ylims,
                    xlabel, ylabel, nstep=25, zlims=None, global_min=False):
    """ Make a color plot (castro plot) of the
        log-likelihood as a function of
        energy and flux normalization

    castroData : A CastroData_Base object, with the
                 log-likelihood v. normalization for each energy bin
    ylims      : y-axis limits
    xlabel     : x-axis title
    ylabel     : y-axis title
    nstep      : Number of y-axis steps to plot for each energy bin
    zlims      : z-axis limits
    global_min : Plot the log-likelihood w.r.t. the global min.

    returns fig,ax,im,ztmp which are matplotlib figure, axes and image objects
    """
    import matplotlib.pyplot as plt

    ymin = ylims[0]
    ymax = ylims[1]
    if zlims is None:
        zmin = -10
        zmax = 0.
    else:
        zmin = zlims[0]
        zmax = zlims[1]

    fig = plt.figure()
    ax = fig.add_subplot(111)

    ax.set_xscale('log')
    ax.set_yscale('log')
    ax.set_ylim((ymin, ymax))

    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel)

    normVals = np.logspace(np.log10(ymin), np.log10(ymax), nstep)

    ztmp = []
    for i in range(castroData.nx):
        ztmp.append(castroData[i].interp(normVals))

    ztmp = np.asarray(ztmp).T
    ztmp *= -1.
    ztmp = np.where(ztmp < zmin, np.nan, ztmp)

    if global_min:
        global_offset = castroData.nll_offsets.min()
        offsets = global_offset - castroData.nll_offsets
        ztmp += offsets

    cmap = plt.get_cmap('jet_r')

    xedge = castroData.x_edges()
    ax.set_xlim((xedge[0], xedge[-1]))

    im = ax.pcolormesh(xedge, normVals, ztmp,
                       vmin=zmin, vmax=zmax, cmap=cmap, linewidth=0)

    #cax = ax
    #cbar = plt.colorbar(im)
    #cbar.set_label(r"$\Delta \log \mathcal{L}$")

    cax, cbar = make_colorbar(fig, ax, im, (zmin, zmax))

    #ax.set_ylim()
    #plt.gca().set_yscale('log')
    #plt.gca().set_xscale('log')
    #plt.gca().set_xlim(sed['e_min'][0], sed['e_max'][-1])
    #
    #cax, cbar = make_colorbar(fig, ax, im, (zmin, zmax))
    # cbar = fig.colorbar(im, ticks=np.arange(zmin,zmax),
    #                    fraction=0.10,panchor=(1.05,0.5))
    #cbar.set_label(r'$\Delta \log\mathcal{L}$')
    #cax = None
    return fig, ax, im, ztmp, cax, cbar


Instruction:
Implement a Python 3 function for
making a color plot of the delta log - likelihood v.

Response:
def plotCastro(castroData, ylims, nstep=25, zlims=None):
    """ Make a color plot (castro plot) of the
        delta log-likelihood as a function of
        energy and flux normalization

    castroData : A CastroData object, with the
                 log-likelihood v. normalization for each energy bin
    ylims      : y-axis limits
    nstep      : Number of y-axis steps to plot for each energy bin
    zlims      : z-axis limits

    returns fig,ax,im,ztmp which are matplotlib figure, axes and image objects
    """
    xlabel = "Energy [MeV]"
    ylabel = NORM_LABEL[castroData.norm_type]
    return plotCastro_base(castroData, ylims,
                           xlabel, ylabel, nstep, zlims)


Instruction:
How would you code a function in Python 3 to
plot a SED plot of the negative log - likelihood vs. flux of each energy bin.

Response:
def plotSED(castroData, ylims, TS_thresh=4.0, errSigma=1.0, specVals=[]):
    """ Make a color plot (castro plot) of the (negative) log-likelihood
        as a function of energy and flux normalization

    castroData : A CastroData object, with the
                 log-likelihood v. normalization for each energy bin
    ylims      : y-axis limits
    TS_thresh  : TS value above with to plot a point,
                 rather than an upper limit
    errSigma   : Number of sigma to use for error bars
    specVals   : List of spectra to add to plot
    returns fig,ax which are matplotlib figure and axes objects
    """
    import matplotlib.pyplot as plt

    xmin = castroData.refSpec.ebins[0]
    xmax = castroData.refSpec.ebins[-1]
    ymin = ylims[0]
    ymax = ylims[1]

    fig = plt.figure()
    ax = fig.add_subplot(111)

    ax.set_xscale('log')
    ax.set_yscale('log')
    ax.set_xlim((xmin, xmax))
    ax.set_ylim((ymin, ymax))

    ax.set_xlabel("Energy [GeV]")
    ax.set_ylabel(NORM_LABEL[castroData.norm_type])

    plotSED_OnAxis(ax, castroData, TS_thresh, errSigma)

    for spec in specVals:
        ax.loglog(castroData.refSpec.eref, spec)
        pass

    return fig, ax


Instruction:
Write a Python 3 script for
comparing two SEDs castroData1: A CastroData object, with the log-likelihood v. normalization for each energy bin castroData2: A CastroData object, with the log-likelihood v. normalization for each energy bin ylims : y-axis limits TS_thresh : TS value above with to plot a point, rather than an upper limit errSigma : Number of sigma to use for error bars specVals : List of spectra to add to plot returns fig,ax which are matplotlib figure and axes objects

Response:
def compare_SED(castroData1, castroData2, ylims, TS_thresh=4.0,
                errSigma=1.0, specVals=[]):
    """ Compare two SEDs

    castroData1: A CastroData object, with the
                 log-likelihood v. normalization for each energy bin
    castroData2: A CastroData object, with the
                 log-likelihood v. normalization for each energy bin
    ylims      : y-axis limits
    TS_thresh  : TS value above with to plot a point,
                 rather than an upper limit
    errSigma   : Number of sigma to use for error bars
    specVals   : List of spectra to add to plot
    returns fig,ax which are matplotlib figure and axes objects
    """
    import matplotlib.pyplot as plt

    xmin = min(castroData1.refSpec.ebins[0], castroData2.refSpec.ebins[0])
    xmax = max(castroData1.refSpec.ebins[-1], castroData2.refSpec.ebins[-1])
    ymin = ylims[0]
    ymax = ylims[1]

    fig = plt.figure()
    ax = fig.add_subplot(111)

    ax.set_xscale('log')
    ax.set_yscale('log')
    ax.set_xlim((xmin, xmax))
    ax.set_ylim((ymin, ymax))

    ax.set_xlabel("Energy [GeV]")
    ax.set_ylabel(NORM_LABEL[castroData1.norm_type])

    plotSED_OnAxis(ax, castroData1, TS_thresh, errSigma,
                   colorLim='blue', colorPoint='blue')
    plotSED_OnAxis(ax, castroData2, TS_thresh, errSigma,
                   colorLim='red', colorPoint='red')

    for spec in specVals:
        ax.loglog(castroData1.refSpec.eref, spec)

    return fig, ax


Instruction:
Write a Python 3 function for
building and return the information about the Galprop rings

Response:
def make_ring_dicts(**kwargs):
    """Build and return the information about the Galprop rings
    """
    library_yamlfile = kwargs.get('library', 'models/library.yaml')
    gmm = kwargs.get('GalpropMapManager', GalpropMapManager(**kwargs))
    if library_yamlfile is None or library_yamlfile == 'None':
        return gmm
    diffuse_comps = DiffuseModelManager.read_diffuse_component_yaml(library_yamlfile)
    for diffuse_value in diffuse_comps.values():
        if diffuse_value is None:
            continue
        if diffuse_value['model_type'] != 'galprop_rings':
            continue
        versions = diffuse_value['versions']
        for version in versions:
            gmm.make_ring_dict(version)
    return gmm


Instruction:
Can you write a function in Python 3 where it
builds and return the information about the diffuse components

Response:
def make_diffuse_comp_info_dict(**kwargs):
    """Build and return the information about the diffuse components
    """
    library_yamlfile = kwargs.pop('library', 'models/library.yaml')
    components = kwargs.pop('components', None)
    if components is None:
        comp_yamlfile = kwargs.pop('comp', 'config/binning.yaml')
        components = Component.build_from_yamlfile(comp_yamlfile)
    gmm = kwargs.get('GalpropMapManager', GalpropMapManager(**kwargs))
    dmm = kwargs.get('DiffuseModelManager', DiffuseModelManager(**kwargs))
    if library_yamlfile is None or library_yamlfile == 'None':
        diffuse_comps = {}
    else:
        diffuse_comps = DiffuseModelManager.read_diffuse_component_yaml(
            library_yamlfile)
    diffuse_comp_info_dict = dmm.make_diffuse_comp_info_dict(
        diffuse_comps, components)
    for diffuse_value in diffuse_comps.values():
        if diffuse_value is None:
            continue
        if diffuse_value['model_type'] != 'galprop_rings':
            continue
        versions = diffuse_value['versions']
        for version in versions:
            galprop_dict = gmm.make_diffuse_comp_info_dict(version)
            diffuse_comp_info_dict.update(galprop_dict)

    return dict(comp_info_dict=diffuse_comp_info_dict,
                GalpropMapManager=gmm,
                DiffuseModelManager=dmm)


Instruction:
Write a Python 3 script for
reading the yaml file for a partiuclar galprop key

Response:
def read_galprop_rings_yaml(self, galkey):
        """ Read the yaml file for a partiuclar galprop key
        """
        galprop_rings_yaml = self._name_factory.galprop_rings_yaml(galkey=galkey,
                                                                   fullpath=True)
        galprop_rings = yaml.safe_load(open(galprop_rings_yaml))
        return galprop_rings


Instruction:
Create a Python 3 function to
make the name of a gasmap file for a single ring

Response:
def make_ring_filename(self, source_name, ring, galprop_run):
        """ Make the name of a gasmap file for a single ring

        Parameters
        ----------

        source_name : str
            The galprop component, used to define path to gasmap files
        ring : int
            The ring index
        galprop_run : str
            String identifying the galprop parameters
        """
        format_dict = self.__dict__.copy()
        format_dict['sourcekey'] = self._name_factory.galprop_ringkey(source_name=source_name,
                                                                      ringkey="ring_%i" % ring)
        format_dict['galprop_run'] = galprop_run
        return self._name_factory.galprop_gasmap(**format_dict)


Instruction:
How would you implement a function in Python 3 that
makes the name of a merged gasmap file for a set of merged rings

Response:
def make_merged_name(self, source_name, galkey, fullpath):
        """ Make the name of a gasmap file for a set of merged rings

        Parameters
        ----------

        source_name : str
            The galprop component, used to define path to gasmap files
        galkey : str
            A short key identifying the galprop parameters
        fullpath : bool
            Return the full path name
        """
        format_dict = self.__dict__.copy()
        format_dict['sourcekey'] = self._name_factory.galprop_sourcekey(source_name=source_name,
                                                                        galpropkey=galkey)
        format_dict['fullpath'] = fullpath
        return self._name_factory.merged_gasmap(**format_dict)


Instruction:
Given the following Python 3 function, write the documentation
def make_xml_name(self, source_name, galkey, fullpath):
        format_dict = self.__dict__.copy()
        format_dict['sourcekey'] = self._name_factory.galprop_sourcekey(source_name=source_name,
                                                                        galpropkey=galkey)
        format_dict['fullpath'] = fullpath
        return self._name_factory.srcmdl_xml(**format_dict)

Response: Make the name of an xml file for a set of merged rings


Instruction:
Given the following Python 3 function, write the documentation
def make_ring_filelist(self, sourcekeys, rings, galprop_run):
        flist = []
        for sourcekey in sourcekeys:
            for ring in rings:
                flist += [self.make_ring_filename(sourcekey,
                                                  ring, galprop_run)]
        return flist

Response: Make a list of all the template files for a merged component