Exemple #1
0
def plotBayesGrid(lcfile,
                  ax='',
                  trestrange=[-15, 30],
                  CCmoderr=0.1,
                  Nsim=2000,
                  kcorfile='PS1/kcor_tonry_SALT2.fits',
                  nlogz=0):
    close('all')

    import snana
    sn = snana.SuperNova(lcfile)
    sn.doGridClassify(clobber=3,
                      noCosmoPrior=True,
                      kcorfile=kcorfile,
                      trestrange=trestrange,
                      modelerror=[0.08, CCmoderr],
                      Nsim=Nsim,
                      nlogz=nlogz)

    if not ax:
        close('all')
        ax1 = axes([0.12, 0.09, 0.75, 0.27])
        ax2 = axes([0.12, 0.36, 0.75, 0.27])
        ax3 = axes([0.12, 0.63, 0.75, 0.27])

    #plot the data points
    for m, f, e, flt in zip(sn.MJD, sn.FLUXCAL, sn.FLUXCALERR, sn.FLT):
        ax1.errorbar(m, f, yerr=e, color=filt_color[flt], fmt='.')
        ax2.errorbar(m, f, yerr=e, color=filt_color[flt], fmt='.')
        ax3.errorbar(m, f, yerr=e, color=filt_color[flt], fmt='.')

    for f in sn.FILTERS:
        row = where(sn.ClassSim.Ia.FLT[0] == f)[0]
        ax1.plot(sn.trestbestIa * (1 + sn.z) + sn.pkmjd,
                 sn.bestlcIa[row],
                 color=filt_color[f])
        ax2.plot(sn.trestbestIbc * (1 + sn.z) + sn.pkmjd,
                 sn.bestlcIbc[row],
                 color=filt_color[f])
        ax3.plot(sn.trestbestII * (1 + sn.z) + sn.pkmjd,
                 sn.bestlcII[row],
                 color=filt_color[f])

    ax2.set_ylabel('Flux')
    ax1.set_xlabel('MJD')
    ax1.set_ylim([0, max(sn.FLUXCAL) + 5])
    ax1.set_xlim([sn.pkmjd - 20, sn.pkmjd + 60])
    ax2.set_ylim([0, max(sn.FLUXCAL) + 5])
    ax2.set_xlim([sn.pkmjd - 20, sn.pkmjd + 60])
    ax3.set_ylim([0, max(sn.FLUXCAL) + 5])
    ax3.set_xlim([sn.pkmjd - 20, sn.pkmjd + 60])

    print('# PIa  PIbc  PII')
    print sn.PIa, sn.PIbc, sn.PII
    import pdb
    pdb.set_trace()

    return
