csscs.py 30.1 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958
#! /usr/bin/env python
# ==========================================================================
# Spectral component separation script
#
# Copyright (C) 2020 Luigi Tibaldo
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# ==========================================================================
import ctools
import gammalib
import math
import sys
from cscripts import mputils
from cscripts import obsutils


# ================= #
# csscs class #
# ================= #
class csscs(ctools.csobservation):
    """
    Spectral component separation script
    """

    # Constructor
    def __init__(self, *argv):
        """
        Constructor

        Parameters
        ----------
        argv : list of str
            List of IRAF command line parameter strings of the form
            ``parameter=3``.
        """
        # Initialise application by calling the base class constructor
        self._init_csobservation(self.__class__.__name__, ctools.__version__, argv)

        # Initialise data members
        self._nthreads = 0
        self._srcnames = []
        self._method = None
        self._fits = None
        self._excl_reg_map = None  # Exclusion region map for on/off analysis
        self._excl_reg_name = None

        # Return
        return

    # State methods for pickling
    def __getstate__(self):
        """
        Extend ctools.csobservation __getstate__ method

        Returns
        -------
        state : dict
            Pickled instance
        """
        # Set pickled dictionary
        # Set pickled dictionary
        state = {'base': ctools.csobservation.__getstate__(self),
                 'nthreads': self._nthreads,
                 'method': self._method,
                 'srcnames': self._srcnames,
                 'fits': self._fits,
                 'excl_reg_map': self._excl_reg_map,
                 'excl_reg_name' : self._excl_reg_name}

        # Return pickled dictionary
        return state

    def __setstate__(self, state):
        """
        Extend ctools.csobservation __setstate__ method

        Parameters
        ----------
        state : dict
            Pickled instance
        """
        # Set state
        ctools.csobservation.__setstate__(self, state['base'])
        self._nthreads = state['nthreads']
        self._srcnames = state['srcnames']
        self._method = state['method']
        self._fits = state['fits']
        self._excl_reg_map = state['excl_reg_map']
        self._excl_reg_name = state['excl_reg_name']

        # Return
        return

    # Private methods
    def _get_onoff_parameters(self):
        """
        Get On/Off analysis parameters.
        This is done here rather then in ctools.is_onoff
        because the exclusion map needs to be handled differently
        as an automatic parameter but queried only if not already set
        and we need to verify is not empty.
        Also many parameters are already queried for all methods
        TODO: verify if this can be made more uniform with other scripts
        """
        # Exclusion map
        if (self._excl_reg_map is not None) and (self._excl_reg_map.map().npix() > 0):
            # Exclusion map set and is not empty
            pass
        elif self['inexclusion'].is_valid():
            self._excl_reg_name = self['inexclusion'].filename()
            self._excl_reg_map = gammalib.GSkyRegionMap(self._excl_reg_name)
        else:
            msg = 'csscs in On/Off mode requires input exclusion region.'
            raise RuntimeError(msg)

        # Other csphagen parameters
        self["enumbins"].integer()
        if self["bkgmethod"].string() == "REFLECTED":
            self["bkgregmin"].integer()
            self['bkgregskip'].integer()
        self["maxoffset"].real()
        self["etruemin"].real()
        self["etruemax"].real()
        self["etruebins"].integer()

        return

    def _get_parameters(self):
        """
        Get parameters from parfile
        """

        # Set observation if not done before
        if self.obs().is_empty():
            self.obs(self._get_observations())

        # Set observation statistic
        self._set_obs_statistic(gammalib.toupper(self['statistic'].string()))

        # Collect number of unbinned, binned and On/Off observations in
        # observation container
        n_unbinned = 0
        n_binned = 0
        n_onoff = 0
        for obs in self.obs():
            if obs.classname() == 'GCTAObservation':
                if obs.eventtype() == 'CountsCube':
                    n_binned += 1
                else:
                    n_unbinned += 1
            elif obs.classname() == 'GCTAOnOffObservation':
                n_onoff += 1
        n_cta = n_unbinned + n_binned + n_onoff
        n_other = self.obs().size() - n_cta

        # Check if there are On/Off or non-IACT observations
        if n_onoff > 0 or n_other > 0:
            msg = 'On/Off or non-CTA observations found. ' \
                  'csscs does not support this type of observations.'
            raise RuntimeError(msg)
        # Otherwise check if there is a mix of binned and unbinned
        elif n_unbinned > 0 and n_binned > 0:
            msg = 'Mix of unbinned and binned CTA observations ' \
                  'found in observation container. csscs does not ' \
                  'support this mix.'
            raise RuntimeError(msg)

        # Set models if there are none in the container
        if self.obs().models().size() == 0:
            self.obs().models(self['inmodel'].filename())

        # Query the map definition parameters
        self['xref'].real()
        self['yref'].real()
        self['coordsys'].string()
        self['proj'].string()
        self['nxpix'].integer()
        self['nypix'].integer()
        self['binsz'].real()

        # Radius of ROI for component separation
        self['rad'].real()

        # Energy boundaries
        self["emin"].real()
        self["emax"].real()

        # If we have unbinned observations query analysis method
        if n_unbinned > 0:
            self._method = self['method'].string()
            # If method is Onoff query csphagen parameters
            if self._method == 'ONOFF':
                self._get_onoff_parameters()
        # Otherwise set method to binned
        else:
            self._method = 'BINNED'

        # Query target source names
        srcnames = self['srcnames'].string()

        # Fashion target sources into Python list
        self._srcnames = srcnames.split(';')
        # Strip leading and trailing spaces from names
        for s, name in enumerate(self._srcnames):
            self._srcnames[s] = name.strip()

        # Verify that the target sources are in the model
        src_in_model = True
        for name in self._srcnames:
            src_in_model = src_in_model and self.obs().models().contains(name)
        if src_in_model == False:
            msg = 'Not all target sources are present in input model.'
            raise RuntimeError(msg)

        # For On/Off analysis check the number of gamma-ray sources in the model
        if self._method == 'ONOFF':
            nsources = 0
            # Loop over models and verify if model is of type GModelSky
            for model in self.obs().models():
                if model.classname() == 'GModelSky':
                    nsources += 1
            # If there are background gamma-ray sources in the model
            # throw runtime error
            if nsources > len(self._srcnames):
                msg = 'Background gamma-ray sources found in the model. ' \
                      'On/Off analysis does not support this feature.'
                raise RuntimeError(msg)
            # Otherwise continue
            else:
                pass

        # Query other hidden parameters, just in case
        self['edisp'].boolean()
        self['calc_ulim'].boolean()
        self['calc_ts'].boolean()
        self['fix_bkg'].boolean()
        self['fix_srcs'].boolean()

        # Read ahead output parameters
        if self._read_ahead():
            self['outfile'].query()

        #  Write input parameters into logger
        self._log_parameters(gammalib.TERSE)

        # Set number of processes for multiprocessing
        self._nthreads = mputils.nthreads(self)

        # Return
        return

    def _create_map(self):
        """
        Create a gammalib.GSkyMap object to store the output

        Returns
        -------
        skymap : `~gammalib.GSkyMap`
        """

        skymap = gammalib.GSkyMap(self['proj'].string(), self['coordsys'].string(),
                                  self['xref'].real(), self['yref'].real(),
                                  -self['binsz'].real(), self['binsz'].real(),
                                  self['nxpix'].integer(), self['nypix'].integer(),
                                  1)

        return skymap

    def _adjust_model_pars(self):
        """
        Adjust model parameters
        """
        # Write header
        self._log_header1(gammalib.TERSE, 'Adjust model parameters')

        # Adjust model parameters based on input user parameters
        for model in self.obs().models():

            # Initialise TS flag for all models to false
            model.tscalc(False)

            # Log model name
            self._log_header3(gammalib.EXPLICIT, model.name())

            # In On/Off mode we cannot support multiple source morphologies
            # Thus, if we have more than one target we will set them all
            # to isotropic
            if self._method == 'ONOFF' and len(self._srcnames) > 1:
                # Check if it is a source
                try:
                    gammalib.GModelSky(model)
                    # In this case check if the spatial model is already isotropic
                    if model.spatial() == 'DiffuseIsotropic':
                        pass
                    # Otherwise change it to isotropic
                    else:
                        msg = ' Setting spatial model to diffuse isotropic'
                        self._log_string(gammalib.EXPLICIT, msg)
                        model.spatial(gammalib.GModelSpatialDiffuseConst())
                except:
                    pass

            # Freeze all parameters except the normalization
            # which is assumed to be the first spectral parameter
            normpar = model.spectral()[0]
            for par in model:
                if par.name() == normpar.name():
                    pass
                else:
                    if par.is_free():
                        self._log_string(gammalib.EXPLICIT, ' Fixing "' + par.name() + '"')
                        par.fix()

            # Deal with the target sources
            if model.name() in self._srcnames:

                # Free the normalisation parameter which is assumed to be
                # the first spectral parameter
                if normpar.is_fixed():
                    self._log_string(gammalib.EXPLICIT, ' Freeing "' + normpar.name() + '"')
                    normpar.free()

                # Optionally compute Test Statistic value
                if self['calc_ts'].boolean():
                    model.tscalc(True)

            # Deal with background models
            elif self['fix_bkg'].boolean() and not model.classname() == 'GModelSky':

                if normpar.is_free():
                    self._log_string(gammalib.EXPLICIT, ' Fixing "' + normpar.name() + '"')
                    normpar.fix()


            # Deal with background sources
            elif self['fix_srcs'].boolean() and model.classname() == 'GModelSky':

                if normpar.is_free():
                    self._log_string(gammalib.EXPLICIT, ' Fixing "' + normpar.name() + '"')
                    normpar.fix()

        # Return
        return

    def _mask_cube(self, obs, ra, dec, rad):
        """
        Mask cube observation

        Parameters
        ----------
        obs     : `gammalib.GCTAObservation` Input observation of type cube
        ra      : `float` R.A. (deg)
        dec     : `float` Dec (deg)
        rad     : `float` radius (deg)

        Returns
        -------
        new_obs : `gammalib.GCTAObservations`
            Output observations with masked cubes
        """

        # Filter cube according to ROI and user energy range
        cubemask = ctools.ctcubemask(obs)
        cubemask['ra'] = ra
        cubemask['dec'] = dec
        cubemask['rad'] = rad
        cubemask['regfile'] = 'NONE'
        cubemask['emin'] = self['emin'].real()
        cubemask['emax'] = self['emax'].real()

        # If chatter level is verbose and debugging is requested then
        # switch also on the debug model in ctcubemask
        if self._logVerbose() and self._logDebug():
            cubemask['debug'] = True

        # Mask cube
        cubemask.run()

        # Get deep copy of filtered observations
        new_obs = cubemask.obs().copy()

        # Return
        return new_obs

    def _mask_evlist(self, obs, ra, dec, rad):
        """
        Mask event list

        Parameters
        ----------
        obs     : `gammalib.GCTAObservations` Input observations of type event list
        ra      : `float` R.A. (deg)
        dec     : `float` Dec (deg)
        rad     : `float` radius (deg)

        Returns
        -------
        new_obs : `gammalib.GCTAObservations`
            Output observations with masked event lists
        """

        # Filter event list according to ROI and user energy range
        select = ctools.ctselect(obs)
        select['usepnt'] = False
        select['ra'] = ra
        select['dec'] = dec
        select['rad'] = rad
        select['emin'] = self['emin'].real()
        select['emax'] = self['emax'].real()
        select['tmin'] = 'INDEF'
        select['tmax'] = 'INDEF'

        # If chatter level is verbose and debugging is requested then
        # switch also on the debug model in ctcubemask
        if self._logVerbose() and self._logDebug():
            select['debug'] = True

        # Select event list
        select.run()

        # Get deep copy of filtered observation
        new_obs = select.obs().copy()

        # Return
        return new_obs

    def _mask_observations(self, ra, dec, rad):
        """
        Create observations restricted to circular ROI

        Parameters
        ----------
        ra      : `float` R.A. (deg)
        dec     : `float` Dec (deg)
        rad     : `float` radius (deg)

        Returns
        -------
        new_obs : `~gammalib.GObservations`
            Observations in circular ROI
        """

        # Determine type of masking according
        # to observation type and analysis method
        if self._method == 'UNBINNED':
            new_obs = self._mask_evlist(self.obs(), ra, dec, rad)
        elif self._method == 'BINNED':
            new_obs = self._mask_cube(self.obs(), ra, dec, rad)
        elif self._method == 'ONOFF':
            new_obs = obsutils.get_onoff_obs(self, self.obs(), nthreads=1,
                                             ra=ra, dec=dec,
                                             srcname=self._srcnames[0])

        # Return
        return new_obs

    def _pixel_analysis(self, inx):
        """
        Performs analysis over the region of interest
        corresponding to a single pixel of output map

        Parameters
        ----------
        inx     : `int` pixel index

        Returns
        -------
        result  : `dict` Results
        """

        # Create template for output map to extract pixel coordinates
        outmap = self._create_map()

        # Determine pixel centre coordinates
        pixdir = outmap.inx2dir(inx)
        ra = pixdir.ra_deg()
        dec = pixdir.dec_deg()

        # Write header for spatial bin
        msg = 'Spatial bin (%d) centred on (R.A.,Dec) = (%f,%f) deg' % (inx, ra, dec)
        self._log_header2(gammalib.TERSE, msg)

        # Initialize results
        result = {}
        for name in self._srcnames:
            result[name] = {'flux': 0.0,
                            'flux_err': 0.0,
                            'TS': 0.0,
                            'ulimit': -1.0}

        # Mask observations
        self._log_header3(gammalib.NORMAL, 'Masking observations')
        masked_obs = self._mask_observations(ra, dec, self['rad'].real())

        # Set up likelihood analysis
        self._log_header3(gammalib.NORMAL, 'Performing fit in region')
        like = ctools.ctlike(masked_obs)
        like['edisp'] = self['edisp'].boolean()
        like['nthreads'] = 1  # Avoids OpenMP conflict

        # If chatter level is verbose and debugging is requested then
        # switch also on the debug model in ctlike
        if self._logVerbose() and self._logDebug():
            like['debug'] = True

        # Perform maximum likelihood fit
        like.run()

        # Write model results for explicit chatter level
        self._log_string(gammalib.EXPLICIT, str(like.obs().models()))

        # Prepare objects for flux extraction
        # ROI
        centre = gammalib.GSkyDir()
        centre.radec_deg(ra, dec)
        roi = gammalib.GSkyRegionCircle(centre, self['rad'].real())
        # Energy boundaries
        emin = gammalib.GEnergy(self['emin'].real(), 'TeV')
        emax = gammalib.GEnergy(self['emax'].real(), 'TeV')

        # Continue only if log-likelihood is non-zero
        if like.obs().logL() != 0.0:

            # Loop over target sources
            for name in self._srcnames:

                # Get source
                source = like.obs().models()[name]

                # Get flux
                # Integrate spectral model between emin and emax
                flux = source.spectral().flux(emin, emax)
                # Calculate correction factor
                # Spatial model flux over ROI divided by ROI solid angle
                corr_factor = source.spatial().flux(roi)
                corr_factor /= gammalib.twopi * (
                            1 - math.cos(math.radians(self['rad'].real())))
                # Multiply flux by correction factor
                flux *= corr_factor
                result[name]['flux'] = flux

                # Get flux error
                # Normalization parameter
                normpar = source.spectral()[0]
                # Only normalization parameter free
                # Relative error on flux is same as on normalization
                # Avoid zero division error
                if normpar.value() > 0.:
                    flux_error = flux * normpar.error() / normpar.value()
                else:
                    flux_error = 0.
                result[name]['flux_error'] = flux_error

                # If requested get TS
                if self['calc_ts'].boolean():
                    result[name]['TS'] = source.ts()

                # If requested compute upper flux limit
                if self['calc_ulim'].boolean():

                    # Logging information
                    self._log_header3(gammalib.NORMAL,
                                      'Computing upper limit for source ' + name)

                    # Create upper limit object
                    ulimit = ctools.ctulimit(like.obs())
                    ulimit['srcname'] = name
                    ulimit['emin'] = self['emin'].real()
                    ulimit['emax'] = self['emax'].real()

                    # If chatter level is verbose and debugging is requested
                    # then switch also on the debug model in ctulimit
                    if self._logVerbose() and self._logDebug():
                        ulimit['debug'] = True

                    # Try to run upper limit and catch exceptions
                    try:
                        ulimit.run()
                        ulimit_value = ulimit.flux_ulimit()
                        # Multiply by correction factor to get flux per solid angle in ROI
                        ulimit_value *= corr_factor
                        result[name]['ulimit'] = ulimit_value
                    except:
                        self._log_string(gammalib.NORMAL, 'Upper limit '
                                                          'calculation failed.')


        else:
            value = 'Likelihood is zero. Bin is skipped.'
            self._log_value(gammalib.TERSE, '(R.A.,Dec) = (%f,%f) deg' % (ra, dec), value)

        # Return result
        return result

    def _write_hdu_keywords(self, hdu, is_flux=False):
        """
        Append cards to HDU

        Parameters
        ----------
        hdu  : `~gammalib.GFitsHDU` HDU
        """

        # Flux units
        if is_flux:
            hdu.card('BUNIT', 'ph/cm2/s/sr', 'Photon flux')

        # Minimum and maximum energy
        hdu.card("E_MIN", self['emin'].real(), "[TeV] Lower energy boundary")
        hdu.card("E_MAX", self['emax'].real(), "[TeV] Upper energy boundary")
        hdu.card("EUNIT", "TeV", "Units for E_MIN and E_MAX")

        # ROI size
        hdu.card('ROISZ', self['rad'].real(),
                 '[deg] Size of ROI used for component separation')

        # Analysis method
        hdu.card('METHOD', self._method, 'Analysis method')

        # For On/Off log information
        if self._method == 'ONOFF':

            # Exclusion map
            if self._excl_reg_name is not None:
                hdu.card("EXCLMAP", self._excl_reg_name.url(), "Exclusion map name")

            # Model background?
            hdu.card("BKGMODEL", self['use_model_bkg'].boolean(), 'Use background model?')

            # Fit statistic
            hdu.card("STAT", self['statistic'].string(), 'Fit statistic')

        return

    def _fill_fits(self, results):
        """
        Fill FITS object to store the results

        Parameters
        ----------
        result  : `dict` Results

        Returns
        -------
        fits    : `~gammalib.GFits` Fits object
        """

        # Create new Fits object
        fits = gammalib.GFits()

        # Append empty primary HDU
        fits.append(gammalib.GFitsImageDouble())

        # Loop over target sources
        for s, name in enumerate(self._srcnames):

            # Create skymaps to store results
            # Maps for TS and upper limits created and filled to avoid if statements
            # Will not be saved in the end if not requested
            fmap = self._create_map()
            errmap = self._create_map()
            tsmap = self._create_map()
            ulmap = self._create_map()

            # Loop over pixels and fill maps
            for inx in range(fmap.npix()):
                # Fill maps
                fmap[inx, 0] = results[inx][name]['flux']
                errmap[inx, 0] = results[inx][name]['flux_error']
                tsmap[inx, 0] = results[inx][name]['TS']
                ulmap[inx, 0] = results[inx][name]['ulimit']

            # Uppercase name to adhere to gammalib convention
            Name = gammalib.toupper(name)

            # Write maps to Fits
            fhdu = fmap.write(fits, Name + ' FLUX')
            self._write_hdu_keywords(fhdu, is_flux=True)
            errhdu = errmap.write(fits, Name + ' FLUX ERROR')
            self._write_hdu_keywords(errhdu, is_flux=True)

            # If requested write TS map to fits
            if self['calc_ts'].boolean():
                tshdu = tsmap.write(fits, Name + ' TS')
                self._write_hdu_keywords(tshdu)

            # If requested write upper limit map to fits
            if self['calc_ulim'].boolean():
                ulhdu = ulmap.write(fits, Name + ' FLUX UPPER LIMIT')
                self._write_hdu_keywords(ulhdu, is_flux=True)

        # Return
        return fits

    def _get_skymap(self, name, quantity):
        """
        Fetches skymap from FITS container

        Parameters
        ----------
        name : str
            Source name
        quantity : str
            Quantity

        Returns
        -------
        skymap : `~gammalib.GSkyMap`
            Skymap

        Raises
        ------
        NameError
        """

        # Initialise skymap object
        skymap = None

        # Proceed only if fits has been filled
        if self._fits != None:
            # Check that the name is in the list of target sources
            if name in self._srcnames:
                # Uppercase name
                Name = gammalib.toupper(name)
                # Assemble HDU name
                hduname = Name + ' ' + quantity
                # Try to fetch HDU
                try:
                    hdu = self._fits[hduname]
                    # Convert to GSkyMap
                    skymap = gammalib.GSkyMap(hdu)
                # Catch exception if HDU does not exist
                except:
                    msg = 'HDU "' + hduname + '" not found in FITS container.'
                    raise RuntimeError(msg)
            # Otherwise throw name error
            else:
                print('ERROR: Source "' + name + '" not found in list of target sources.')
                raise NameError(name)

        # Return
        return skymap

    # Public methods
    def run(self):
        """
        Run the script
        """
        # Switch screen logging on in debug mode
        if self._logDebug():
            self._log.cout(True)

        # Get parameters
        self._get_parameters()

        # Write input observation container into logger
        self._log_observations(gammalib.NORMAL, self.obs(), 'Input observation')

        # Adjust model parameters based on input user parameters
        self._adjust_model_pars()

        # Compute number of pixels of output map
        npix = self._create_map().npix()

        # If more than a single thread is requested then use multiprocessing
        if self._nthreads > 1:

            # Compute values in pixels
            args = [(self, '_pixel_analysis', i)
                    for i in range(npix)]
            poolresults = mputils.process(self._nthreads, mputils.mpfunc, args)

            # Construct results
            results = []
            for i in range(npix):
                results.append(poolresults[i][0])
                self._log_string(gammalib.TERSE, poolresults[i][1]['log'], False)

        # Otherwise loop over pixels and run the pixel analysis
        else:
            results = []
            for i in range(npix):
                results.append(self._pixel_analysis(i))

        # Fill output Fits
        self._fits = self._fill_fits(results)

        # Return
        return

    def save(self):
        """
        Save maps to Fits flie
        """
        # Write header
        self._log_header1(gammalib.TERSE, 'Save maps')

        # Continue only if FITS file is valid
        if self._fits != None:
            # Get outmap parameter
            outfile = self['outfile'].filename()

            # Log file name
            self._log_value(gammalib.NORMAL, 'Output file', outfile.url())

            # Save spectrum
            self._fits.saveto(outfile, self['clobber'].boolean())

        # Return
        return

    def exclusion_map(self, object=None):
        """
        Return and optionally set the exclusion regions map

        Parameters
        ----------
        object : `~gammalib.GSkyRegion` or `~gammalib.GSkyMap` or `~gammalib.GFilename`
            Exclusion regions object

        Returns
        -------
        region : `~gammalib.GSkyRegionMap`
            Exclusion regions map
        """
        # If a regions object is provided then set the regions ...
        if object is not None:
            self._excl_reg_map = gammalib.GSkyRegionMap(object)

        # Return
        return self._excl_reg_map

    def fits(self):
        """
        Return fits container

        Returns
        -------
        fits : `~gammalib.GFits()`
            FITS file containing the maps
        """
        # Return
        return self._fits

    def flux(self, name):
        """
        Return flux skymap

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

        Returns
        -------
        skymap : `~gammalib.GSkyMap`
            Flux skymap
        """

        skymap = self._get_skymap(name, 'FLUX')

        return skymap

    def flux_error(self, name):
        """
        Return flux error skymap

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

        Returns
        -------
        skymap : `~gammalib.GSkyMap`
            Flux error skymap
        """

        skymap = self._get_skymap(name, 'FLUX ERROR')

        return skymap

    def ts(self, name):
        """
        Return TS skymap

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

        Returns
        -------
        skymap : `~gammalib.GSkyMap`
            TS skymap
        """

        # Check that TS computation is requested
        if self['calc_ts'].boolean():
            skymap = self._get_skymap(name, 'TS')
        # Otherwise throw error
        else:
            msg = 'TS computation not requested. ' \
                  'Change user parameter calc_ts to True ' \
                  'to obtain TS.'
            raise RuntimeError(msg)

        return skymap

    def ulimit(self, name):
        """
        Return flux upper limit skymap

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

        Returns
        -------
        skymap : `~gammalib.GSkyMap`
            Flux upper limit skymap
        """

        # Check that upper limit computation is requested
        if self['calc_ulim'].boolean():
            skymap = self._get_skymap(name, 'FLUX UPPER LIMIT')
        # Otherwise throw error
        else:
            msg = 'Upper limit computation not requested. ' \
                  'Change user parameter calc_ulimit to True ' \
                  'to obtain upper limit.'
            raise RuntimeError(msg)

        return skymap


# ======================== #
# Main routine entry point #
# ======================== #
if __name__ == '__main__':
    # Create instance of application
    app = csscs(sys.argv)

    # Execute application
    app.execute()