def lcurve_from_txt(txt_file, outfile=None, noclobber=False, outdir=None, mjdref=None, gti=None): """ Load a lightcurve from a text file. Parameters ---------- txt_file : str File name of the input light curve in text format. Assumes two columns: time, counts. Times are seconds from MJDREF 55197.00076601852 (NuSTAR) if not otherwise specified. Returns ------- outfile : [str] Returned as a list with a single element for consistency with `lcurve_from_events` Other Parameters ---------------- outfile : str Output file name noclobber : bool If True, do not overwrite existing files mjdref : float, default 55197.00076601852 the MJD time reference gti : [[gti0_0, gti0_1], [gti1_0, gti1_1], ...] Good Time Intervals """ import numpy as np if mjdref is None: mjdref = np.longdouble('55197.00076601852') outfile = assign_value_if_none(outfile, hen_root(txt_file) + '_lc') outfile = outfile.replace(HEN_FILE_EXTENSION, '') + HEN_FILE_EXTENSION outdir = assign_value_if_none( outdir, os.path.dirname(os.path.abspath(txt_file))) _, outfile = os.path.split(outfile) mkdir_p(outdir) outfile = os.path.join(outdir, outfile) if noclobber and os.path.exists(outfile): warnings.warn('File exists, and noclobber option used. Skipping') return [outfile] time, counts = np.genfromtxt(txt_file, delimiter=' ', unpack=True) time = np.array(time, dtype=np.longdouble) counts = np.array(counts, dtype=np.float) lc = Lightcurve(time=time, counts=counts, gti=gti, mjdref=mjdref) lc.instr = 'EXTERN' logging.info('Saving light curve to %s' % outfile) save_lcurve(lc, outfile) return [outfile]
def load_lcurve(fname): """Load light curve from a file.""" if get_file_format(fname) == 'pickle': data = _load_data_pickle(fname) elif get_file_format(fname) == 'nc': data = _load_data_nc(fname) lcurve = Lightcurve(data['time'], data['counts'], err=data['counts_err'], gti=data['gti'], err_dist=data['err_dist'], mjdref=data['mjdref']) if 'instr' in list(data.keys()): lcurve.instr = data["instr"] if 'expo' in list(data.keys()): lcurve.expo = data["expo"] if 'e_intervals' in list(data.keys()): lcurve.e_intervals = data["e_intervals"] if 'e_interval' in list(data.keys()): lcurve.e_interval = data["e_interval"] if 'use_pi' in list(data.keys()): lcurve.use_pi = bool(data["use_pi"]) if 'header' in list(data.keys()): lcurve.header = data["header"] if 'base' in list(data.keys()): lcurve.base = data["base"] return lcurve
def lcurve_from_fits(fits_file, gtistring='GTI', timecolumn='TIME', ratecolumn=None, ratehdu=1, fracexp_limit=0.9, outfile=None, noclobber=False, outdir=None): """ Load a lightcurve from a fits file and save it in HENDRICS format. .. note :: FITS light curve handling is still under testing. Absolute times might be incorrect depending on the light curve format. Parameters ---------- fits_file : str File name of the input light curve in FITS format Returns ------- outfile : [str] Returned as a list with a single element for consistency with `lcurve_from_events` Other Parameters ---------------- gtistring : str Name of the GTI extension in the FITS file timecolumn : str Name of the column containing times in the FITS file ratecolumn : str Name of the column containing rates in the FITS file ratehdu : str or int Name or index of the FITS extension containing the light curve fracexp_limit : float Minimum exposure fraction allowed outfile : str Output file name noclobber : bool If True, do not overwrite existing files """ logging.warning( """WARNING! FITS light curve handling is still under testing. Absolute times might be incorrect.""") # TODO: # treat consistently TDB, UTC, TAI, etc. This requires some documentation # reading. For now, we assume TDB from astropy.io import fits as pf from astropy.time import Time import numpy as np from .base import create_gti_from_condition outfile = assign_value_if_none(outfile, hen_root(fits_file) + '_lc') outfile = outfile.replace(HEN_FILE_EXTENSION, '') + HEN_FILE_EXTENSION outdir = assign_value_if_none( outdir, os.path.dirname(os.path.abspath(fits_file))) _, outfile = os.path.split(outfile) mkdir_p(outdir) outfile = os.path.join(outdir, outfile) if noclobber and os.path.exists(outfile): warnings.warn('File exists, and noclobber option used. Skipping') return [outfile] lchdulist = pf.open(fits_file) lctable = lchdulist[ratehdu].data # Units of header keywords tunit = lchdulist[ratehdu].header['TIMEUNIT'] try: mjdref = high_precision_keyword_read(lchdulist[ratehdu].header, 'MJDREF') mjdref = Time(mjdref, scale='tdb', format='mjd') except: mjdref = None try: instr = lchdulist[ratehdu].header['INSTRUME'] except: instr = 'EXTERN' # ---------------------------------------------------------------- # Trying to comply with all different formats of fits light curves. # It's a madness... try: tstart = high_precision_keyword_read(lchdulist[ratehdu].header, 'TSTART') tstop = high_precision_keyword_read(lchdulist[ratehdu].header, 'TSTOP') except: raise(Exception('TSTART and TSTOP need to be specified')) # For nulccorr lcs this whould work timezero = high_precision_keyword_read(lchdulist[ratehdu].header, 'TIMEZERO') # Sometimes timezero is "from tstart", sometimes it's an absolute time. # This tries to detect which case is this, and always consider it # referred to tstart timezero = assign_value_if_none(timezero, 0) # for lcurve light curves this should instead work if tunit == 'd': # TODO: # Check this. For now, I assume TD (JD - 2440000.5). # This is likely wrong timezero = Time(2440000.5 + timezero, scale='tdb', format='jd') tstart = Time(2440000.5 + tstart, scale='tdb', format='jd') tstop = Time(2440000.5 + tstop, scale='tdb', format='jd') # if None, use NuSTAR defaulf MJDREF mjdref = assign_value_if_none( mjdref, Time(np.longdouble('55197.00076601852'), scale='tdb', format='mjd')) timezero = (timezero - mjdref).to('s').value tstart = (tstart - mjdref).to('s').value tstop = (tstop - mjdref).to('s').value if timezero > tstart: timezero -= tstart time = np.array(lctable.field(timecolumn), dtype=np.longdouble) if time[-1] < tstart: time += timezero + tstart else: time += timezero try: dt = high_precision_keyword_read(lchdulist[ratehdu].header, 'TIMEDEL') if tunit == 'd': dt *= 86400 except: warnings.warn('Assuming that TIMEDEL is the difference between the' ' first two times of the light curve') dt = time[1] - time[0] # ---------------------------------------------------------------- ratecolumn = assign_value_if_none( ratecolumn, _look_for_array_in_array(['RATE', 'RATE1', 'COUNTS'], lctable.names)) rate = np.array(lctable.field(ratecolumn), dtype=np.float) try: rate_e = np.array(lctable.field('ERROR'), dtype=np.longdouble) except: rate_e = np.zeros_like(rate) if 'RATE' in ratecolumn: rate *= dt rate_e *= dt try: fracexp = np.array(lctable.field('FRACEXP'), dtype=np.longdouble) except: fracexp = np.ones_like(rate) good_intervals = (rate == rate) * (fracexp >= fracexp_limit) * \ (fracexp <= 1) rate[good_intervals] /= fracexp[good_intervals] rate_e[good_intervals] /= fracexp[good_intervals] rate[np.logical_not(good_intervals)] = 0 try: gtitable = lchdulist[gtistring].data gti_list = np.array([[a, b] for a, b in zip(gtitable.field('START'), gtitable.field('STOP'))], dtype=np.longdouble) except: gti_list = create_gti_from_condition(time, good_intervals) lchdulist.close() lc = Lightcurve(time=time, counts=rate, err=rate_e, gti=gti_list, mjdref=mjdref.mjd) lc.instr = instr lc.header = lchdulist[ratehdu].header.tostring() logging.info('Saving light curve to %s' % outfile) save_lcurve(lc, outfile) return [outfile]