Exemple #2
0
    def uploadSNANAPhotometry(self, db=None):
        import snana
        sn = snana.SuperNova(self.options.inputfile)
        if self.options.foundationdefaults:
            sn.SNID = sn.otherID[2:]
        transid = db.get_transient_from_DB(sn.SNID)
        if self.options.onlyexisting and not transid:
            if 'otherID' in sn.__dict__.keys():
                print('Object %s not found!     Trying %s' %
                      (sn.SNID, sn.otherID))
                sn.SNID = sn.otherID
                transid = db.get_transient_from_DB(sn.SNID)
            if self.options.onlyexisting and not transid:
                print('Object %s not found!     Returning' % sn.SNID)
                return ()
        print('uploading object %s' % sn.SNID)

        if self.options.useheader:
            transid = self.uploadHeader(sn)
            transname = sn.SNID
        else:
            transid = db.get_transient_from_DB(sn.SNID)
            transname = sn.SNID

        # get dictionaries for transient and photometry
        if type(sn.RA) == float:
            transientdict, photdict = self.parsePhotHeaderData(
                transname, sn.RA, sn.DECL)
        else:
            transientdict, photdict = self.parsePhotHeaderData(
                transname,
                sn.RA.split()[0],
                sn.DECL.split()[0])
        # get the filter IDs

        PhotUploadAll = {'transient': transientdict, 'photheader': photdict}

        # upload the photometry
        for mjd, flux, fluxerr, mag, magerr, flt, i in zip(
                sn.MJD, sn.FLUXCAL, sn.FLUXCALERR, sn.MAG, sn.MAGERR, sn.FLT,
                range(len(sn.FLT))):

            obsdate = Time(mjd, format='mjd').isot

            PhotUploadDict = {
                'obs_date': obsdate,
                'flux': flux,
                'flux_err': fluxerr,
                'forced': self.options.forcedphot,
                'diffim': self.options.diffim,
                'band': flt,
                'groups': []
            }

            if flux > 0:
                PhotUploadDict['mag'] = mag
                PhotUploadDict['mag_err'] = magerr
            else:
                PhotUploadDict['mag'] = None
                PhotUploadDict['mag_err'] = None

            if self.options.fluxzpt:
                PhotUploadDict['flux_zero_point'] = self.options.fluxzpt
            else:
                PhotUploadDict['flux_zero_point'] = None

            if 'SEARCH_PEAKMJD' in sn.__dict__.keys(
            ) and np.abs(mjd - sn.SEARCH_PEAKMJD) < 0.5:
                PhotUploadDict['discovery_point'] = 1
            else:
                PhotUploadDict['discovery_point'] = 0

            if 'DQ' in sn.__dict__.keys():
                if sn.DQ[i]:
                    PhotUploadDict['data_quality'] = str(sn.DQ[i])
                else:
                    PhotUploadDict['data_quality'] = None
            else:
                PhotUploadDict['data_quality'] = None

            PhotUploadAll['%s_%i' % (obsdate, i)] = PhotUploadDict
            PhotUploadAll['header'] = {
                'clobber': self.options.clobber,
                'mjdmatchmin': self.options.mjdmatchmin
            }

        print(PhotUploadAll)
        import requests
        from requests.auth import HTTPBasicAuth
        url = '%s' % db.dburl.replace('/api', '/add_transient_phot')

        def myconverter(obj):
            if obj is np.nan:
                return None
            elif isinstance(obj, np.integer):
                return int(obj)
            elif isinstance(obj, np.floating):
                return float(obj)
            elif isinstance(obj, np.ndarray):
                return obj.tolist()
            elif isinstance(obj, datetime.datetime):
                return obj.__str__()

        r = requests.post(url=url,
                          data=json.dumps(PhotUploadAll, default=myconverter),
                          auth=HTTPBasicAuth(db.dblogin, db.dbpassword))

        print('YSE_PZ says: %s' % json.loads(r.text)['message'])
