def from_ini(cls, folder='.', ini_file='fpp.ini', recalc=False, refit_trap=False, star_ini_file='star.ini', ichrone=DARTMOUTH, **kwargs): """ To enable simple usage, initializes a FPPCalculation from a .ini file By default, a file called ``fpp.ini`` will be looked for in the current folder. Also present must be a ``star.ini`` file that contains the observed properties of the target star. ``fpp.ini`` must be of the following form:: name = k2oi ra = 11:30:14.510 dec = +07:35:18.21 period = 32.988 #days rprs = 0.0534 #Rp/Rstar photfile = lc_k2oi.csv [constraints] maxrad = 10 #exclusion radius [arcsec] secthresh = 0.001 #maximum allowed secondary signal depth #This variable defines contrast curves #ccfiles = Keck_J.cc, Lick_J.cc Photfile must be a text file with columns ``(days_from_midtransit, flux, flux_err)``. Both whitespace- and comma-delimited will be tried, using ``np.loadtxt``. Photfile need not be there if there is a pickled :class:`TransitSignal` saved in the same directory as ``ini_file``, named ``trsig.pkl`` (or another name as defined by ``trsig`` keyword in ``.ini`` file). ``star.ini`` should look something like the following:: B = 15.005, 0.06 V = 13.496, 0.05 g = 14.223, 0.05 r = 12.858, 0.04 i = 11.661, 0.08 J = 9.763, 0.03 H = 9.135, 0.03 K = 8.899, 0.02 W1 = 8.769, 0.023 W2 = 8.668, 0.02 W3 = 8.552, 0.025 Kepler = 12.473 #Teff = 3503, 80 #feh = 0.09, 0.09 #logg = 4.89, 0.1 Any star properties can be defined; if errors are included then they will be used in the :class:`isochrones.StarModel` MCMC fit. Spectroscopic parameters (``Teff, feh, logg``) are optional. If included, then they will also be included in :class:`isochrones.StarModel` fit. A magnitude for the band in which the transit signal is observed (e.g., ``Kepler``) is required, though need not have associated uncertainty. :param folder: Folder to find configuration files. :param ini_file: Input configuration file. :param star_ini_file: Input config file for :class:`isochrones.StarModel` fits. :param recalc: Whether to re-calculate :class:`PopulationSet`, if a ``popset.h5`` file is already present :param **kwargs: Keyword arguments passed to :class:`PopulationSet`. Creates: * ``trsig.pkl``: the pickled :class:`vespa.TransitSignal` object. * ``starfield.h5``: the TRILEGAL field star simulation * ``starmodel.h5``: the :class:`isochrones.StarModel` fit * ``popset.h5``: the :class:`vespa.PopulationSet` object representing the model population simulations. """ if not os.path.isabs(ini_file): config = ConfigObj(os.path.join(folder,ini_file)) else: config = ConfigObj(ini_file) folder = os.path.abspath(folder) #required items name = config['name'] ra, dec = config['ra'], config['dec'] period = float(config['period']) rprs = float(config['rprs']) #load starmodels if there; # if not, create them. if 'starmodel_basename' not in config: starmodel_basename = 'dartmouth_starmodel' else: starmodel_basename = config['starmodel_basename'] single_starmodel_file = os.path.join(folder,'{}_single.h5'.format(starmodel_basename)) binary_starmodel_file = os.path.join(folder,'{}_binary.h5'.format(starmodel_basename)) triple_starmodel_file = os.path.join(folder,'{}_triple.h5'.format(starmodel_basename)) #Single try: single_starmodel = StarModel.load_hdf(single_starmodel_file) logging.info('Single StarModel loaded from {}'.format(single_starmodel_file)) except: single_starmodel = StarModel.from_ini(ichrone, folder, ini_file=star_ini_file) logging.info('Fitting single StarModel to {}...'.format(single_starmodel.properties)) single_starmodel.fit() single_starmodel.save_hdf(single_starmodel_file) triangle_base = os.path.join(folder, '{}_triangle_single'.format(starmodel_basename)) single_starmodel.triangle_plots(triangle_base) logging.info('StarModel fit done.') #Binary try: binary_starmodel = BinaryStarModel.load_hdf(binary_starmodel_file) logging.info('BinaryStarModel loaded from {}'.format(binary_starmodel_file)) except: binary_starmodel = BinaryStarModel.from_ini(ichrone, folder, ini_file=star_ini_file) logging.info('Fitting BinaryStarModel to {}...'.format(binary_starmodel.properties)) binary_starmodel.fit() binary_starmodel.save_hdf(binary_starmodel_file) triangle_base = os.path.join(folder, '{}_triangle_binary'.format(starmodel_basename)) binary_starmodel.triangle_plots(triangle_base) logging.info('BinaryStarModel fit done.') #Triple try: triple_starmodel = TripleStarModel.load_hdf(triple_starmodel_file) logging.info('TripleStarModel loaded from {}'.format(triple_starmodel_file)) except: triple_starmodel = TripleStarModel.from_ini(ichrone, folder, ini_file=star_ini_file) logging.info('Fitting TripleStarModel to {}...'.format(triple_starmodel.properties)) triple_starmodel.fit() triple_starmodel.save_hdf(triple_starmodel_file) triangle_base = os.path.join(folder, '{}_triangle_triple'.format(starmodel_basename)) triple_starmodel.triangle_plots(triangle_base) logging.info('TripleStarModel fit done.') if 'popset' in config: popset_file = config['popset'] if not os.path.isabs(popset_file): popset_file = os.path.join(folder, popset_file) else: popset_file = os.path.join(folder,'popset.h5') if 'starfield' in config: trilegal_file = config['starfield'] if not os.path.isabs(trilegal_file): trilegal_file = os.path.join(folder, trilegal_file) else: trilegal_file = os.path.join(folder,'starfield.h5') if 'trsig' in config: trsig_file = config['trsig'] if not os.path.isabs(trsig_file): trsig_file = os.path.join(folder, trsig_file) else: trsig_file = os.path.join(folder,'trsig.pkl') #create TransitSignal if os.path.exists(trsig_file): logging.info('Loading transit signal from {}...'.format(trsig_file)) trsig = pickle.load(open(trsig_file,'rb')) else: if 'photfile' not in config: raise AttributeError('If transit pickle file (trsig.pkl) '+ 'not present, "photfile" must be'+ 'defined.') if not os.path.isabs(config['photfile']): photfile = os.path.join(folder,config['photfile']) else: photfile = config['photfile'] logging.info('Reading transit signal photometry ' + 'from {}...'.format(photfile)) try: ts, fs, dfs = np.loadtxt(photfile, unpack=True) except: ts, fs, dfs = np.loadtxt(photfile, delimiter=',', unpack=True) trsig = TransitSignal(ts, fs, dfs, P=period, name=name) logging.info('Fitting transitsignal with MCMC...') trsig.MCMC() trsig.save(trsig_file) #create PopulationSet try: if recalc: if os.path.exists(popset_file): os.remove(popset_file) raise RuntimeError #just to get to except block try: popset = PopulationSet.load_hdf(popset_file) except HDF5ExtError: os.remove(popset_file) logging.warning('{} file corrupted; removing.'.format(popset_file)) raise RuntimeError #to get to except block for m in DEFAULT_MODELS: popset[m] #should there be a better way to check this? (yes) if refit_trap: os.remove(popset_file) for pop in popset.poplist: logging.info('Re-fitting trapezoids for {}...'.format(pop.model)) pop.fit_trapezoids() pop.save_hdf(popset_file, pop.modelshort, append=True) popset = PopulationSet.load_hdf(popset_file) logging.info('PopulationSet loaded from {}'.format(popset_file)) except: if recalc: do_only = DEFAULT_MODELS else: try: popset = PopulationSet.load_hdf(popset_file) do_only = [] for m in DEFAULT_MODELS: try: popset[m] except: do_only.append(m) except: do_only = DEFAULT_MODELS if os.path.exists(popset_file): logging.warning('{} exists, but regenerating Population Set ({})...'.format(popset_file, do_only), exc_info=True) popset = PopulationSet(period=period, mags=single_starmodel.mags, ra=ra, dec=dec, trilegal_filename=trilegal_file, starmodel=single_starmodel, binary_starmodel=binary_starmodel, triple_starmodel=triple_starmodel, rprs=rprs, do_only=do_only, savefile=popset_file, **kwargs) fpp = cls(trsig, popset, folder=folder) ############# # Apply constraints # Exclusion radius maxrad = float(config['constraints']['maxrad']) fpp.set_maxrad(maxrad) if 'secthresh' in config['constraints']: secthresh = float(config['constraints']['secthresh']) if not np.isnan(secthresh): fpp.apply_secthresh(secthresh) # Odd-even constraint diff = 3 * np.max(trsig.depthfit[1]) fpp.constrain_oddeven(diff) #apply contrast curve constraints if present if 'ccfiles' in config['constraints']: ccfiles = config['constraints']['ccfiles'] if isinstance(ccfiles, basestring): ccfiles = [ccfiles] for ccfile in ccfiles: if not os.path.isabs(ccfile): ccfile = os.path.join(folder, ccfile) m = re.search('(\w+)_(\w+)\.cc',os.path.basename(ccfile)) if not m: logging.warning('Invalid CC filename ({}); '.format(ccfile) + 'skipping.') continue else: band = m.group(2) inst = m.group(1) name = '{} {}-band'.format(inst, band) cc = ContrastCurveFromFile(ccfile, band, name=name) fpp.apply_cc(cc) #apply "velocity contrast curve" if present if 'vcc' in config['constraints']: dv = float(config['constraints']['vcc'][0]) dmag = float(config['constraints']['vcc'][1]) vcc = VelocityContrastCurve(dv, dmag) fpp.apply_vcc(vcc) return fpp
kepfolder = 'fits/' + args.keplernumber fitfolder = kepfolder +'/' + args.folder ini_file = fitfolder + '/' + 'congfig.ini' config = ConfigObj(ini_file) #convert strings to ints where necessary config['koinum'] = int(config['koinum']) config['planets'] = [int(i) for i in config['planets']] #reassign to make code easier to read koinum = config['koinum'] planets = config['planets'] planets = [int(i) for i in planets] which = config['which'] #star model h5 file is in the kepfolder starmodel = kepfolder + '/dartmouth_starmodel_binary.h5' #load the star model from isochrones starmod = BinaryStarModel.load_hdf(starmodel) #create density and dilution samples rhostarA = density_samples(starmod) rhostarB = density_samples(starmod,'B') dilution = dilution_samples(starmod) #build light curve and grab Kepler data, save to file lc = BinaryKeplerLightCurve(int(koinum),planets,rhostarA,rhostarB,dilution) lc.save_hdf(fitfolder+'/'+str(koinum)+'_lc.h5') #makedirs('fits/{}/{}/chains/'.format(args.keplernumber,args.folder))
def get_mod_special(self, ic, folder): return BinaryStarModel(ic, folder=folder)
def from_ini(cls, folder='.', ini_file='fpp.ini', recalc=False, refit_trap=False, star_ini_file='star.ini', ichrone=DARTMOUTH, **kwargs): """ To enable simple usage, initializes a FPPCalculation from a .ini file By default, a file called ``fpp.ini`` will be looked for in the current folder. Also present must be a ``star.ini`` file that contains the observed properties of the target star. ``fpp.ini`` must be of the following form:: name = k2oi ra = 11:30:14.510 dec = +07:35:18.21 period = 32.988 #days rprs = 0.0534 #Rp/Rstar photfile = lc_k2oi.csv [constraints] maxrad = 10 #exclusion radius [arcsec] secthresh = 0.001 #maximum allowed secondary signal depth #This variable defines contrast curves #ccfiles = Keck_J.cc, Lick_J.cc Photfile must be a text file with columns ``(days_from_midtransit, flux, flux_err)``. Both whitespace- and comma-delimited will be tried, using ``np.loadtxt``. Photfile need not be there if there is a pickled :class:`TransitSignal` saved in the same directory as ``ini_file``, named ``trsig.pkl`` (or another name as defined by ``trsig`` keyword in ``.ini`` file). ``star.ini`` should look something like the following:: B = 15.005, 0.06 V = 13.496, 0.05 g = 14.223, 0.05 r = 12.858, 0.04 i = 11.661, 0.08 J = 9.763, 0.03 H = 9.135, 0.03 K = 8.899, 0.02 W1 = 8.769, 0.023 W2 = 8.668, 0.02 W3 = 8.552, 0.025 Kepler = 12.473 #Teff = 3503, 80 #feh = 0.09, 0.09 #logg = 4.89, 0.1 Any star properties can be defined; if errors are included then they will be used in the :class:`isochrones.StarModel` MCMC fit. Spectroscopic parameters (``Teff, feh, logg``) are optional. If included, then they will also be included in :class:`isochrones.StarModel` fit. A magnitude for the band in which the transit signal is observed (e.g., ``Kepler``) is required, though need not have associated uncertainty. :param folder: Folder to find configuration files. :param ini_file: Input configuration file. :param star_ini_file: Input config file for :class:`isochrones.StarModel` fits. :param recalc: Whether to re-calculate :class:`PopulationSet`, if a ``popset.h5`` file is already present :param **kwargs: Keyword arguments passed to :class:`PopulationSet`. Creates: * ``trsig.pkl``: the pickled :class:`vespa.TransitSignal` object. * ``starfield.h5``: the TRILEGAL field star simulation * ``starmodel.h5``: the :class:`isochrones.StarModel` fit * ``popset.h5``: the :class:`vespa.PopulationSet` object representing the model population simulations. """ if not os.path.isabs(ini_file): config = ConfigObj(os.path.join(folder, ini_file)) else: config = ConfigObj(ini_file) folder = os.path.abspath(folder) #required items name = config['name'] ra, dec = config['ra'], config['dec'] period = float(config['period']) rprs = float(config['rprs']) #load starmodels if there; # if not, create them. if 'starmodel_basename' not in config: starmodel_basename = 'dartmouth_starmodel' else: starmodel_basename = config['starmodel_basename'] single_starmodel_file = os.path.join( folder, '{}_single.h5'.format(starmodel_basename)) binary_starmodel_file = os.path.join( folder, '{}_binary.h5'.format(starmodel_basename)) triple_starmodel_file = os.path.join( folder, '{}_triple.h5'.format(starmodel_basename)) #Single try: single_starmodel = StarModel.load_hdf(single_starmodel_file) logging.info('Single StarModel loaded from {}'.format( single_starmodel_file)) except: single_starmodel = StarModel.from_ini(ichrone, folder, ini_file=star_ini_file) logging.info('Fitting single StarModel to {}...'.format( single_starmodel.properties)) single_starmodel.fit() single_starmodel.save_hdf(single_starmodel_file) triangle_base = os.path.join( folder, '{}_triangle_single'.format(starmodel_basename)) single_starmodel.triangle_plots(triangle_base) logging.info('StarModel fit done.') #Binary try: binary_starmodel = BinaryStarModel.load_hdf(binary_starmodel_file) logging.info( 'BinaryStarModel loaded from {}'.format(binary_starmodel_file)) except: binary_starmodel = BinaryStarModel.from_ini(ichrone, folder, ini_file=star_ini_file) logging.info('Fitting BinaryStarModel to {}...'.format( binary_starmodel.properties)) binary_starmodel.fit() binary_starmodel.save_hdf(binary_starmodel_file) triangle_base = os.path.join( folder, '{}_triangle_binary'.format(starmodel_basename)) binary_starmodel.triangle_plots(triangle_base) logging.info('BinaryStarModel fit done.') #Triple try: triple_starmodel = TripleStarModel.load_hdf(triple_starmodel_file) logging.info( 'TripleStarModel loaded from {}'.format(triple_starmodel_file)) except: triple_starmodel = TripleStarModel.from_ini(ichrone, folder, ini_file=star_ini_file) logging.info('Fitting TripleStarModel to {}...'.format( triple_starmodel.properties)) triple_starmodel.fit() triple_starmodel.save_hdf(triple_starmodel_file) triangle_base = os.path.join( folder, '{}_triangle_triple'.format(starmodel_basename)) triple_starmodel.triangle_plots(triangle_base) logging.info('TripleStarModel fit done.') if 'popset' in config: popset_file = config['popset'] if not os.path.isabs(popset_file): popset_file = os.path.join(folder, popset_file) else: popset_file = os.path.join(folder, 'popset.h5') if 'starfield' in config: trilegal_file = config['starfield'] if not os.path.isabs(trilegal_file): trilegal_file = os.path.join(folder, trilegal_file) else: trilegal_file = os.path.join(folder, 'starfield.h5') if 'trsig' in config: trsig_file = config['trsig'] if not os.path.isabs(trsig_file): trsig_file = os.path.join(folder, trsig_file) else: trsig_file = os.path.join(folder, 'trsig.pkl') #create TransitSignal if os.path.exists(trsig_file): logging.info( 'Loading transit signal from {}...'.format(trsig_file)) trsig = pickle.load(open(trsig_file, 'rb')) else: if 'photfile' not in config: raise AttributeError('If transit pickle file (trsig.pkl) ' + 'not present, "photfile" must be' + 'defined.') if not os.path.isabs(config['photfile']): photfile = os.path.join(folder, config['photfile']) else: photfile = config['photfile'] logging.info('Reading transit signal photometry ' + 'from {}...'.format(photfile)) try: ts, fs, dfs = np.loadtxt(photfile, unpack=True) except: ts, fs, dfs = np.loadtxt(photfile, delimiter=',', unpack=True) trsig = TransitSignal(ts, fs, dfs, P=period, name=name) logging.info('Fitting transitsignal with MCMC...') trsig.MCMC() trsig.save(trsig_file) #create PopulationSet try: if recalc: if os.path.exists(popset_file): os.remove(popset_file) raise RuntimeError #just to get to except block try: popset = PopulationSet.load_hdf(popset_file) except HDF5ExtError: os.remove(popset_file) logging.warning( '{} file corrupted; removing.'.format(popset_file)) raise RuntimeError #to get to except block for m in DEFAULT_MODELS: popset[m] #should there be a better way to check this? (yes) if refit_trap: os.remove(popset_file) for pop in popset.poplist: logging.info('Re-fitting trapezoids for {}...'.format( pop.model)) pop.fit_trapezoids() pop.save_hdf(popset_file, pop.modelshort, append=True) popset = PopulationSet.load_hdf(popset_file) logging.info('PopulationSet loaded from {}'.format(popset_file)) except: if recalc: do_only = DEFAULT_MODELS else: try: popset = PopulationSet.load_hdf(popset_file) do_only = [] for m in DEFAULT_MODELS: try: popset[m] except: do_only.append(m) except: do_only = DEFAULT_MODELS if os.path.exists(popset_file): logging.warning( '{} exists, but regenerating Population Set ({})...'. format(popset_file, do_only), exc_info=True) popset = PopulationSet(period=period, mags=single_starmodel.mags, ra=ra, dec=dec, trilegal_filename=trilegal_file, starmodel=single_starmodel, binary_starmodel=binary_starmodel, triple_starmodel=triple_starmodel, rprs=rprs, do_only=do_only, savefile=popset_file, **kwargs) fpp = cls(trsig, popset, folder=folder) ############# # Apply constraints # Exclusion radius maxrad = float(config['constraints']['maxrad']) fpp.set_maxrad(maxrad) if 'secthresh' in config['constraints']: secthresh = float(config['constraints']['secthresh']) if not np.isnan(secthresh): fpp.apply_secthresh(secthresh) # Odd-even constraint diff = 3 * np.max(trsig.depthfit[1]) fpp.constrain_oddeven(diff) #apply contrast curve constraints if present if 'ccfiles' in config['constraints']: ccfiles = list(config['constraints']['ccfiles']) for ccfile in ccfiles: if not os.path.isabs(ccfile): ccfile = os.path.join(folder, ccfile) m = re.search('(\w+)_(\w+)\.cc', os.path.basename(ccfile)) if not m: logging.warning('Invalid CC filename ({}); ' + 'skipping.'.format(ccfile)) continue else: band = m.group(2) inst = m.group(1) name = '{} {}-band'.format(inst, band) cc = ContrastCurveFromFile(ccfile, band, name=name) fpp.apply_cc(cc) #apply "velocity contrast curve" if present if 'vcc' in config['constraints']: dv = float(config['constraints']['vcc'][0]) dmag = float(config['constraints']['vcc'][1]) vcc = VelocityContrastCurve(dv, dmag) fpp.apply_vcc(vcc) return fpp