Exemple #3
0
def mktib(lcfile='/Users/David/tib.DAT',
          ax='',
          trestrange=[-15, 30],
          CCmoderr=0.1,
          Nsim=2000,
          kcorfile='PS1/kcor_tonry_SALT2.fits',
          nlogz=0,
          sn=''):
    """Separate plots of best-fit tiberius light curves for Brandon"""

    close('all')

    import snana
    if not sn:
        sn = snana.SuperNova(lcfile)
        sn.doGridClassify(clobber=3,
                          noCosmoPrior=True,
                          kcorfile=kcorfile,
                          trestrange=trestrange,
                          modelerror=[0.08, CCmoderr],
                          Nsim=Nsim,
                          nlogz=nlogz)

    if not ax:
        close('all')
        import rcpar
        reload(rcpar)
        fig = rcpar.fullpaperfig()
        ax1 = fig.add_subplot(331)
        ax2 = fig.add_subplot(332)
        ax3 = fig.add_subplot(333)
        ax4 = fig.add_subplot(334)
        ax5 = fig.add_subplot(335)
        ax6 = fig.add_subplot(336)
        ax7 = fig.add_subplot(337)
        ax8 = fig.add_subplot(338)
        ax9 = fig.add_subplot(339)

        filtorder = array([0, 4, 1, 6, 7, 5, 2, 3])
        axlist = [ax1, ax2, ax3, ax4, ax5, ax6, ax7, ax8]
        axlist = array(axlist)[filtorder]

    #plot the data points
    for m, f, e, flt in zip(sn.MJD, sn.FLUXCAL, sn.FLUXCALERR, sn.FLT):
        row = where(flt == unique(sn.FLT))[0][0]
        limrow = where(flt == sn.FLT)[0]
        axlist[row].set_ylim([0, max(sn.FLUXCAL[limrow]) + 10])
        if flt == 'H' or flt == 'J' or flt == 'Z':
            axlist[row].set_ylim([0, max(sn.FLUXCAL[limrow]) + 20])
        if flt == 'R': axlist[row].set_ylim([0, 10])
        if flt == 'V': axlist[row].set_ylim([0, 6])
        axlist[row].errorbar(m, f, yerr=e, color='k', fmt='o')
        frow = where(array(filter2band.values()) == flt)[0]
        filter = filter2band.keys()[frow]
        if flt != 'H' and flt != 'J' and flt != 'Z' and flt != 'R' and flt != 'V':
            axlist[row].text(sn.pkmjd + 30,
                             max(sn.FLUXCAL[limrow] + 10.) * 6 / 8.,
                             '%s' % filter,
                             fontsize=20,
                             style='normal')
        elif flt == 'H' or flt == 'J' or flt == 'Z':
            axlist[row].text(sn.pkmjd + 30,
                             max(sn.FLUXCAL[limrow] + 20.) * 6 / 8.,
                             '%s' % filter,
                             fontsize=20,
                             style='normal')
        elif flt == 'R':
            axlist[row].text(sn.pkmjd + 30,
                             10. * 6 / 8.,
                             '%s' % filter,
                             fontsize=20,
                             style='normal')
        elif flt == 'V':
            axlist[row].text(sn.pkmjd + 30,
                             6. * 6 / 8.,
                             '%s' % filter,
                             fontsize=20,
                             style='normal')

    for f, ax in zip(unique(sn.FLT), axlist):
        row = where(sn.ClassSim.Ia.FLT[0] == f)[0]
        if f == 'H':
            pkmjdrow = where(sn.maxLikeIaModel.FLUXCAL[row] == max(
                sn.maxLikeIaModel.FLUXCAL[row]))[0]
            pkmjd = sn.maxLikeIaModel.MJD[pkmjdrow]
        ax.plot(sn.maxLikeIaModel.MJD[row],
                sn.maxLikeIaModel.FLUXCAL[row],
                color='r')
        ax.plot(sn.maxLikeIbcModel.MJD[row],
                sn.maxLikeIbcModel.FLUXCAL[row],
                color='g')
        ax.plot(sn.maxLikeIIModel.MJD[row],
                sn.maxLikeIIModel.FLUXCAL[row],
                color='b')

    for ax, i in zip(axlist, range(8)):
        ax.set_ylabel('Flux')
        ax.set_xlabel('MJD', fontsize='small')
        ax.set_xlim([sn.pkmjd - 20, sn.pkmjd + 60])
        ax.set_xticks([55550, 55560, 55570, 55580, 55590, 55600, 55610, 55620])
        ax.set_xticklabels([
            '55550', '55560', '55570', '55580', '55590', '55600', '55610',
            '55620'
        ])
        axtop = ax.twiny()
        if i == 0 or i == 2 or i == 6:
            axtop.set_xlabel('Time relative SN Ia peak (rest frame)',
                             fontsize='small')
        axtop.set_xlim((array(ax.get_xlim()) - pkmjd) / (1 + sn.z))
        axtop.set_xticks([-10, 0, 10, 20])

    ax9.set_xticks([-1, -2])
    ax9.set_yticks([-1, -1])
    ax9.set_xticklabels(['', '', '', '', '', ''])
    ax9.set_yticklabels(['', '', '', '', '', ''])
    ax9.set_ylim([0, 1])
    ax9.set_xlim([0, 1])

    ax9.text(0.1,
             0.7,
             r"""Type Ia (red curves)
Best $\chi^2/\nu$ = %.1f/%i""" % (min(sn.chi2Ia), sn.Ndof),
             color='r',
             fontsize='large')
    ax9.text(0.1,
             0.4,
             r"""Type Ib/c (green curves)
Best match: SN SDSS-002744 (Type Ib)
Best $\chi^2/\nu$ = %.1f/%i""" % (min(sn.chi2Ibc), sn.Ndof),
             color='g',
             fontsize='large')
    ax9.text(0.1,
             0.1,
             r"""Type II (blue curves)
Best match: SN SDSS-015339 (Type IIP)
Best $\chi^2/\nu$ = %.1f/%i""" % (min(sn.chi2II), sn.Ndof),
             color='b',
             fontsize='large')

    #ax2.legend(numpoints=1,prop={'size':8})

    print('# PIa  PIbc  PII')
    print sn.PIa, sn.PIbc, sn.PII
    #import pdb; pdb.set_trace()

    return
Exemple #4
0
def plottib(lcfile='/Users/David/tib.DAT',
            ax='',
            trestrange=[-15, 30],
            CCmoderr=0.1,
            Nsim=2000,
            kcorfile='PS1/kcor_tonry_SALT2.fits',
            nlogz=0):

    close('all')

    import snana
    sn = snana.SuperNova(lcfile)
    sn.doGridClassify(clobber=3,
                      noCosmoPrior=True,
                      kcorfile=kcorfile,
                      trestrange=trestrange,
                      modelerror=[0.08, CCmoderr],
                      Nsim=Nsim,
                      nlogz=nlogz)

    if not ax:
        close('all')
        import rcpar
        rcpar.lcpaperfig()
        ax3 = axes([0.12, 0.09, 0.75, 0.27])
        ax2 = axes([0.12, 0.36, 0.75, 0.27])
        ax1 = axes([0.12, 0.63, 0.75, 0.27])

    #plot the data points
    for m, f, e, flt in zip(sn.MJD, sn.FLUXCAL, sn.FLUXCALERR, sn.FLT):
        ax1.errorbar(m, f, yerr=e, color=filt_color[flt], fmt='.')
        ax2.errorbar(m, f, yerr=e, color=filt_color[flt], fmt='.')
        ax3.errorbar(m, f, yerr=e, color=filt_color[flt], fmt='.')
    for flt in sn.FILTERS:
        row = where(array(filter2band.values()) == flt)[0]
        filter = filter2band.keys()[row]
        ax2.plot(min(sn.MJD) - 500,
                 sn.FLUXCAL[0],
                 '.',
                 color=filt_color[flt],
                 label=filter)

    for f in sn.FILTERS:
        row = where(sn.ClassSim.Ia.FLT[0] == f)[0]
        ax1.plot(sn.trestbestIa * (1 + sn.z) + sn.pkmjd,
                 sn.bestlcIa[row],
                 color=filt_color[f])
        ax2.plot(sn.trestbestIbc * (1 + sn.z) + sn.pkmjd,
                 sn.bestlcIbc[row],
                 color=filt_color[f])
        ax3.plot(sn.trestbestII * (1 + sn.z) + sn.pkmjd,
                 sn.bestlcII[row],
                 color=filt_color[f])

    ax2.set_ylabel('Flux')
    ax3.set_xlabel('MJD')
    ax1.set_ylim([0, max(sn.FLUXCAL) + 10])
    ax1.set_xlim([sn.pkmjd - 20, sn.pkmjd + 60])
    ax2.set_ylim([0, max(sn.FLUXCAL) + 10])
    ax2.set_xlim([sn.pkmjd - 20, sn.pkmjd + 60])
    ax3.set_ylim([0, max(sn.FLUXCAL) + 10])
    ax3.set_xlim([sn.pkmjd - 20, sn.pkmjd + 60])

    ax1.set_xticklabels(['', '', '', '', '', ''])
    ax2.set_xticklabels(['', '', '', '', '', ''])
    ax3.set_xticks([55550, 55560, 55570, 55580, 55590, 55600, 55610, 55620])
    ax3.set_xticklabels([
        '55510', '55520', '55530', '55540', '55550', '55560', '55570', '55580'
    ])

    ax1.text(sn.pkmjd + 30,
             max(sn.FLUXCAL) * 3 / 4.,
             r"""Type Ia
Best $\chi^2/\nu$ = %.1f/%i""" % (min(sn.chi2Ia), sn.Ndof),
             color='k',
             fontsize='medium')
    ax2.text(sn.pkmjd + 30,
             max(sn.FLUXCAL) * 3 / 4.,
             r"""Type Ib/c
Best $\chi^2/\nu$ = %.1f/%i""" % (min(sn.chi2Ibc), sn.Ndof),
             color='k',
             fontsize='medium')
    ax3.text(sn.pkmjd + 30,
             max(sn.FLUXCAL) * 3 / 4.,
             r"""Type II
Best $\chi^2/\nu$ = %.1f/%i""" % (min(sn.chi2II), sn.Ndof),
             color='k',
             fontsize='medium')

    ax2.legend(numpoints=1, prop={'size': 8})

    print('# PIa  PIbc  PII')
    print sn.PIa, sn.PIbc, sn.PII
    import pdb
    pdb.set_trace()

    return
Exemple #5
0
    def uploadSNANAPhotometry(self, db=None):
        import snana
        sn = snana.SuperNova(self.options.inputfile)
        if self.options.foundationdefaults:
            sn.SNID = sn.otherID[2:]
        transid = db.get_ID_from_DB('transients', sn.SNID)
        if self.options.onlyexisting and not transid:
            print('Object %s not found!  Returning' % sn.SNID)
            return ()
        print('uploading object %s' % sn.SNID)

        if self.options.useheader:
            transid = self.uploadHeader(sn)
            transname = sn.SNID
        else:
            transid = db.get_ID_from_DB('transients', sn.SNID)
            transname = sn.SNID

        # create photometry object, if it doesn't exist
        photheaderdata = db.get_objects_from_DB('photometry')
        if type(sn.RA) == float:
            self.parsePhotHeaderData(photheaderdata,
                                     transname,
                                     sn.RA,
                                     sn.DECL,
                                     db=db)
        else:
            self.parsePhotHeaderData(photheaderdata,
                                     transname,
                                     sn.RA.split()[0],
                                     sn.DECL.split()[0],
                                     db=db)
        # get the filter IDs

        # upload the photometry
        for mjd, flux, fluxerr, mag, magerr, flt in zip(
                sn.MJD, sn.FLUXCAL, sn.FLUXCALERR, sn.MAG, sn.MAGERR, sn.FLT):

            obsdate = Time(mjd, format='mjd').isot
            bandid = db.getBandfromDB('band', flt, self.instid)
            if not bandid:
                raise RuntimeError(
                    'Error : band %s is not defined in the DB!!' % flt)

            PhotUploadDict = {
                'obs_date': obsdate,
                'flux': flux,
                'flux_err': fluxerr,
                'photometry': self.photdataid,
                'forced': 1,
                'dq': 1,
                'band': bandid,
                'flux_zero_point': 27.5
            }

            if flux > 0:
                PhotUploadDict['mag'] = mag
                PhotUploadDict['mag_err'] = magerr

            if 'SEARCH_PEAKMJD' in sn.__dict__.keys(
            ) and np.abs(mjd - sn.SEARCH_PEAKMJD) < 0.5:
                PhotUploadDict['discovery_point'] = 1

            if not transid:
                photdata = db.post_object_to_DB('photdata', PhotUploadDict)
            else:
                # if the transient is already in the DB, we need to check for photometry
                # and avoid duplicate epochs
                photepochs = db.get_objects_from_DB('photdata')
                closeID = None
                for p in photepochs:
                    pmjd = Time(p['obs_date'], format='isot').mjd
                    if p['photometry'] == self.photdataid and np.abs(
                            pmjd - mjd
                    ) < self.options.mjdmatchmin and p['band'] == bandid:
                        closeID = p['url']
                        break
                if closeID and self.options.clobber:
                    photdata = db.patch_object_to_DB('photdata',
                                                     PhotUploadDict, closeID)
                elif closeID and not self.options.clobber:
                    print('data point at MJD %i exists!  not clobbering' %
                          pmjd)
                else:
                    photdata = db.post_object_to_DB('photdata', PhotUploadDict)