_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q258800
_epd_function
validation
def _epd_function(coeffs, fluxes, xcc, ycc, bgv, bge): '''This is the EPD function to fit. Parameters ---------- coeffs : array-like of floats Contains the EPD coefficients that will be used to generate the EPD fit function. fluxes : array-like The flux measurement array being used. xcc,ycc : array-like Arrays of the x and y coordinates associated with each measurement in `fluxes`. bgv,bge : array-like Arrays of the flux background value and the flux background error associated with each measurement in `fluxes`. Returns ------- np.array Contains the fit
python
{ "resource": "" }
q258801
get_centroid_offsets
validation
def get_centroid_offsets(lcd, t_ing_egr, oot_buffer_time=0.1, sample_factor=3): '''After running `detrend_centroid`, this gets positions of centroids during transits, and outside of transits. These positions can then be used in a false positive analysis. This routine requires knowing the ingress and egress times for every transit of interest within the quarter this routine is being called for. There is currently no astrobase routine that automates this for periodic transits (it must be done in a calling routine). To get out of transit centroids, this routine takes points outside of the "buffer" set by `oot_buffer_time`, sampling 3x as many points on either side of the transit as are in the transit (or however many are specified by `sample_factor`). Parameters ---------- lcd : lcdict An `lcdict` generated by the `read_kepler_fitslc` function. We assume that the `detrend_centroid` function has been run on this `lcdict`. t_ing_egr : list of tuples This is of the form:: [(ingress time of i^th transit, egress time of i^th transit)] for i the transit number index in this quarter (starts at zero at the beginning of every quarter). Assumes units of BJD. oot_buffer_time : float Number of days away from ingress and egress times to begin sampling "out of transit" centroid points. The number of out of transit points to take per transit is 3x the number of points in transit. sample_factor : float The size of out of transit window from which to sample. Returns ------- dict This is a dictionary keyed by transit number (i.e., the same index as `t_ing_egr`), where each key contains the following value:: {'ctd_x_in_tra':ctd_x_in_tra, 'ctd_y_in_tra':ctd_y_in_tra, 'ctd_x_oot':ctd_x_oot, 'ctd_y_oot':ctd_y_oot, 'npts_in_tra':len(ctd_x_in_tra), 'npts_oot':len(ctd_x_oot), 'in_tra_times':in_tra_times, 'oot_times':oot_times} ''' # NOTE: # Bryson+ (2013) gives a more complicated and more correct approach to this # problem, computing offsets relative to positions defined on the SKY. This # requires using a Kepler focal plane geometry model. I don't have that # model, or know how to get it. So I use a simpler approach. qnum = int(np.unique(lcd['quarter'])) LOGINFO('Getting centroid offsets (qnum: {:d})...'.format(qnum)) # Kepler pixel scale, cf. # https://keplerscience.arc.nasa.gov/the-kepler-space-telescope.html arcsec_per_px = 3.98 # Get the residuals (units: pixel offset). times = lcd['ctd_dtr']['times'] ctd_resid_x = lcd['ctd_dtr']['ctd_x'] - lcd['ctd_dtr']['fit_ctd_x'] ctd_resid_y = lcd['ctd_dtr']['ctd_y'] - lcd['ctd_dtr']['fit_ctd_y'] # Return results in "centroid dictionary" (has keys of transit number). cd =
python
{ "resource": "" }
q258802
_get_legendre_deg_ctd
validation
def _get_legendre_deg_ctd(npts): '''This is a helper function for centroid detrending. ''' from scipy.interpolate import interp1d degs = nparray([4,5,6,10,15])
python
{ "resource": "" }
q258803
_legendre_dtr
validation
def _legendre_dtr(x, y, y_err, legendredeg=10): '''This calculates the residual and chi-sq values for a Legendre function fit. Parameters ---------- x : np.array Array of the independent variable. y : np.array Array of the dependent variable. y_err : np.array Array of errors associated with each `y` value. Used to calculate fit weights. legendredeg : int The degree of the Legendre function to use when fitting. Returns ------- tuple The tuple returned is of the form: (fit_y, fitchisq, fitredchisq) ''' try: p = Legendre.fit(x,
python
{ "resource": "" }
q258804
timebinlc
validation
def timebinlc(lcfile, binsizesec, outdir=None, lcformat='hat-sql', lcformatdir=None, timecols=None, magcols=None, errcols=None, minbinelems=7): '''This bins the given light curve file in time using the specified bin size. Parameters ---------- lcfile : str The file name to process. binsizesec : float The time bin-size in seconds. outdir : str or None If this is a str, the output LC will be written to `outdir`. If this is None, the output LC will be written to the same directory as `lcfile`. lcformat : str This is the `formatkey` associated with your light curve format, which you previously passed in to the `lcproc.register_lcformat` function. This will be used to look up how to find and read the light curve file. lcformatdir : str or None If this is provided, gives the path to a directory when you've stored your lcformat description JSONs, other than the usual directories lcproc knows to search for them in. Use this along with `lcformat` to specify an LC format JSON file that's not currently registered with lcproc. timecols,magcols,errcols : lists of str The keys in the lcdict produced by your light curve reader function that correspond to the times, mags/fluxes, and associated measurement errors that will be used as inputs to the binning process. If these are None, the default values for `timecols`, `magcols`, and `errcols` for your light curve format will be used here. minbinelems : int The minimum number of time-bin elements required to accept a time-bin as valid for the output binned light curve. Returns ------- str The name of the output pickle file with the binned LC. Writes the output binned light curve to a pickle that contains the lcdict with an added `lcdict['binned'][magcol]` key, which contains the binned times, mags/fluxes, and errs as `lcdict['binned'][magcol]['times']`, `lcdict['binned'][magcol]['mags']`, and `lcdict['epd'][magcol]['errs']` for each `magcol` provided in the input or default `magcols` value for this light curve format. ''' try: formatinfo = get_lcformat(lcformat,
python
{ "resource": "" }
q258805
parallel_timebin
validation
def parallel_timebin(lclist, binsizesec, maxobjects=None, outdir=None, lcformat='hat-sql', lcformatdir=None, timecols=None, magcols=None, errcols=None, minbinelems=7, nworkers=NCPUS, maxworkertasks=1000): '''This time-bins all the LCs in the list using the specified bin size. Parameters ---------- lclist : list of str The input LCs to process. binsizesec : float The time bin size to use in seconds. maxobjects : int or None If provided, LC processing will stop at `lclist[maxobjects]`. outdir : str or None The directory where output LCs will be written. If None, will write to the same directory as the input LCs. lcformat : str This is the `formatkey` associated with your light curve format, which you previously passed in to the `lcproc.register_lcformat` function. This will be used to look up how to find and read the light curve file. lcformatdir : str or None If this is provided, gives the path to a directory when you've stored your lcformat description JSONs, other than the usual directories lcproc knows to search for them in. Use this along with `lcformat` to specify an LC format JSON file that's not currently registered with lcproc. timecols,magcols,errcols : lists of str The keys in the lcdict produced by your light curve reader function that correspond to the times, mags/fluxes, and associated measurement errors that will be used as inputs to the binning process. If these are None, the default values for `timecols`, `magcols`, and
python
{ "resource": "" }
q258806
parallel_timebin_lcdir
validation
def parallel_timebin_lcdir(lcdir, binsizesec, maxobjects=None, outdir=None, lcformat='hat-sql', lcformatdir=None, timecols=None, magcols=None, errcols=None, minbinelems=7, nworkers=NCPUS, maxworkertasks=1000): ''' This time bins all the light curves in the specified directory. Parameters ---------- lcdir : list of str Directory containing the input LCs to process. binsizesec : float The time bin size to use in seconds. maxobjects : int or None If provided, LC processing will stop at `lclist[maxobjects]`. outdir : str or None The directory where output LCs will be written. If None, will write to the same directory as the input LCs. lcformat : str This is the `formatkey` associated with your light curve format, which you previously passed in to the `lcproc.register_lcformat` function. This will be used to look up how to find and read the light curve file. lcformatdir : str or None If this is provided, gives the path to a directory when you've stored your lcformat description JSONs, other than the usual directories lcproc knows to search
python
{ "resource": "" }
q258807
_varfeatures_worker
validation
def _varfeatures_worker(task): ''' This wraps varfeatures. ''' try: (lcfile, outdir, timecols, magcols, errcols, mindet, lcformat, lcformatdir) = task return get_varfeatures(lcfile, outdir, timecols=timecols, magcols=magcols,
python
{ "resource": "" }
q258808
serial_varfeatures
validation
def serial_varfeatures(lclist, outdir, maxobjects=None, timecols=None, magcols=None, errcols=None, mindet=1000, lcformat='hat-sql', lcformatdir=None): '''This runs variability feature extraction for a list of LCs. Parameters ---------- lclist : list of str The list of light curve file names to process. outdir : str The directory where the output varfeatures pickle files will be written. maxobjects : int The number of LCs to process from `lclist`. timecols : list of str or None The timecol keys to use from the lcdict in calculating the features. magcols : list of str or None The magcol keys to use from the lcdict in calculating the features. errcols : list of str or None The errcol keys to use from the lcdict in calculating the features. mindet : int The minimum number of LC points required to generate variability features. lcformat : str This is the `formatkey` associated with your light curve format, which you previously passed in to the `lcproc.register_lcformat` function. This will be used to look up how to find and read the light curves specified in `basedir` or `use_list_of_filenames`. lcformatdir
python
{ "resource": "" }
q258809
parallel_varfeatures
validation
def parallel_varfeatures(lclist, outdir, maxobjects=None, timecols=None, magcols=None, errcols=None, mindet=1000, lcformat='hat-sql', lcformatdir=None, nworkers=NCPUS): '''This runs variable feature extraction in parallel for all LCs in `lclist`. Parameters ---------- lclist : list of str The list of light curve file names to process. outdir : str The directory where the output varfeatures pickle files will be written. maxobjects : int The number of LCs to process from `lclist`. timecols : list of str or None The timecol keys to use from the lcdict in calculating the features. magcols : list of str or None The magcol keys to use from the lcdict in calculating the features. errcols : list of str or None The errcol keys to use from the lcdict in calculating the features. mindet : int The minimum number of LC points required to generate variability features. lcformat : str This is the `formatkey` associated with your light curve format, which you previously passed in to the `lcproc.register_lcformat` function. This will be used to look up how to find and read the light curves specified in `basedir` or `use_list_of_filenames`. lcformatdir : str or None If this is provided, gives the path to a directory when you've stored your lcformat
python
{ "resource": "" }
q258810
parallel_varfeatures_lcdir
validation
def parallel_varfeatures_lcdir(lcdir, outdir, fileglob=None, maxobjects=None, timecols=None, magcols=None, errcols=None, recursive=True, mindet=1000, lcformat='hat-sql', lcformatdir=None, nworkers=NCPUS): '''This runs parallel variable feature extraction for a directory of LCs. Parameters ---------- lcdir : str The directory of light curve files to process. outdir : str The directory where the output varfeatures pickle files will be written. fileglob : str or None The file glob to use when looking for light curve files in `lcdir`. If None, the default file glob associated for this LC format will be used. maxobjects : int The number of LCs to process from `lclist`. timecols : list of str or None The timecol keys to use from the lcdict in calculating the features. magcols : list of str or None The magcol keys to use from the lcdict in calculating the features. errcols : list of str or None The errcol keys to use from the lcdict in calculating the features. mindet : int The minimum number of LC points required to generate variability features. lcformat : str This is the `formatkey` associated with your light curve format, which you previously passed in to the `lcproc.register_lcformat` function. This will be used to look up how to find and read the light curves specified in `basedir` or `use_list_of_filenames`. lcformatdir : str or None If this is provided, gives the path to a directory when you've stored your lcformat description JSONs, other than the usual directories lcproc knows to search for them in. Use this along with `lcformat` to specify an LC format
python
{ "resource": "" }
q258811
cp2png
validation
def cp2png(checkplotin, extrarows=None): '''This is just a shortened form of the function above for convenience. This only handles pickle files as input. Parameters ---------- checkplotin : str File name of a checkplot pickle file to convert to a PNG. extrarows : list of tuples This is a list of 4-element tuples containing paths to PNG files that will be added to the end of the rows generated from the checkplotin pickle/dict. Each tuple represents a row in the final output PNG file. If there are less than 4 elements per tuple, the missing elements will be filled in with white-space. If there are more than 4 elements per tuple, only the first four will be used. The purpose of this kwarg is to incorporate periodograms and phased LC plots (in the form of PNGs) generated from an external period-finding function or program (like VARTOOLS) to allow for comparison with astrobase results. NOTE: the PNG files specified in `extrarows` here will be added to those already present in the input `checkplotdict['externalplots']` if that is None because you passed in a similar list of external plots to the :py:func:`astrobase.checkplot.pkl.checkplot_pickle` function earlier. In this case, `extrarows` can be used to add even more external plots if desired. Each external plot PNG will be resized to 750 x 480 pixels to fit into an output image cell. By convention, each 4-element tuple should contain: - a periodiogram
python
{ "resource": "" }
q258812
flare_model
validation
def flare_model(flareparams, times, mags, errs): '''This is a flare model function, similar to Kowalski+ 2011. From the paper by Pitkin+ 2014: http://adsabs.harvard.edu/abs/2014MNRAS.445.2268P Parameters ---------- flareparams : list of float This defines the flare model:: [amplitude, flare_peak_time, rise_gaussian_stdev, decay_time_constant] where: `amplitude`: the maximum flare amplitude in mags or flux. If flux, then amplitude should be positive. If mags, amplitude should be negative. `flare_peak_time`: time at which the flare maximum happens. `rise_gaussian_stdev`: the stdev of the gaussian describing the rise of the flare. `decay_time_constant`: the time constant of the exponential fall of the flare. times,mags,errs : np.array The input time-series of measurements and associated errors for which the model will be generated. The times will be used to generate model mags. Returns ------- (modelmags, times, mags, errs) : tuple Returns the model mags evaluated at the input time values. Also returns the input `times`, `mags`, and `errs`. ''' (amplitude, flare_peak_time, rise_gaussian_stdev, decay_time_constant) = flareparams zerolevel = np.median(mags)
python
{ "resource": "" }
q258813
flare_model_residual
validation
def flare_model_residual(flareparams, times, mags, errs): ''' This returns the residual between model mags and the actual mags. Parameters ---------- flareparams : list of float This defines the flare model:: [amplitude, flare_peak_time, rise_gaussian_stdev, decay_time_constant] where: `amplitude`: the maximum flare amplitude in mags or flux. If flux, then amplitude should be positive. If mags, amplitude should be negative. `flare_peak_time`: time at which the flare maximum happens. `rise_gaussian_stdev`: the stdev of the gaussian describing the rise of the flare. `decay_time_constant`: the time constant of the exponential fall of the
python
{ "resource": "" }
q258814
shutdown_check_handler
validation
def shutdown_check_handler(): """This checks the AWS instance data URL to see if there's a pending shutdown for the instance. This is useful for AWS spot instances. If there is a pending shutdown posted to the instance data URL, we'll use the result of this function break out of the processing loop and shut everything down ASAP before the instance dies. Returns ------- bool - True if the instance is going to die soon. - False if the instance is still safe. """ url = 'http://169.254.169.254/latest/meta-data/spot/instance-action' try: resp = requests.get(url, timeout=1.0) resp.raise_for_status() stopinfo = resp.json() if 'action' in stopinfo and stopinfo['action'] in ('stop', 'terminate',
python
{ "resource": "" }
q258815
runcp_producer_loop_savedstate
validation
def runcp_producer_loop_savedstate( use_saved_state=None, lightcurve_list=None, input_queue=None, input_bucket=None, result_queue=None, result_bucket=None, pfresult_list=None, runcp_kwargs=None, process_list_slice=None, download_when_done=True, purge_queues_when_done=True, save_state_when_done=True, delete_queues_when_done=False, s3_client=None, sqs_client=None ): """This wraps the function above to allow for loading previous state from a file. Parameters ---------- use_saved_state : str or None This is the path to the saved state pickle file produced by a previous run of `runcp_producer_loop`. Will get all of the arguments to run another instance of the loop from that pickle file. If this is None, you MUST provide all of the appropriate arguments to that function. lightcurve_list : str or list of str or None This is either a string pointing to a file containing a list of light curves filenames to process or the list itself. The names must correspond to the full filenames of files stored on S3, including all prefixes, but not include the 's3://<bucket name>/' bit (these will be added automatically). input_queue : str or None This is the name of the SQS queue which will receive processing tasks generated by this function. The queue URL will automatically be obtained from AWS. input_bucket : str or None The name of the S3 bucket containing the light curve files to process. result_queue : str or None This is the name of the SQS queue that this function will listen to for messages from the workers as they complete processing on their input elements. This function will attempt to match input sent to the `input_queue` with results coming into the `result_queue` so it knows how many objects have been successfully processed. If this function receives task results that aren't in its own input queue, it will acknowledge them so they complete successfully, but not download them automatically. This handles leftover tasks completing from a previous run of this function. result_bucket : str or None The name of the S3 bucket which will receive the results from the workers. pfresult_list : list of str or None This is a list of periodfinder result pickle S3 URLs associated with each light curve. If provided, this will be used to add in phased light curve plots to each checkplot pickle. If this is None, the worker loop will produce checkplot pickles that only contain object information, neighbor information, and unphased light curves. runcp_kwargs : dict or None This is a dict used to pass any extra keyword arguments to the `lcproc.checkplotgen.runcp` function that will be run by the worker loop. process_list_slice : list or None This is used to index into the input light curve list so a subset of the full list can be processed in this specific run of this function. Use None for a slice index elem to emulate single slice spec behavior: process_list_slice = [10, None] -> lightcurve_list[10:] process_list_slice = [None, 500] -> lightcurve_list[:500] purge_queues_when_done : bool or None If this is True, and this function exits (either when all done, or when it is interrupted with a Ctrl+C), all outstanding elements in the input/output queues that have not yet been acknowledged by
python
{ "resource": "" }
q258816
spline_fit_magseries
validation
def spline_fit_magseries(times, mags, errs, period, knotfraction=0.01, maxknots=30, sigclip=30.0, plotfit=False, ignoreinitfail=False, magsarefluxes=False, verbose=True): '''This fits a univariate cubic spline to the phased light curve. This fit may be better than the Fourier fit for sharply variable objects, like EBs, so can be used to distinguish them from other types of variables. Parameters ---------- times,mags,errs : np.array The input mag/flux time-series to fit a spline to. period : float The period to use for the spline fit. knotfraction : float The knot fraction is the number of internal knots to use for the spline. A value of 0.01 (or 1%) of the total number of non-nan observations appears to work quite well, without over-fitting. maxknots controls the maximum number of knots that will be allowed. maxknots : int The maximum number of knots that will be used even if `knotfraction` gives a value to use larger than `maxknots`. This helps dealing with over-fitting to short time-scale variations. sigclip : float or int or sequence of two floats/ints or None If a single float or int, a symmetric sigma-clip will be performed using the number provided as the sigma-multiplier to cut out from the input time-series. If a list of two ints/floats is provided, the function will perform an 'asymmetric' sigma-clip. The first element in this list is the sigma value to use for fainter flux/mag values; the second element in this list is the sigma value to use for brighter flux/mag values. For example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma dimmings and greater than 3-sigma brightenings. Here the meaning of "dimming" and "brightening" is set by *physics* (not the magnitude system), which is why the `magsarefluxes` kwarg must be correctly set. If `sigclip` is None, no sigma-clipping will be performed, and the time-series (with non-finite elems removed) will be passed through to the output. magsarefluxes : bool If True, will treat the input values of `mags` as fluxes for purposes of plotting the fit and sig-clipping. plotfit : str or False If this is a string, this function will make a plot for the fit to the mag/flux time-series and writes the plot to the path specified here. ignoreinitfail : bool If this is True, ignores the initial failure to find a set of optimized Fourier parameters using the global optimization function and proceeds to do a least-squares fit anyway. verbose : bool If True, will indicate progress and warn of any problems. Returns ------- dict This function returns a dict containing the model fit parameters, the minimized chi-sq value and the reduced chi-sq value. The form of this dict is mostly standardized across all functions in this module:: { 'fittype':'spline', 'fitinfo':{ 'nknots': the number of knots used for the fit 'fitmags': the model fit mags, 'fitepoch': the epoch of minimum light for the fit, }, 'fitchisq': the minimized value of the fit's chi-sq, 'fitredchisq':the reduced chi-sq value, 'fitplotfile': the output fit plot if fitplot is not None, 'magseries':{ 'times':input times in phase order of the model, 'phase':the phases of the model mags, 'mags':input mags/fluxes in the phase order of the model, 'errs':errs in the phase order of the model, 'magsarefluxes':input value of magsarefluxes kwarg } } ''' # this is required to fit the spline correctly if errs is None: errs = npfull_like(mags, 0.005) # sigclip the magnitude time series stimes, smags, serrs = sigclip_magseries(times, mags, errs,
python
{ "resource": "" }
q258817
runcp_worker
validation
def runcp_worker(task): ''' This is the worker for running checkplots. Parameters ---------- task : tuple This is of the form: (pfpickle, outdir, lcbasedir, kwargs). Returns ------- list of str The list of checkplot pickles returned by the `runcp` function. ''' pfpickle, outdir, lcbasedir, kwargs
python
{ "resource": "" }
q258818
parallel_cp
validation
def parallel_cp( pfpicklelist, outdir, lcbasedir, fast_mode=False, lcfnamelist=None, cprenorm=False, lclistpkl=None, gaia_max_timeout=60.0, gaia_mirror=None, nbrradiusarcsec=60.0, maxnumneighbors=5, makeneighborlcs=True, xmatchinfo=None, xmatchradiusarcsec=3.0, sigclip=10.0, minobservations=99, lcformat='hat-sql', lcformatdir=None, timecols=None, magcols=None, errcols=None, skipdone=False, done_callback=None, done_callback_args=None, done_callback_kwargs=None, liststartindex=None, maxobjects=None, nworkers=NCPUS, ): '''This drives the parallel execution of `runcp` for a list of periodfinding result pickles. Parameters ---------- pfpicklelist : list of str or list of Nones This is the list of the filenames of the period-finding result pickles to process. To make checkplots using the light curves directly, set this to a list of Nones with the same length as the list of light curve files that you provide in `lcfnamelist`. outdir : str The directory the checkplot pickles will be written to. lcbasedir : str The base directory that this function will look in to find the light curves pointed to by the period-finding result files. If you're using `lcfnamelist` to provide a list of light curve filenames directly, this arg is ignored. lcfnamelist : list of str or None If this is provided, it must be a list of the input light curve filenames to process. These can either be associated with each input period-finder result pickle, or can be provided standalone to make checkplots without phased LC plots in them. In the second case, you must set `pfpicklelist` to a list of Nones that matches the length of `lcfnamelist`. cprenorm : bool Set this to True if the light curves should be renormalized by `checkplot.checkplot_pickle`. This is set to False by default because we do our own normalization in this function using the light curve's registered normalization function and pass the normalized times, mags, errs to the `checkplot.checkplot_pickle` function. lclistpkl : str or dict This is either the filename of a pickle or the actual dict produced by lcproc.make_lclist. This is used to gather neighbor information. nbrradiusarcsec : float The radius in arcseconds to use for a search conducted around the coordinates of this object to look for any potential confusion and blending of variability amplitude caused by their proximity. maxnumneighbors : int The maximum number of neighbors that will have their light curves and magnitudes noted in this checkplot as potential blends with the target object. makeneighborlcs : bool If True, will make light curve and phased light curve plots for all neighbors found in the object collection for each input object. fast_mode : bool or float This runs the external catalog operations in a "fast" mode, with short timeouts and not trying to hit external catalogs that take a long time to respond. If this is set to True, the default settings for the external requests will then become:: skyview_lookup = False skyview_timeout = 10.0 skyview_retry_failed = False dust_timeout = 10.0 gaia_submit_timeout = 7.0 gaia_max_timeout = 10.0 gaia_submit_tries = 2 complete_query_later = False search_simbad = False If this is a float, will run in "fast" mode with the provided timeout value in seconds and the following settings:: skyview_lookup = True skyview_timeout = fast_mode skyview_retry_failed = False dust_timeout = fast_mode gaia_submit_timeout = 0.66*fast_mode gaia_max_timeout = fast_mode gaia_submit_tries = 2 complete_query_later = False search_simbad = False gaia_max_timeout : float Sets the timeout in seconds to use when waiting for the GAIA service to respond to our request for the object's information. Note that if `fast_mode` is set, this is ignored. gaia_mirror : str or None This sets the GAIA mirror to use. This is a key in the `services.gaia.GAIA_URLS` dict which defines the URLs to hit for each mirror. xmatchinfo : str or dict This is either the xmatch dict produced by the function `load_xmatch_external_catalogs` above, or the path to the xmatch info pickle file produced by that function. xmatchradiusarcsec : float This is the cross-matching radius to use in arcseconds. minobservations : int The minimum of observations the input object's mag/flux time-series must have for this function to plot its light curve and phased light curve. If the object has less than this number, no light curves will be plotted, but the checkplotdict will still contain all of the other information. sigclip : float or int or sequence of two floats/ints or None If a single float or int, a symmetric sigma-clip will be performed using the number provided as the sigma-multiplier to cut out from the input time-series. If a list of two ints/floats is provided, the function will perform an 'asymmetric' sigma-clip. The first element in this list is the sigma value to use for fainter flux/mag values; the second element in this list is the sigma value to use for brighter flux/mag values. For example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma dimmings and greater than 3-sigma brightenings. Here the meaning of "dimming" and "brightening" is set by *physics* (not the magnitude system), which is why the `magsarefluxes` kwarg must be correctly set. If `sigclip` is None, no sigma-clipping will be performed, and the time-series (with non-finite elems removed) will be passed through to the output. lcformat : str This is the `formatkey` associated with your light curve format, which you previously passed in to the `lcproc.register_lcformat` function. This will be used to look up how to find and read the light curves specified in `basedir` or `use_list_of_filenames`. lcformatdir : str or None If this is provided, gives the path to a directory when you've stored your lcformat description JSONs, other than the usual directories lcproc knows to search for them in. Use this along with `lcformat` to specify
python
{ "resource": "" }
q258819
parallel_cp_pfdir
validation
def parallel_cp_pfdir(pfpickledir, outdir, lcbasedir, pfpickleglob='periodfinding-*.pkl*', lclistpkl=None, cprenorm=False, nbrradiusarcsec=60.0, maxnumneighbors=5, makeneighborlcs=True, fast_mode=False, gaia_max_timeout=60.0, gaia_mirror=None, xmatchinfo=None, xmatchradiusarcsec=3.0, minobservations=99, sigclip=10.0, lcformat='hat-sql', lcformatdir=None, timecols=None, magcols=None, errcols=None, skipdone=False, done_callback=None, done_callback_args=None, done_callback_kwargs=None, maxobjects=None, nworkers=32): '''This drives the parallel execution of `runcp` for a directory of periodfinding pickles. Parameters ---------- pfpickledir : str This is the directory containing all of the period-finding pickles to process. outdir : str The directory the checkplot pickles will be written to. lcbasedir : str The base directory that this function will look in to find the light curves pointed to by the period-finding result files. If you're using `lcfnamelist` to provide a list of light curve filenames directly, this arg is ignored. pkpickleglob : str This is a UNIX file glob to select period-finding result pickles in the specified `pfpickledir`. lclistpkl : str or dict This is either the filename of a pickle or the actual dict produced by lcproc.make_lclist. This is used to gather neighbor information. cprenorm : bool Set this to True if the light curves should be renormalized by `checkplot.checkplot_pickle`. This is set to False by default because we do our own normalization in this function using the light curve's registered normalization function and pass the normalized times, mags, errs to the `checkplot.checkplot_pickle` function. nbrradiusarcsec : float The radius in arcseconds to use for a search conducted around the coordinates of this object to look for any potential confusion and blending of variability amplitude caused by their proximity. maxnumneighbors : int The maximum number of neighbors that will have their light curves and magnitudes noted in this checkplot as potential blends with the target object. makeneighborlcs : bool If True, will make light curve and phased light curve plots for all neighbors found in the object collection for each input object. fast_mode : bool or float This runs the external catalog operations in a "fast" mode, with short timeouts and not trying to hit external catalogs that take a long time to respond. If this is set to True, the default settings for the external requests will then become:: skyview_lookup = False skyview_timeout = 10.0 skyview_retry_failed = False dust_timeout = 10.0 gaia_submit_timeout = 7.0 gaia_max_timeout = 10.0 gaia_submit_tries = 2 complete_query_later = False search_simbad = False If this is a float, will run in "fast" mode with the provided timeout value in seconds and the following settings:: skyview_lookup = True skyview_timeout = fast_mode skyview_retry_failed = False dust_timeout = fast_mode gaia_submit_timeout = 0.66*fast_mode gaia_max_timeout = fast_mode gaia_submit_tries = 2 complete_query_later = False search_simbad = False gaia_max_timeout : float Sets the timeout in seconds to use when waiting for the GAIA service to respond to our request for the object's information. Note that if `fast_mode` is set, this is ignored. gaia_mirror : str or None This sets the GAIA mirror to use. This is a key in the `services.gaia.GAIA_URLS` dict which defines the URLs to hit for each mirror. xmatchinfo : str or dict This is either the xmatch dict produced by the function `load_xmatch_external_catalogs` above, or the path to the xmatch info pickle file produced by that function. xmatchradiusarcsec : float This is the cross-matching radius to use in arcseconds. minobservations : int The minimum of observations the input object's mag/flux time-series must have for this function to plot its light curve and phased light curve. If the object has less than this number, no light curves will be plotted, but the checkplotdict will still contain all of the other information. sigclip : float or int or sequence of two floats/ints or None If a single float or int, a symmetric sigma-clip will be performed using the number provided as the sigma-multiplier to cut out from the input time-series. If a list of two ints/floats is provided, the function will perform an 'asymmetric' sigma-clip. The first element in this list is the sigma value to use for fainter flux/mag values; the second element in this list is the sigma value to use for brighter flux/mag values. For example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma dimmings and greater than 3-sigma brightenings. Here the meaning of "dimming" and "brightening" is set by *physics* (not the magnitude system), which is why the `magsarefluxes` kwarg must be correctly set. If `sigclip` is None, no sigma-clipping will be performed, and the time-series (with non-finite elems removed) will be passed through to
python
{ "resource": "" }
q258820
_runpf_worker
validation
def _runpf_worker(task): ''' This runs the runpf function. ''' (lcfile, outdir, timecols, magcols, errcols, lcformat, lcformatdir, pfmethods, pfkwargs, getblssnr, sigclip, nworkers, minobservations, excludeprocessed) = task if os.path.exists(lcfile): pfresult = runpf(lcfile, outdir, timecols=timecols, magcols=magcols, errcols=errcols, lcformat=lcformat, lcformatdir=lcformatdir, pfmethods=pfmethods, pfkwargs=pfkwargs,
python
{ "resource": "" }
q258821
parallel_pf
validation
def parallel_pf(lclist, outdir, timecols=None, magcols=None, errcols=None, lcformat='hat-sql', lcformatdir=None, pfmethods=('gls','pdm','mav','win'), pfkwargs=({},{},{},{}), sigclip=10.0, getblssnr=False, nperiodworkers=NCPUS, ncontrolworkers=1, liststartindex=None, listmaxobjects=None, minobservations=500, excludeprocessed=True): '''This drives the overall parallel period processing for a list of LCs. As a rough benchmark, 25000 HATNet light curves with up to 50000 points per LC take about 26 days in total for an invocation of this function using GLS+PDM+BLS, 10 periodworkers, and 4 controlworkers (so all 40 'cores') on a 2 x Xeon E5-2660v3 machine. Parameters ---------- lclist : list of str The list of light curve file to process. outdir : str The output directory where the period-finding result pickles will go. timecols : list of str or None The timecol keys to use from the lcdict in calculating the features. magcols : list of str or None The magcol keys to use from the lcdict in calculating the features. errcols : list of str or None The errcol keys to use from the lcdict in calculating the features. lcformat : str This is the `formatkey` associated with your light curve format, which you previously passed in to the `lcproc.register_lcformat` function. This will be used to look up how to find and read the light curves specified in `basedir` or `use_list_of_filenames`. lcformatdir : str or None If this is provided, gives the path to a directory when you've stored your lcformat description JSONs, other than the usual directories lcproc knows to search for them in. Use this along with `lcformat` to specify an LC format JSON file that's not currently registered with lcproc. pfmethods : list of str This is a list of period finding methods to run. Each element is a string matching the keys of the `PFMETHODS` dict above. By default, this runs GLS, PDM, AoVMH, and the spectral window Lomb-Scargle periodogram. pfkwargs : list of dicts This is used to provide any special kwargs as dicts to each period-finding method function specified in `pfmethods`. sigclip : float or int or sequence of two floats/ints or None If a single float or int, a symmetric sigma-clip will be performed using the number provided as the sigma-multiplier to cut out from the input
python
{ "resource": "" }
q258822
parallel_pf_lcdir
validation
def parallel_pf_lcdir(lcdir, outdir, fileglob=None, recursive=True, timecols=None, magcols=None, errcols=None, lcformat='hat-sql', lcformatdir=None, pfmethods=('gls','pdm','mav','win'), pfkwargs=({},{},{},{}), sigclip=10.0, getblssnr=False, nperiodworkers=NCPUS, ncontrolworkers=1, liststartindex=None, listmaxobjects=None, minobservations=500, excludeprocessed=True): '''This runs parallel light curve period finding for directory of LCs. Parameters ---------- lcdir : str The directory containing the LCs to process. outdir : str The directory where the resulting period-finding pickles will go. fileglob : str or None The UNIX file glob to use to search for LCs in `lcdir`. If None, the default file glob associated with the registered LC format will be used instead. recursive : bool If True, will search recursively in `lcdir` for light curves to process. timecols : list of str or None The timecol keys to use from the lcdict in calculating the features. magcols : list of str or None The magcol keys to use from the lcdict in calculating the features. errcols : list of str or None The errcol keys to use from the lcdict in calculating the features. lcformat : str This is the `formatkey` associated with your light curve format, which you previously passed in to the `lcproc.register_lcformat` function. This will be used to look up how to find and read the light curves specified in `basedir` or `use_list_of_filenames`. lcformatdir : str or None If this is provided, gives the path to a directory when you've stored your lcformat description JSONs, other than the usual directories lcproc knows to search for them in. Use this along with `lcformat` to specify an LC format JSON file that's not currently registered with lcproc. pfmethods : list of str This is a list of period finding methods to run. Each element is a string matching the keys of the `PFMETHODS` dict above. By default, this runs GLS, PDM, AoVMH, and the spectral window Lomb-Scargle periodogram. pfkwargs : list of dicts This is used to provide any special kwargs as dicts to each period-finding method function specified in `pfmethods`. sigclip : float or int or sequence of two floats/ints or None If a single float or int, a symmetric sigma-clip will be performed using the number provided as the sigma-multiplier to cut out from the input time-series. If a list of two ints/floats is provided, the function will perform an 'asymmetric' sigma-clip. The first element in this list is the sigma value to use for fainter flux/mag values; the second element in this list is the sigma value to use for brighter flux/mag values. For example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma dimmings and greater than 3-sigma brightenings. Here the meaning of "dimming" and "brightening" is set by *physics* (not the magnitude system), which is why the `magsarefluxes` kwarg must be correctly set. If `sigclip` is None, no sigma-clipping will be performed, and the time-series (with non-finite elems removed) will be passed through to the output. getblssnr : bool If this is True and BLS is one of the methods specified in `pfmethods`, will also calculate the stats for each best period in the BLS results: transit depth, duration, ingress duration, refit period and epoch, and the SNR of the transit. nperiodworkers : int The number of parallel period-finding workers to launch per object task. ncontrolworkers : int The number of controlling processes to launch. This effectively sets how many objects from `lclist` will be processed in parallel. liststartindex : int or None This sets the index from where to start in `lclist`. listmaxobjects : int or None This sets the maximum number of objects in `lclist` to run period-finding for in this invocation. Together with `liststartindex`, `listmaxobjects` can be used to distribute processing over several independent machines if the number of light curves is very large. minobservations : int The minimum number of finite LC points required to process a light curve. excludeprocessed : bool If this is True, light curves that have existing period-finding result pickles in `outdir` will not be processed. FIXME: currently, this uses a dumb method of excluding already-processed files. A smarter way to do this is to (i) generate a SHA512 cachekey based on a repr of `{'lcfile', 'timecols', 'magcols', 'errcols', 'lcformat', 'pfmethods', 'sigclip', 'getblssnr', 'pfkwargs'}`, (ii) make sure all list kwargs in the dict are sorted, (iii) check if the output file has the same cachekey in its filename (last 8 chars of cachekey should work), so the result was processed in exactly the same way as specifed in the input to this function, and can therefore be ignored. Will implement this later.
python
{ "resource": "" }
q258823
collect_nonperiodic_features
validation
def collect_nonperiodic_features( featuresdir, magcol, outfile, pklglob='varfeatures-*.pkl', featurestouse=NONPERIODIC_FEATURES_TO_COLLECT, maxobjects=None, labeldict=None, labeltype='binary', ): '''This collects variability features into arrays for use with the classifer. Parameters ---------- featuresdir : str This is the directory where all the varfeatures pickles are. Use `pklglob` to specify the glob to search for. The `varfeatures` pickles contain objectids, a light curve magcol, and features as dict key-vals. The :py:mod:`astrobase.lcproc.lcvfeatures` module can be used to produce these. magcol : str This is the key in each varfeatures pickle corresponding to the magcol of the light curve the variability features were extracted from. outfile : str This is the filename of the output pickle that will be written containing a dict of all the features extracted into np.arrays. pklglob : str This is the UNIX file glob to use to search for varfeatures pickle files in `featuresdir`. featurestouse : list of str Each varfeatures pickle can contain any combination of non-periodic, stellar, and periodic features; these must have the same names as elements in the list of strings provided in `featurestouse`. This tries to get all the features listed in NONPERIODIC_FEATURES_TO_COLLECT by default. If `featurestouse` is provided as a list, gets only the features listed in this kwarg instead. maxobjects : int or None The controls how many pickles from the featuresdir to process. If None, will process all varfeatures pickles. labeldict : dict or None If this is provided, it must be a dict with the following key:val list:: '<objectid>':<label value> for each objectid collected from the varfeatures pickles. This will turn the collected information into a training set for classifiers. Example: to carry out non-periodic variable feature collection of fake LCS prepared by :py:mod:`astrobase.fakelcs.generation`, use the value of the 'isvariable' dict elem from the `fakelcs-info.pkl` here, like so:: labeldict={x:y for x,y in zip(fakelcinfo['objectid'], fakelcinfo['isvariable'])} labeltype : {'binary', 'classes'} This is either 'binary' or 'classes' for binary/multi-class
python
{ "resource": "" }
q258824
train_rf_classifier
validation
def train_rf_classifier( collected_features, test_fraction=0.25, n_crossval_iterations=20, n_kfolds=5, crossval_scoring_metric='f1', classifier_to_pickle=None, nworkers=-1, ): '''This gets the best RF classifier after running cross-validation. - splits the training set into test/train samples - does `KFold` stratified cross-validation using `RandomizedSearchCV` - gets the `RandomForestClassifier` with the best performance after CV - gets the confusion matrix for the test set Runs on the output dict from functions that produce dicts similar to that produced by `collect_nonperiodic_features` above. Parameters ---------- collected_features : dict or str This is either the dict produced by a `collect_*_features` function or the pickle produced by the same. test_fraction : float This sets the fraction of the input set that will be used as the test set after training. n_crossval_iterations : int This sets the number of iterations to use when running the cross-validation. n_kfolds : int This sets the number of K-folds to use on the data when doing a test-train split. crossval_scoring_metric : str This is a string that describes how the cross-validation score is calculated for each iteration. See the URL below for how to specify this parameter: http://scikit-learn.org/stable/modules/model_evaluation.html#scoring-parameter By default, this is tuned for binary classification and uses the F1 scoring metric. Change the `crossval_scoring_metric` to another metric (probably 'accuracy') for multi-class classification, e.g. for periodic variable classification. classifier_to_pickle : str If this is a string indicating the name of a pickle file to write, will write the trained classifier to the pickle that can be later loaded and used to classify data. nworkers : int This is the number of parallel workers to use in the RandomForestClassifier. Set to -1 to use all CPUs on your machine. Returns ------- dict A dict containing the trained classifier, cross-validation results, the input data set, and all input kwargs used is returned, along with cross-validation score metrics. ''' if (isinstance(collected_features,str) and os.path.exists(collected_features)): with open(collected_features,'rb') as infd: fdict = pickle.load(infd) elif isinstance(collected_features, dict): fdict = collected_features else: LOGERROR("can't figure out the input collected_features
python
{ "resource": "" }
q258825
apply_rf_classifier
validation
def apply_rf_classifier(classifier, varfeaturesdir, outpickle, maxobjects=None): '''This applys an RF classifier trained using `train_rf_classifier` to varfeatures pickles in `varfeaturesdir`. Parameters ---------- classifier : dict or str This is the output dict or pickle created by `get_rf_classifier`. This will contain a `features_name` key that will be used to collect the same features used to train the classifier from the varfeatures pickles in varfeaturesdir. varfeaturesdir : str The directory containing the varfeatures pickles for objects that will be classified by the trained `classifier`. outpickle : str This is a filename for the pickle that will be written containing the result dict from this function. maxobjects : int This sets the number of objects to process in `varfeaturesdir`. Returns ------- dict The classification results after running the trained `classifier` as returned as a dict. This contains predicted labels and their prediction probabilities. ''' if isinstance(classifier,str) and os.path.exists(classifier): with open(classifier,'rb') as infd: clfdict =
python
{ "resource": "" }
q258826
plot_training_results
validation
def plot_training_results(classifier, classlabels, outfile): '''This plots the training results from the classifier run on the training set. - plots the confusion matrix - plots the feature importances - FIXME: plot the learning curves too, see: http://scikit-learn.org/stable/modules/learning_curve.html Parameters ---------- classifier : dict or str This is the output dict or pickle created by `get_rf_classifier` containing the trained classifier. classlabels : list of str This contains all of the class labels for the current classification problem. outfile : str This is the filename where the plots will be written. Returns ------- str The path to the generated plot file. ''' if isinstance(classifier,str) and os.path.exists(classifier): with open(classifier,'rb') as infd: clfdict = pickle.load(infd) elif isinstance(classifier, dict): clfdict = classifier else: LOGERROR("can't figure out the input classifier arg") return None confmatrix = clfdict['best_confmatrix'] overall_feature_importances = clfdict[ 'best_classifier' ].feature_importances_ feature_importances_per_tree = np.array([ tree.feature_importances_ for tree in clfdict['best_classifier'].estimators_ ]) stdev_feature_importances = np.std(feature_importances_per_tree,axis=0) feature_names = np.array(clfdict['feature_names']) plt.figure(figsize=(6.4*3.0,4.8)) # confusion matrix plt.subplot(121) classes = np.array(classlabels) plt.imshow(confmatrix, interpolation='nearest', cmap=plt.cm.Blues) tick_marks = np.arange(len(classes)) plt.xticks(tick_marks, classes) plt.yticks(tick_marks, classes) plt.title('evaluation set confusion matrix') plt.ylabel('predicted class') plt.xlabel('actual class') thresh = confmatrix.max() / 2. for i, j in itertools.product(range(confmatrix.shape[0]),
python
{ "resource": "" }
q258827
_fourier_func
validation
def _fourier_func(fourierparams, phase, mags): '''This returns a summed Fourier cosine series. Parameters ---------- fourierparams : list This MUST be a list of the following form like so:: [period, epoch, [amplitude_1, amplitude_2, amplitude_3, ..., amplitude_X], [phase_1, phase_2, phase_3, ..., phase_X]] where X is the Fourier order. phase,mags : np.array The input phase and magnitude areas to use as the basis for the cosine series. The phases are used directly to generate the values of the function, while the mags array is used to generate the zeroth order amplitude coefficient. Returns ------- np.array The Fourier cosine series function evaluated over `phase`.
python
{ "resource": "" }
q258828
_fourier_chisq
validation
def _fourier_chisq(fourierparams, phase, mags, errs): '''This is the chisq objective function to be minimized by `scipy.minimize`. The parameters are the same as `_fourier_func` above. `errs` is used to
python
{ "resource": "" }
q258829
_fourier_residual
validation
def _fourier_residual(fourierparams, phase, mags): ''' This is the residual objective function to be minimized by `scipy.leastsq`. The parameters are the same as `_fourier_func` above.
python
{ "resource": "" }
q258830
skyview_stamp
validation
def skyview_stamp(ra, decl, survey='DSS2 Red', scaling='Linear', flip=True, convolvewith=None, forcefetch=False, cachedir='~/.astrobase/stamp-cache', timeout=10.0, retry_failed=False, savewcsheader=True, verbose=False): '''This downloads a DSS FITS stamp centered on the coordinates specified. This wraps the function :py:func:`astrobase.services.skyview.get_stamp`, which downloads Digitized Sky Survey stamps in FITS format from the NASA SkyView service: https://skyview.gsfc.nasa.gov/current/cgi/query.pl Also adds some useful operations on top of the FITS file returned. Parameters ---------- ra,decl : float The center coordinates for the stamp in decimal degrees. survey : str The survey name to get the stamp from. This is one of the values in the 'SkyView Surveys' option boxes on the SkyView webpage. Currently, we've only tested using 'DSS2 Red' as the value for this kwarg, but the other ones should work in principle. scaling : str This is the pixel value scaling function to use. flip : bool Will flip the downloaded image top to bottom. This should usually be True because matplotlib and FITS have different image coord origin conventions. Alternatively, set this to False and use the `origin='lower'` in any call to `matplotlib.pyplot.imshow` when plotting this image. convolvewith : astropy.convolution Kernel object or None If `convolvewith` is an astropy.convolution Kernel object from: http://docs.astropy.org/en/stable/convolution/kernels.html then, this function will return the stamp convolved with that kernel. This can be useful to see effects of wide-field telescopes (like the HATNet and HATSouth lenses) degrading the nominal 1 arcsec/px of DSS, causing blending of targets and any variability. forcefetch : bool If True, will disregard any existing cached copies of the stamp already downloaded corresponding to the requested center coordinates and redownload the FITS from the SkyView service. cachedir : str This is the path to the astrobase cache directory. All downloaded FITS stamps are stored here as .fits.gz files so we can immediately respond with the cached copy when a request is made for a coordinate center that's already been downloaded. timeout : float Sets the timeout in seconds to wait for a response from the NASA SkyView service. retry_failed : bool If the initial request to SkyView fails, and this is True, will retry until it succeeds. savewcsheader : bool If this is True, also returns the WCS header of the downloaded FITS stamp in addition to the FITS image itself. Useful for
python
{ "resource": "" }
q258831
plot_periodbase_lsp
validation
def plot_periodbase_lsp(lspinfo, outfile=None, plotdpi=100): '''Makes a plot of periodograms obtained from `periodbase` functions. This takes the output dict produced by any `astrobase.periodbase` period-finder function or a pickle filename containing such a dict and makes a periodogram plot. Parameters ---------- lspinfo : dict or str If lspinfo is a dict, it must be a dict produced by an `astrobase.periodbase` period-finder function or a dict from your own period-finder function or routine that is of the form below with at least these keys:: {'periods': np.array of all periods searched by the period-finder, 'lspvals': np.array of periodogram power value for each period, 'bestperiod': a float value that is the period with the highest peak in the periodogram, i.e. the most-likely actual period, 'method': a three-letter code naming the period-finder used; must be one of the keys in the `METHODLABELS` dict above, 'nbestperiods': a list of the periods corresponding to periodogram peaks (`nbestlspvals` below) to annotate on the periodogram plot so they can be called out visually, 'nbestlspvals': a list of the power values associated with periodogram peaks to annotate on the periodogram plot so they can be called out visually; should be the same length as `nbestperiods` above} If lspinfo is a str, then it must be a path to a pickle file that contains a dict of the form described above. outfile : str or None If this is a str, will write the periodogram plot to the file specified by this string. If this is None, will write to a file called 'lsp-plot.png' in the current working directory. plotdpi : int Sets the resolution in DPI of the output periodogram plot PNG file. Returns ------- str Absolute path to the periodogram plot file created. ''' # get the lspinfo from a pickle file transparently if isinstance(lspinfo,str) and os.path.exists(lspinfo): LOGINFO('loading LSP info from pickle %s' % lspinfo) with open(lspinfo,'rb') as infd: lspinfo = pickle.load(infd) try: # get the things to plot out of the data periods = lspinfo['periods'] lspvals = lspinfo['lspvals'] bestperiod = lspinfo['bestperiod'] lspmethod = lspinfo['method'] # make the LSP plot on the first subplot plt.plot(periods, lspvals)
python
{ "resource": "" }
q258832
lcdict_to_pickle
validation
def lcdict_to_pickle(lcdict, outfile=None): '''This just writes the lcdict to a pickle. If outfile is None, then will try to get the name from the lcdict['objectid'] and write to <objectid>-hptxtlc.pkl. If that fails, will write to a file named hptxtlc.pkl'. ''' if not outfile and lcdict['objectid']: outfile = '%s-hplc.pkl' % lcdict['objectid'] elif not outfile and not lcdict['objectid']: outfile = 'hplc.pkl' with open(outfile,'wb') as outfd:
python
{ "resource": "" }
q258833
read_hatpi_pklc
validation
def read_hatpi_pklc(lcfile): ''' This just reads a pickle LC. Returns an lcdict. ''' try: if lcfile.endswith('.gz'): infd = gzip.open(lcfile,'rb') else: infd = open(lcfile,'rb') lcdict = pickle.load(infd) infd.close() return lcdict except UnicodeDecodeError: if lcfile.endswith('.gz'): infd = gzip.open(lcfile,'rb') else: infd = open(lcfile,'rb') LOGWARNING('pickle %s was probably from Python 2 '
python
{ "resource": "" }
q258834
concatenate_textlcs
validation
def concatenate_textlcs(lclist, sortby='rjd', normalize=True): '''This concatenates a list of light curves. Does not care about overlaps or duplicates. The light curves must all be from the same aperture. The intended use is to concatenate light curves across CCDs or instrument changes for a single object. These can then be normalized later using standard astrobase tools to search for variablity and/or periodicity. sortby is a column to sort the final concatenated light curve by in ascending order. If normalize is True, then each light curve's magnitude columns are normalized to zero. The returned lcdict has an extra column: 'lcn' that tracks which measurement belongs to which input light curve. This can be used with lcdict['concatenated'] which relates input light curve index to input light curve filepath. Finally, there is an 'nconcatenated' key in the lcdict that contains the total number of concatenated light curves. ''' # read the first light curve lcdict = read_hatpi_textlc(lclist[0]) # track which LC goes where # initial LC lccounter = 0 lcdict['concatenated'] = {lccounter: os.path.abspath(lclist[0])} lcdict['lcn'] = np.full_like(lcdict['rjd'], lccounter) # normalize if needed if normalize: for col in MAGCOLS: if col in lcdict: thismedval = np.nanmedian(lcdict[col]) # handle fluxes if col in ('ifl1','ifl2','ifl3'): lcdict[col] = lcdict[col] / thismedval # handle mags else: lcdict[col] = lcdict[col] - thismedval # now read the rest for lcf in lclist[1:]: thislcd = read_hatpi_textlc(lcf)
python
{ "resource": "" }
q258835
concatenate_textlcs_for_objectid
validation
def concatenate_textlcs_for_objectid(lcbasedir, objectid, aperture='TF1', postfix='.gz', sortby='rjd', normalize=True, recursive=True): '''This concatenates all text LCs for an objectid with the given aperture. Does not care about overlaps or duplicates. The light curves must all be from the same aperture. The intended use is to concatenate light curves across CCDs or instrument changes for a single object. These can then be normalized later using standard astrobase tools to search for variablity and/or periodicity. lcbasedir is the directory to start searching in. objectid is the object to search for. aperture is the aperture postfix to use: (TF1 = aperture 1, TF2 = aperture 2, TF3 = aperture 3) sortby is a column to sort the final concatenated light curve by in ascending order. If normalize is True, then each light curve's magnitude columns are normalized to zero, and the whole light curve is then normalized to the global median magnitude for each magnitude column. If recursive is True, then the function will search recursively in lcbasedir for any light curves matching the specified criteria. This may take a while, especially on network filesystems. The returned lcdict has an extra column: 'lcn' that tracks which measurement belongs to which input light curve. This can be used with lcdict['concatenated'] which relates input light curve index to input light curve filepath. Finally, there is an 'nconcatenated' key in the lcdict that contains the total number of concatenated light curves. ''' LOGINFO('looking for light curves for %s, aperture %s in directory: %s' % (objectid, aperture, lcbasedir)) if recursive is False: matching = glob.glob(os.path.join(lcbasedir, '*%s*%s*%s' % (objectid, aperture, postfix))) else: # use recursive glob for Python 3.5+ if sys.version_info[:2] > (3,4): matching = glob.glob(os.path.join(lcbasedir, '**', '*%s*%s*%s' % (objectid, aperture, postfix)), recursive=True) LOGINFO('found %s files: %s' % (len(matching), repr(matching)))
python
{ "resource": "" }
q258836
concat_write_pklc
validation
def concat_write_pklc(lcbasedir, objectid, aperture='TF1', postfix='.gz', sortby='rjd', normalize=True, outdir=None, recursive=True): '''This concatenates all text LCs for the given object and writes to a pklc. Basically a rollup for the concatenate_textlcs_for_objectid and lcdict_to_pickle functions. ''' concatlcd = concatenate_textlcs_for_objectid(lcbasedir, objectid, aperture=aperture,
python
{ "resource": "" }
q258837
parallel_concat_worker
validation
def parallel_concat_worker(task): ''' This is a worker for the function below. task[0] = lcbasedir task[1] = objectid task[2] = {'aperture','postfix','sortby','normalize','outdir','recursive'} ''' lcbasedir, objectid, kwargs = task try: return concat_write_pklc(lcbasedir, objectid, **kwargs)
python
{ "resource": "" }
q258838
parallel_concat_lcdir
validation
def parallel_concat_lcdir(lcbasedir, objectidlist, aperture='TF1', postfix='.gz', sortby='rjd', normalize=True, outdir=None, recursive=True, nworkers=32, maxworkertasks=1000): '''This concatenates all text LCs for the given objectidlist. ''' if not outdir: outdir = 'pklcs' if not os.path.exists(outdir): os.mkdir(outdir) tasks = [(lcbasedir, x, {'aperture':aperture, 'postfix':postfix, 'sortby':sortby,
python
{ "resource": "" }
q258839
merge_hatpi_textlc_apertures
validation
def merge_hatpi_textlc_apertures(lclist): '''This merges all TFA text LCs with separate apertures for a single object. The framekey column will be used as the join column across all light curves in lclist. Missing values will be filled in with nans. This function assumes all light curves are in the format specified in COLDEFS above and readable by read_hatpi_textlc above (i.e. have a single column for TFA mags for a specific aperture at the end). ''' lcaps = {} framekeys = [] for lc in lclist: lcd = read_hatpi_textlc(lc) # figure what aperture this is and put it
python
{ "resource": "" }
q258840
generate_hatpi_binnedlc_pkl
validation
def generate_hatpi_binnedlc_pkl(binnedpklf, textlcf, timebinsec, outfile=None): ''' This reads the binned LC and writes it out to a pickle. ''' binlcdict = read_hatpi_binnedlc(binnedpklf, textlcf, timebinsec) if binlcdict: if outfile is None: outfile = os.path.join( os.path.dirname(binnedpklf), '%s-hplc.pkl' % (
python
{ "resource": "" }
q258841
parallel_gen_binnedlc_pkls
validation
def parallel_gen_binnedlc_pkls(binnedpkldir, textlcdir, timebinsec, binnedpklglob='*binned*sec*.pkl', textlcglob='*.tfalc.TF1*'): ''' This generates the binnedlc pkls for a directory of such files. FIXME: finish this
python
{ "resource": "" }
q258842
pklc_fovcatalog_objectinfo
validation
def pklc_fovcatalog_objectinfo( pklcdir, fovcatalog, fovcatalog_columns=[0,1,2, 6,7, 8,9, 10,11, 13,14,15,16, 17,18,19, 20,21], fovcatalog_colnames=['objectid','ra','decl', 'jmag','jmag_err', 'hmag','hmag_err', 'kmag','kmag_err', 'bmag','vmag','rmag','imag', 'sdssu','sdssg','sdssr', 'sdssi','sdssz'], fovcatalog_colformats=('U20,f8,f8,' 'f8,f8,' 'f8,f8,' 'f8,f8,' 'f8,f8,f8,f8,' 'f8,f8,f8,' 'f8,f8') ): '''Adds catalog info to objectinfo key of all pklcs in lcdir. If fovcatalog, fovcatalog_columns, fovcatalog_colnames are provided, uses them to find all the additional information listed in the fovcatalog_colname keys, and writes this info to the objectinfo key of each lcdict. This makes it easier for astrobase tools to work on these light curve. The default set up for fovcatalog is to use a text file generated by the HATPI pipeline before auto-calibrating a field. The format is specified as above in _columns, _colnames, and _colformats. ''' if fovcatalog.endswith('.gz'): catfd = gzip.open(fovcatalog) else: catfd = open(fovcatalog) # read the catalog using the colformats, etc. fovcat = np.genfromtxt(catfd, usecols=fovcatalog_columns, names=fovcatalog_colnames, dtype=fovcatalog_colformats) catfd.close() pklclist = sorted(glob.glob(os.path.join(pklcdir, '*HAT*-pklc.pkl'))) updatedpklcs, failedpklcs = [], [] for pklc in pklclist: lcdict = read_hatpi_pklc(pklc) objectid = lcdict['objectid'] catind = np.where(fovcat['objectid'] == objectid) # if we found catalog info for this object, put it into objectinfo if len(catind) > 0 and catind[0]:
python
{ "resource": "" }
q258843
_base64_to_file
validation
def _base64_to_file(b64str, outfpath, writetostrio=False): '''This converts the base64 encoded string to a file. Parameters ---------- b64str : str A base64 encoded strin that is the output of `base64.b64encode`. outfpath : str The path to where the file will be written. This should include an appropriate extension for the file (e.g. a base64 encoded string that represents a PNG should have its `outfpath` end in a '.png') so the OS can open these files correctly. writetostrio : bool If this is True, will return a StringIO object with the binary stream decoded from the base64-encoded input string `b64str`. This can be useful to embed these into other files without having to write them to disk. Returns ------- str or StringIO object If `writetostrio` is False, will return the output file's path as a str. If it is True, will return a StringIO object directly. If writing the file fails in either case, will return None. ''' try: filebytes = base64.b64decode(b64str) # if we're writing back to a stringio object
python
{ "resource": "" }
q258844
_read_checkplot_picklefile
validation
def _read_checkplot_picklefile(checkplotpickle): '''This reads a checkplot gzipped pickle file back into a dict. NOTE: the try-except is for Python 2 pickles that have numpy arrays in them. Apparently, these aren't compatible with Python 3. See here: http://stackoverflow.com/q/11305790 The workaround is noted in this answer: http://stackoverflow.com/a/41366785 Parameters ---------- checkplotpickle : str The path to a checkplot pickle file. This can be a gzipped file (in
python
{ "resource": "" }
q258845
make_fit_plot
validation
def make_fit_plot(phase, pmags, perrs, fitmags, period, mintime, magseriesepoch, plotfit, magsarefluxes=False, wrap=False, model_over_lc=False): '''This makes a plot of the LC model fit. Parameters ---------- phase,pmags,perrs : np.array The actual mag/flux time-series. fitmags : np.array The model fit time-series. period : float The period at which the phased LC was generated. mintime : float The minimum time value. magseriesepoch : float The value of time around which the phased LC was folded. plotfit : str The name of a file to write the plot to. magsarefluxes : bool Set this to True if the values in `pmags` and `fitmags` are actually fluxes. wrap : bool If True, will wrap the phased LC around 0.0 to make some phased LCs easier to look at. model_over_lc : bool Usually, this function will plot the actual LC over the model LC. Set this to True to plot the model over the actual LC; this is most useful when you have a very dense light curve and want to be able to see how it follows the model. Returns ------- Nothing. ''' # set up the figure plt.close('all') plt.figure(figsize=(8,4.8)) if model_over_lc: model_z = 100 lc_z = 0 else: model_z = 0 lc_z = 100 if not wrap: plt.plot(phase, fitmags, linewidth=3.0, color='red',zorder=model_z) plt.plot(phase,pmags, marker='o', markersize=1.0, linestyle='none', rasterized=True, color='k',zorder=lc_z) # set the x axis ticks and label plt.gca().set_xticks( [0.0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0] ) else: plt.plot(np.concatenate([phase-1.0,phase]),
python
{ "resource": "" }
q258846
objectlist_conesearch
validation
def objectlist_conesearch(racenter, declcenter, searchradiusarcsec, gaia_mirror=None, columns=('source_id', 'ra','dec', 'phot_g_mean_mag', 'l','b', 'parallax', 'parallax_error', 'pmra','pmra_error', 'pmdec','pmdec_error'), extra_filter=None, returnformat='csv', forcefetch=False, cachedir='~/.astrobase/gaia-cache', verbose=True, timeout=15.0, refresh=2.0, maxtimeout=300.0, maxtries=3, complete_query_later=True): '''This queries the GAIA TAP service for a list of objects near the coords. Runs a conesearch around `(racenter, declcenter)` with radius in arcsec of `searchradiusarcsec`. Parameters ---------- racenter,declcenter : float The center equatorial coordinates in decimal degrees. searchradiusarcsec : float The search radius of the cone-search in arcseconds. gaia_mirror : {'gaia','heidelberg','vizier'} or None This is the key used to select a GAIA catalog mirror from the `GAIA_URLS` dict above. If set, the specified mirror will be used. If None, a random mirror chosen from that dict will be used. columns : sequence of str This indicates which columns from the GAIA table to request for the objects found within the search radius. extra_filter: str or None If this is provided, must be a valid ADQL filter string that is used to further filter the cone-search results. returnformat : {'csv','votable','json'} The returned file format to request from the GAIA catalog service. forcefetch : bool If this is True, the query will be retried even if cached results for it exist. cachedir : str This points to the directory where results will be downloaded. verbose : bool If True, will indicate progress and warn of any issues. timeout : float This sets the amount of time in seconds to wait for the service to respond to our initial request. refresh : float This sets the amount of time in seconds to wait before checking if the result file is available. If the results file isn't available after `refresh` seconds have elapsed, the function will wait for `refresh` seconds continuously, until `maxtimeout` is reached or the results file becomes available. maxtimeout : float The maximum amount of time in seconds to wait for a result to become available after submitting our query request. maxtries : int The maximum number of tries (across all mirrors tried) to make to either submit the request or download the results, before giving up. completequerylater : bool If set to True, a submitted query that does not return a result before `maxtimeout` has passed will be cancelled but its input request parameters and the result URL provided by
python
{ "resource": "" }
q258847
objectlist_radeclbox
validation
def objectlist_radeclbox(radeclbox, gaia_mirror=None, columns=('source_id', 'ra','dec', 'phot_g_mean_mag', 'l','b', 'parallax, parallax_error', 'pmra','pmra_error', 'pmdec','pmdec_error'), extra_filter=None, returnformat='csv', forcefetch=False, cachedir='~/.astrobase/gaia-cache', verbose=True, timeout=15.0, refresh=2.0, maxtimeout=300.0, maxtries=3, complete_query_later=True): '''This queries the GAIA TAP service for a list of objects in an equatorial coordinate box. Parameters ---------- radeclbox : sequence of four floats This defines the box to search in:: [ra_min, ra_max, decl_min, decl_max] gaia_mirror : {'gaia','heidelberg','vizier'} or None This is the key used to select a GAIA catalog mirror from the `GAIA_URLS` dict above. If set, the specified mirror will be used. If None, a random mirror chosen from that dict will be used. columns : sequence of str This indicates which columns from the GAIA table to request for the objects found within the search radius. extra_filter: str or None If this is provided, must be a valid ADQL filter string that is used to further filter the cone-search results. returnformat : {'csv','votable','json'} The returned file format to request from the GAIA catalog service. forcefetch : bool If this is True, the query will be retried even if cached results for it exist. cachedir : str This points to the directory where results will be downloaded. verbose : bool If True, will indicate progress and warn of any issues. timeout : float This sets the amount of time in seconds to wait for the service to respond to our initial request. refresh : float This sets the amount of time in seconds to wait before checking if the result file is available. If the results file isn't available after `refresh` seconds have elapsed, the function will wait for `refresh` seconds continuously, until `maxtimeout` is reached or the results file becomes available. maxtimeout : float The maximum amount of time in seconds to wait for a result to become available after submitting our query request. maxtries : int The maximum number of tries (across all mirrors tried) to make to either submit the request or download the results, before giving up. completequerylater : bool If set to True, a submitted query that does not return a result before `maxtimeout` has passed will be cancelled but its input request parameters and the result URL provided by the service will be saved. If this function is then called later with these same input request parameters, it will check if the query finally finished and a result is
python
{ "resource": "" }
q258848
objectid_search
validation
def objectid_search(gaiaid, gaia_mirror=None, columns=('source_id', 'ra','dec', 'phot_g_mean_mag', 'phot_bp_mean_mag', 'phot_rp_mean_mag', 'l','b', 'parallax, parallax_error', 'pmra','pmra_error', 'pmdec','pmdec_error'), returnformat='csv', forcefetch=False, cachedir='~/.astrobase/gaia-cache', verbose=True, timeout=15.0, refresh=2.0, maxtimeout=300.0, maxtries=3, complete_query_later=True): '''This queries the GAIA TAP service for a single GAIA source ID. Parameters ---------- gaiaid : str The source ID of the object whose info will be collected. gaia_mirror : {'gaia','heidelberg','vizier'} or None This is the key used to select a GAIA catalog mirror from the `GAIA_URLS` dict above. If set, the specified mirror will be used. If None, a random mirror chosen from that dict will be used. columns : sequence of str This indicates which columns from the GAIA table to request for the objects found within the search radius. returnformat : {'csv','votable','json'} The returned file format to request from the GAIA catalog service. forcefetch : bool If this is True, the query will be retried even if cached results for it exist. cachedir : str This points to the directory where results will be downloaded. verbose : bool If True, will indicate progress and warn of any issues. timeout : float This sets the amount of time in seconds to wait for the service to respond to our initial request. refresh : float This sets the amount of time in seconds to wait before checking if the result file is available. If the results file isn't available after `refresh` seconds have elapsed, the function will wait for `refresh` seconds continuously, until `maxtimeout` is reached or the results file becomes available. maxtimeout : float The maximum amount of time in seconds to wait for a result to become available after submitting our query request. maxtries : int The maximum number of tries (across all mirrors tried) to make to either submit the request or download the results, before giving up. completequerylater : bool If set to True, a submitted query that does not return a result before `maxtimeout` has passed will be cancelled but its input request parameters and the result
python
{ "resource": "" }
q258849
generalized_lsp_value_notau
validation
def generalized_lsp_value_notau(times, mags, errs, omega): ''' This is the simplified version not using tau. The relations used are:: W = sum (1.0/(errs*errs) ) w_i = (1/W)*(1/(errs*errs)) Y = sum( w_i*y_i ) C = sum( w_i*cos(wt_i) ) S = sum( w_i*sin(wt_i) ) YY = sum( w_i*y_i*y_i ) - Y*Y YC = sum( w_i*y_i*cos(wt_i) ) - Y*C YS = sum( w_i*y_i*sin(wt_i) ) - Y*S CpC = sum( w_i*cos(w_t_i)*cos(w_t_i) ) CC = CpC - C*C SS = (1 - CpC) - S*S CS = sum( w_i*cos(w_t_i)*sin(w_t_i) ) - C*S D(omega) = CC*SS - CS*CS P(omega) = (SS*YC*YC + CC*YS*YS - 2.0*CS*YC*YS)/(YY*D) Parameters ---------- times,mags,errs : np.array The time-series to calculate the periodogram value for. omega : float The frequency to calculate the periodogram value at. Returns ------- periodogramvalue : float The normalized periodogram at the specified test frequency `omega`. ''' one_over_errs2 = 1.0/(errs*errs) W = npsum(one_over_errs2) wi = one_over_errs2/W sin_omegat = npsin(omega*times) cos_omegat = npcos(omega*times) sin2_omegat = sin_omegat*sin_omegat cos2_omegat = cos_omegat*cos_omegat sincos_omegat = sin_omegat*cos_omegat # calculate some more sums and terms Y = npsum( wi*mags
python
{ "resource": "" }
q258850
specwindow_lsp_value
validation
def specwindow_lsp_value(times, mags, errs, omega): '''This calculates the peak associated with the spectral window function for times and at the specified omega. NOTE: this is classical Lomb-Scargle, not the Generalized Lomb-Scargle. `mags` and `errs` are silently ignored since we're calculating the periodogram of the observing window function. These are kept to present a consistent external API so the `pgen_lsp` function below can call this transparently. Parameters ---------- times,mags,errs : np.array The time-series to calculate the periodogram value for. omega : float The frequency to calculate the periodogram value at. Returns ------- periodogramvalue : float The normalized periodogram at the specified test frequency `omega`. ''' norm_times = times - times.min() tau = ( (1.0/(2.0*omega)) * nparctan( npsum(npsin(2.0*omega*norm_times)) / npsum(npcos(2.0*omega*norm_times)) ) ) lspval_top_cos = (npsum(1.0 * npcos(omega*(norm_times-tau))) * npsum(1.0 * npcos(omega*(norm_times-tau))))
python
{ "resource": "" }
q258851
specwindow_lsp
validation
def specwindow_lsp( times, mags, errs, magsarefluxes=False, startp=None, endp=None, stepsize=1.0e-4, autofreq=True, nbestpeaks=5, periodepsilon=0.1, sigclip=10.0, nworkers=None, glspfunc=_glsp_worker_specwindow, verbose=True ): '''This calculates the spectral window function. Wraps the `pgen_lsp` function above to use the specific worker for calculating the window-function. Parameters ---------- times,mags,errs : np.array The mag/flux time-series with associated measurement errors to run the period-finding on. magsarefluxes : bool If the input measurement values in `mags` and `errs` are in fluxes, set this to True. startp,endp : float or None The minimum and maximum periods to consider for the transit search. stepsize : float The step-size in frequency to use when constructing a frequency grid for the period search. autofreq : bool If this is True, the value of `stepsize` will be ignored and the :py:func:`astrobase.periodbase.get_frequency_grid` function will be used to generate a frequency grid based on `startp`, and `endp`. If these are None as well, `startp` will be set to 0.1 and `endp` will be set to `times.max() - times.min()`. nbestpeaks : int The number of 'best' peaks to return from the periodogram results, starting from the global maximum of the periodogram peak values. periodepsilon : float The fractional difference between successive values of 'best' periods when sorting by periodogram power to consider them as separate periods (as opposed to part of the same periodogram peak). This is used to avoid broad peaks in the periodogram and make sure the 'best' periods returned are all actually independent. sigclip : float or int or sequence of two floats/ints or None If a single float or int, a symmetric sigma-clip will be performed using the number provided as the sigma-multiplier to cut out from the input time-series. If a list of two ints/floats is provided, the function will perform an 'asymmetric' sigma-clip. The first element in this list is the sigma value to use for fainter flux/mag values; the second element in this list is the sigma value to use for brighter flux/mag values. For example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma dimmings and greater than 3-sigma brightenings. Here the meaning of "dimming" and "brightening" is set by *physics* (not the magnitude system), which is why the `magsarefluxes` kwarg must be correctly set. If `sigclip` is None, no sigma-clipping will be performed, and the time-series (with non-finite elems removed) will be passed through to the output. nworkers : int The number of parallel workers to use when calculating the periodogram. glspfunc : Python function The worker function to use to calculate the periodogram. This is used to used to make the `pgen_lsp` function calculate the time-series sampling window function instead of the time-series measurements' GLS periodogram
python
{ "resource": "" }
q258852
check_existing_apikey
validation
def check_existing_apikey(lcc_server): '''This validates if an API key for the specified LCC-Server is available. API keys are stored using the following file scheme:: ~/.astrobase/lccs/apikey-domain.of.lccserver.org e.g. for the HAT LCC-Server at https://data.hatsurveys.org:: ~/.astrobase/lccs/apikey-https-data.hatsurveys.org Parameters ---------- lcc_server : str The base URL of the LCC-Server for which the existence of API keys will be checked. Returns ------- (apikey_ok, apikey_str, expiry) : tuple The returned tuple contains the status of the API key, the API key itself if present, and its expiry date if present. ''' USERHOME = os.path.expanduser('~') APIKEYFILE = os.path.join(USERHOME, '.astrobase', 'lccs', 'apikey-%s' % lcc_server.replace( 'https://', 'https-' ).replace( 'http://', 'http-' )) if os.path.exists(APIKEYFILE): # check if this file is readable/writeable by user only fileperm = oct(os.stat(APIKEYFILE)[stat.ST_MODE]) if fileperm == '0100600' or fileperm == '0o100600': with open(APIKEYFILE) as infd: apikey, expires = infd.read().strip('\n').split() # get today's datetime now = datetime.now(utc) if sys.version_info[:2] < (3,7): # this hideous incantation is required for lesser Pythons
python
{ "resource": "" }
q258853
get_new_apikey
validation
def get_new_apikey(lcc_server): '''This gets a new API key from the specified LCC-Server. NOTE: this only gets an anonymous API key. To get an API key tied to a user account (and associated privilege level), see the `import_apikey` function below. Parameters ---------- lcc_server : str The base URL of the LCC-Server from where the API key will be fetched. Returns ------- (apikey, expiry) : tuple This returns a tuple with the API key and its expiry date. ''' USERHOME = os.path.expanduser('~') APIKEYFILE = os.path.join(USERHOME, '.astrobase', 'lccs', 'apikey-%s' % lcc_server.replace( 'https://', 'https-'
python
{ "resource": "" }
q258854
import_apikey
validation
def import_apikey(lcc_server, apikey_text_json): '''This imports an API key from text and writes it to the cache dir. Use this with the JSON text copied from the API key text box on your LCC-Server user home page. The API key will thus be tied to the privileges of that user account and can then access objects, datasets, and collections marked as private for the user only or shared with that user. Parameters ---------- lcc_server : str The base URL of the LCC-Server to get the API key for. apikey_text_json : str The JSON string from the API key text box on the user's LCC-Server home page at `lcc_server/users/home`. Returns ------- (apikey, expiry) : tuple This returns a tuple with the API key and its expiry date. ''' USERHOME = os.path.expanduser('~') APIKEYFILE = os.path.join(USERHOME, '.astrobase', 'lccs', 'apikey-%s' % lcc_server.replace( 'https://', 'https-' ).replace( 'http://', 'http-'
python
{ "resource": "" }
q258855
submit_post_searchquery
validation
def submit_post_searchquery(url, data, apikey): '''This submits a POST query to an LCC-Server search API endpoint. Handles streaming of the results, and returns the final JSON stream. Also handles results that time out. Parameters ---------- url : str The URL of the search API endpoint to hit. This is something like `https://data.hatsurveys.org/api/conesearch` data : dict A dict of the search query parameters to pass to the search service. apikey : str The API key to use to access the search service. API keys are required for all POST request made to an LCC-Server's API endpoints. Returns ------- (status_flag, data_dict, dataset_id) : tuple This returns a tuple containing the status of the request: ('complete', 'failed', 'background', etc.), a dict parsed from the JSON result of the request, and a dataset ID, which can be used to reconstruct the URL on the LCC-Server where the results can be browsed. ''' # first, we need to convert any columns and collections items to broken out # params postdata = {} for key in data: if key == 'columns': postdata['columns[]'] = data[key] elif key == 'collections': postdata['collections[]'] = data[key] else: postdata[key] = data[key] # do the urlencode with doseq=True # we also need to encode to bytes encoded_postdata = urlencode(postdata, doseq=True).encode() # if apikey is not None, add it in as an Authorization: Bearer [apikey] # header if apikey: headers = {'Authorization':'Bearer: %s' % apikey} else: headers = {} LOGINFO('submitting search query to LCC-Server API URL: %s' % url) try: # hit the server with a POST request req = Request(url, data=encoded_postdata, headers=headers) resp = urlopen(req) if resp.code == 200: # we'll iterate over the lines in the response # this works super-well for ND-JSON! for line in resp: data = json.loads(line) msg = data['message'] status = data['status'] if status != 'failed': LOGINFO('status: %s, %s' % (status, msg)) else: LOGERROR('status: %s, %s' % (status, msg)) # here, we'll decide what to do about the query # completed query or query sent to background... if status in ('ok','background'): setid = data['result']['setid'] # save the data pickle to astrobase lccs directory outpickle = os.path.join(os.path.expanduser('~'), '.astrobase', 'lccs', 'query-%s.pkl' % setid) if not os.path.exists(os.path.dirname(outpickle)):
python
{ "resource": "" }
q258856
cone_search
validation
def cone_search(lcc_server, center_ra, center_decl, radiusarcmin=5.0, result_visibility='unlisted', email_when_done=False, collections=None, columns=None, filters=None, sortspec=None, samplespec=None, limitspec=None, download_data=True, outdir=None, maxtimeout=300.0, refresh=15.0): '''This runs a cone-search query. Parameters ---------- lcc_server : str This is the base URL of the LCC-Server to talk to. (e.g. for HAT, use: https://data.hatsurveys.org) center_ra,center_decl : float These are the central coordinates of the search to conduct. These can be either decimal degrees of type float, or sexagesimal coordinates of type str: - OK: 290.0, 45.0 - OK: 15:00:00 +45:00:00 - OK: 15 00 00.0 -45 00 00.0 - NOT OK: 290.0 +45:00:00 - NOT OK: 15:00:00 45.0 radiusarcmin : float This is the search radius to use for the cone-search. This is in arcminutes. The maximum radius you can use is 60 arcminutes = 1 degree. result_visibility : {'private', 'unlisted', 'public'} This sets the visibility of the dataset produced from the search result:: 'private' -> the dataset and its products are not visible or accessible by any user other than the one that created the dataset. 'unlisted' -> the dataset and its products are not visible in the list of public datasets, but can be accessed if the dataset URL is known 'public' -> the dataset and its products are visible in the list of public datasets and can be accessed by anyone. email_when_done : bool If True, the LCC-Server will email you when the search is complete. This will also set `download_data` to False. Using this requires an LCC-Server account and an API key tied to that account. collections : list of str or None This is a list of LC collections to search in. If this is None, all collections will be searched. columns : list of str or None This is a list of columns to return in the results. Matching objects' object IDs, RAs, DECs, and links to light curve files will always be returned so there is no need to specify these columns. If None, only these columns will be returned: 'objectid', 'ra', 'decl', 'lcfname' filters : str or None This is an SQL-like string to use to filter on database columns in the LCC-Server's collections. To see the columns available for a search, visit the Collections tab in the LCC-Server's browser UI. The filter operators allowed are:: lt -> less than gt -> greater than ge -> greater than or equal to le -> less than or equal to eq -> equal to ne -> not equal to ct -> contains text isnull -> column value is null notnull -> column value is not null You may use the `and` and `or` operators between filter specifications to chain them together logically. Example filter strings:: "(propermotion gt 200.0) and (sdssr lt 11.0)" "(dered_jmag_kmag gt 2.0) and (aep_000_stetsonj gt 10.0)" "(gaia_status ct 'ok') and (propermotion gt 300.0)" "(simbad_best_objtype ct 'RR') and (dered_sdssu_sdssg lt 0.5)" sortspec : tuple of two strs or None If not None, this should be a tuple of two items:: ('column to sort by', 'asc|desc') This sets the column to sort the results by. For cone_search, the default column and sort order are 'dist_arcsec' and 'asc', meaning the distance from the search center in ascending order. samplespec : int or None If this is an int, will indicate how many rows from the initial search result will be uniformly random sampled and returned. limitspec : int or None If this is an int, will indicate how many rows from the initial search result to return in total. `sortspec`, `samplespec`, and `limitspec` are applied in this order: sample -> sort -> limit download_data : bool This sets if the accompanying data from the search results will be downloaded automatically. This includes the data table CSV, the dataset pickle file, and a light curve ZIP file. Note that if the search service indicates that your query is still in progress, this function will block until the light curve ZIP file becomes available. The maximum wait time in seconds is set by maxtimeout and the refresh interval is set by refresh. To avoid the wait block, set download_data to False and the function will write a pickle file to `~/.astrobase/lccs/query-[setid].pkl` containing all the information necessary to retrieve these data files later when the query is done. To do so, call the `retrieve_dataset_files` with the path to this pickle file (it will be returned). outdir : str or None If this is provided, sets the output directory of the downloaded dataset files. If None, they will be downloaded to the current directory. maxtimeout : float The maximum time in seconds to wait for the LCC-Server to respond with a result before timing out. You can use the `retrieve_dataset_files`
python
{ "resource": "" }
q258857
xmatch_search
validation
def xmatch_search(lcc_server, file_to_upload, xmatch_dist_arcsec=3.0, result_visibility='unlisted', email_when_done=False, collections=None, columns=None, filters=None, sortspec=None, limitspec=None, samplespec=None, download_data=True, outdir=None, maxtimeout=300.0, refresh=15.0): '''This runs a cross-match search query. Parameters ---------- lcc_server : str This is the base URL of the LCC-Server to talk to. (e.g. for HAT, use: https://data.hatsurveys.org) file_to_upload : str This is the path to a text file containing objectid, RA, declination rows for the objects to cross-match against the LCC-Server collections. This should follow the format of the following example:: # example object and coordinate list # objectid ra dec aaa 289.99698 44.99839 bbb 293.358 -23.206 ccc 294.197 +23.181 ddd 19 25 27.9129 +42 47 03.693 eee 19:25:27 -42:47:03.21 # . # . # . # etc. lines starting with '#' will be ignored # (max 5000 objects) xmatch_dist_arcsec : float This is the maximum distance in arcseconds to consider when cross-matching objects in the uploaded file to the LCC-Server's collections. The maximum allowed distance is 30 arcseconds. Multiple matches to an uploaded object are possible and will be returned in order of increasing distance grouped by input `objectid`. result_visibility : {'private', 'unlisted', 'public'} This sets the visibility of the dataset produced from the search result:: 'private' -> the dataset and its products are not visible or accessible by any user other than the one that created the dataset. 'unlisted' -> the dataset and its products are not visible in the list of public datasets, but can be accessed if the dataset URL is known 'public' -> the dataset and its products are visible in the list of public datasets and can be accessed by anyone. email_when_done : bool If True, the LCC-Server will email you when the search is complete. This will also set `download_data` to False. Using this requires an LCC-Server account and an API key tied to that account. collections : list of str or None This is a list of LC collections to search in. If this is None, all collections will be searched. columns : list of str or None This is a list of columns to return in the results. Matching objects' object IDs, RAs, DECs, and links to light curve files will always be returned so there is no need to specify these columns. If None, only these columns will be returned: 'objectid', 'ra', 'decl', 'lcfname' filters : str or None This is an SQL-like string to use to filter on database columns in the LCC-Server's collections. To see the columns available for a search, visit the Collections tab in the LCC-Server's browser UI. The filter operators allowed are:: lt -> less than gt -> greater than ge -> greater than or equal to le -> less than or equal to eq -> equal to ne -> not equal to ct -> contains text isnull -> column value is null notnull -> column value is not null You may use the `and` and `or` operators between filter specifications to chain them together logically. Example filter strings:: "(propermotion gt 200.0) and (sdssr lt 11.0)" "(dered_jmag_kmag gt 2.0) and (aep_000_stetsonj gt 10.0)" "(gaia_status ct 'ok') and (propermotion gt 300.0)" "(simbad_best_objtype ct 'RR') and (dered_sdssu_sdssg lt 0.5)" sortspec : tuple of two strs or None If not None, this should be a tuple of two items:: ('column to sort by', 'asc|desc') This sets the column to sort the results by. For cone_search, the default column and sort order are 'dist_arcsec' and 'asc', meaning the distance from the search center in ascending order. samplespec : int or None If this is an int, will indicate how many rows from the initial search result will be uniformly random sampled and returned. limitspec : int or None If this is an int, will indicate how many rows from the initial search result to return in total. `sortspec`, `samplespec`, and `limitspec` are applied in this order: sample -> sort -> limit download_data : bool This sets if the accompanying data from the search results will be downloaded automatically. This includes the data table CSV, the dataset pickle file, and a light curve ZIP file. Note that if the search service indicates that your query is still in progress, this function will block until the light curve ZIP file becomes available. The maximum wait time in seconds is set by maxtimeout and the refresh interval is set by refresh. To avoid the wait block, set download_data to False and the function will write a pickle file to `~/.astrobase/lccs/query-[setid].pkl` containing all the information necessary to retrieve these data files later when the query is done. To do so, call the `retrieve_dataset_files` with the path to this pickle file (it will be returned). outdir : str or None If this is provided, sets the output directory of the downloaded dataset
python
{ "resource": "" }
q258858
get_dataset
validation
def get_dataset(lcc_server, dataset_id, strformat=False, page=1): '''This downloads a JSON form of a dataset from the specified lcc_server. If the dataset contains more than 1000 rows, it will be paginated, so you must use the `page` kwarg to get the page you want. The dataset JSON will contain the keys 'npages', 'currpage', and 'rows_per_page' to help with this. The 'rows' key contains the actual data rows as a list of tuples. The JSON contains metadata about the query that produced the dataset, information about the data table's columns, and links to download the dataset's products including the light curve ZIP and the dataset CSV. Parameters ---------- lcc_server : str This is the base URL of the LCC-Server to talk to. dataset_id : str This is the unique setid of the dataset you want to get. In the results from the `*_search` functions above, this is the value of the `infodict['result']['setid']` key in the first item (the infodict) in the returned tuple. strformat : bool This sets if you want the returned data rows to be formatted in their string representations already. This can be useful
python
{ "resource": "" }
q258859
object_info
validation
def object_info(lcc_server, objectid, db_collection_id): '''This gets information on a single object from the LCC-Server. Returns a dict with all of the available information on an object, including finding charts, comments, object type and variability tags, and period-search results (if available). If you have an LCC-Server API key present in `~/.astrobase/lccs/` that is associated with an LCC-Server user account, objects that are visible to this user will be returned, even if they are not visible to the public. Use this to look up objects that have been marked as 'private' or 'shared'. NOTE: you can pass the result dict returned by this function directly into the `astrobase.checkplot.checkplot_pickle_to_png` function, e.g.:: astrobase.checkplot.checkplot_pickle_to_png(result_dict, 'object-%s-info.png' % result_dict['objectid']) to generate a quick PNG overview of the object information. Parameters ---------- lcc_server : str This is the base URL of the LCC-Server to talk to. objectid : str This is the unique database ID of the object to retrieve info for. This is always returned as the `db_oid` column in LCC-Server search results. db_collection_id : str This is the collection ID which will be searched for the object. This is always returned as the `collection` column in LCC-Server search results. Returns ------- dict A dict containing the object info is returned. Some important items in the result dict: - `objectinfo`: all object magnitude, color, GAIA cross-match, and object type information available for this object - `objectcomments`: comments on the object's variability if available - `varinfo`: variability comments, variability features, type tags, period and epoch information if available - `neighbors`: information on the neighboring objects of this object in its parent light curve collection - `xmatch`: information on any cross-matches to external catalogs (e.g. KIC, EPIC, TIC, APOGEE, etc.) - `finderchart`: a base-64 encoded PNG image of the object's DSS2 RED finder chart. To convert this to an actual PNG, try the function: `astrobase.checkplot.pkl_io._b64_to_file`. - `magseries`: a base-64 encoded PNG image of the object's light curve. To convert this to an actual PNG, try the function: `astrobase.checkplot.pkl_io._b64_to_file`. - `pfmethods`: a list of period-finding methods applied to the object if any. If this list is present, use the keys in it to get to the actual period-finding results for each method. These will contain base-64 encoded
python
{ "resource": "" }
q258860
list_recent_datasets
validation
def list_recent_datasets(lcc_server, nrecent=25): '''This lists recent publicly visible datasets available on the LCC-Server. If you have an LCC-Server API key present in `~/.astrobase/lccs/` that is associated with an LCC-Server user account, datasets that belong to this user will be returned as well, even if they are not visible to the public. Parameters ---------- lcc_server : str This is the base URL of the LCC-Server to talk to. nrecent : int This indicates how many recent public datasets you want to list. This is always capped at 1000. Returns ------- list of dicts Returns a list of dicts, with each dict containing info on each dataset. ''' urlparams = {'nsets':nrecent} urlqs = urlencode(urlparams) url = '%s/api/datasets?%s' % (lcc_server, urlqs) try: LOGINFO( 'getting list of recent publicly ' 'visible and owned datasets from %s' % ( lcc_server, ) ) # check if we have an API key already have_apikey, apikey, expires = check_existing_apikey(lcc_server)
python
{ "resource": "" }
q258861
list_lc_collections
validation
def list_lc_collections(lcc_server): '''This lists all light curve collections made available on the LCC-Server. If you have an LCC-Server API key present in `~/.astrobase/lccs/` that is associated with an LCC-Server user account, light curve collections visible to this user will be returned as well, even if they are not visible to the public. Parameters ---------- lcc_server : str The base URL of the LCC-Server to talk to. Returns ------- dict Returns a dict containing lists of info items per collection. This includes collection_ids, lists of columns, lists of indexed columns, lists of full-text indexed columns, detailed column descriptions, number of objects in each collection, collection sky coverage, etc. ''' url = '%s/api/collections' % lcc_server try: LOGINFO( 'getting list of recent publicly visible ' 'and owned LC collections from %s' % ( lcc_server, ) ) # check if we have an API key already have_apikey, apikey, expires = check_existing_apikey(lcc_server)
python
{ "resource": "" }
q258862
stetson_jindex
validation
def stetson_jindex(ftimes, fmags, ferrs, weightbytimediff=False): '''This calculates the Stetson index for the magseries, based on consecutive pairs of observations. Based on Nicole Loncke's work for her Planets and Life certificate at Princeton in 2014. Parameters ---------- ftimes,fmags,ferrs : np.array The input mag/flux time-series with all non-finite elements removed. weightbytimediff : bool If this is True, the Stetson index for any pair of mags will be reweighted by the difference in times between them using the scheme in Fruth+ 2012 and Zhange+ 2003 (as seen in Sokolovsky+ 2017):: w_i = exp(- (t_i+1 - t_i)/ delta_t ) Returns ------- float The calculated Stetson J variability index. ''' ndet = len(fmags) if ndet > 9: # get the median and ndet medmag = npmedian(fmags) # get the stetson index elements delta_prefactor = (ndet/(ndet - 1)) sigma_i = delta_prefactor*(fmags - medmag)/ferrs # Nicole's clever trick to advance indices by 1 and do x_i*x_(i+1)
python
{ "resource": "" }
q258863
lightcurve_moments
validation
def lightcurve_moments(ftimes, fmags, ferrs): '''This calculates the weighted mean, stdev, median, MAD, percentiles, skew, kurtosis, fraction of LC beyond 1-stdev, and IQR. Parameters ---------- ftimes,fmags,ferrs : np.array The input mag/flux time-series with all non-finite elements removed. Returns ------- dict A dict with all of the light curve moments calculated. ''' ndet = len(fmags) if ndet > 9: # now calculate the various things we need series_median = npmedian(fmags) series_wmean = ( npsum(fmags*(1.0/(ferrs*ferrs)))/npsum(1.0/(ferrs*ferrs)) ) series_mad = npmedian(npabs(fmags - series_median)) series_stdev = 1.483*series_mad series_skew = spskew(fmags) series_kurtosis = spkurtosis(fmags) # get the beyond1std fraction series_above1std = len(fmags[fmags > (series_median + series_stdev)]) series_below1std = len(fmags[fmags < (series_median - series_stdev)]) # this is the fraction beyond 1 stdev series_beyond1std = (series_above1std + series_below1std)/float(ndet) # get the magnitude percentiles series_mag_percentiles = nppercentile( fmags,
python
{ "resource": "" }
q258864
lightcurve_flux_measures
validation
def lightcurve_flux_measures(ftimes, fmags, ferrs, magsarefluxes=False): '''This calculates percentiles and percentile ratios of the flux. Parameters ---------- ftimes,fmags,ferrs : np.array The input mag/flux time-series with all non-finite elements removed. magsarefluxes : bool If the `fmags` array actually contains fluxes, will not convert `mags` to fluxes before calculating the percentiles. Returns ------- dict A dict with all of the light curve flux percentiles and percentile ratios calculated. ''' ndet = len(fmags) if ndet > 9: # get the fluxes if magsarefluxes: series_fluxes = fmags else: series_fluxes = 10.0**(-0.4*fmags) series_flux_median = npmedian(series_fluxes) # get the percent_amplitude for the fluxes series_flux_percent_amplitude = ( npmax(npabs(series_fluxes))/series_flux_median ) # get the flux percentiles series_flux_percentiles = nppercentile( series_fluxes, [5.0,10,17.5,25,32.5,40,60,67.5,75,82.5,90,95] ) series_frat_595 = ( series_flux_percentiles[-1] - series_flux_percentiles[0] ) series_frat_1090 = ( series_flux_percentiles[-2] - series_flux_percentiles[1] ) series_frat_175825 = ( series_flux_percentiles[-3] - series_flux_percentiles[2] ) series_frat_2575 = ( series_flux_percentiles[-4] - series_flux_percentiles[3] ) series_frat_325675 = ( series_flux_percentiles[-5] - series_flux_percentiles[4] ) series_frat_4060 = ( series_flux_percentiles[-6] - series_flux_percentiles[5]
python
{ "resource": "" }
q258865
all_nonperiodic_features
validation
def all_nonperiodic_features(times, mags, errs, magsarefluxes=False, stetson_weightbytimediff=True): '''This rolls up the feature functions above and returns a single dict. NOTE: this doesn't calculate the CDPP to save time since binning and smoothing takes a while for dense light curves. Parameters ---------- times,mags,errs : np.array The input mag/flux time-series to calculate CDPP for. magsarefluxes : bool If True, indicates `mags` is actually an array of flux values. stetson_weightbytimediff : bool If this is True, the Stetson index for any pair of mags will be
python
{ "resource": "" }
q258866
_bls_runner
validation
def _bls_runner(times, mags, nfreq, freqmin, stepsize, nbins, minduration, maxduration): '''This runs the pyeebls.eebls function using the given inputs. Parameters ---------- times,mags : np.array The input magnitude time-series to search for transits. nfreq : int The number of frequencies to use when searching for transits. freqmin : float The minimum frequency of the period-search -> max period that will be used for the search. stepsize : float The step-size in frequency to use to generate a frequency-grid. nbins : int The number of phase bins to use. minduration : float The minimum fractional transit duration that will be considered. maxduration : float The maximum fractional transit duration that will be considered. Returns ------- dict Returns a dict of the form:: { 'power': the periodogram power array, 'bestperiod': the best period found,
python
{ "resource": "" }
q258867
_parallel_bls_worker
validation
def _parallel_bls_worker(task): ''' This wraps the BLS function for the parallel driver below. Parameters ---------- tasks : tuple This is of the form:: task[0] = times task[1] = mags task[2] = nfreq task[3] = freqmin task[4] = stepsize task[5] = nbins task[6] = minduration task[7] = maxduration Returns ------- dict Returns a dict of the form:: { 'power': the periodogram power array, 'bestperiod': the best period found, 'bestpower': the highest peak of the periodogram power, 'transdepth': transit depth found by eebls.f, 'transduration': transit duration found by eebls.f, 'transingressbin': transit ingress bin found by eebls.f, 'transegressbin': transit egress
python
{ "resource": "" }
q258868
bls_stats_singleperiod
validation
def bls_stats_singleperiod(times, mags, errs, period, magsarefluxes=False, sigclip=10.0, perioddeltapercent=10, nphasebins=200, mintransitduration=0.01, maxtransitduration=0.4, ingressdurationfraction=0.1, verbose=True): '''This calculates the SNR, depth, duration, a refit period, and time of center-transit for a single period. The equation used for SNR is:: SNR = (transit model depth / RMS of LC with transit model subtracted) * sqrt(number of points in transit) NOTE: you should set the kwargs `sigclip`, `nphasebins`, `mintransitduration`, `maxtransitduration` to what you used for an initial BLS run to detect transits in the input light curve to match those input conditions. Parameters ---------- times,mags,errs : np.array These contain the magnitude/flux time-series and any associated errors. period : float The period to search around and refit the transits. This will be used to calculate the start and end periods of a rerun of BLS to calculate the stats. magsarefluxes : bool Set to True if the input measurements in `mags` are actually fluxes and not magnitudes. sigclip : float or int or sequence of two floats/ints or None If a single float or int, a symmetric sigma-clip will be performed using the number provided as the sigma-multiplier to cut out from the input time-series. If a list of two ints/floats is provided, the function will perform an 'asymmetric' sigma-clip. The first element in this list is the sigma value to use for fainter flux/mag values; the second element in this list is the sigma value to use for brighter flux/mag values. For example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma dimmings and greater than 3-sigma brightenings. Here the meaning of "dimming" and "brightening" is set by *physics* (not the magnitude system), which is why the `magsarefluxes` kwarg must be correctly set. If `sigclip` is None, no sigma-clipping will be performed, and the time-series (with non-finite elems removed) will be passed through to the output. perioddeltapercent : float The fraction of the period provided to use to search around this value. This is a percentage. The period range searched will then be:: [period - (perioddeltapercent/100.0)*period, period + (perioddeltapercent/100.0)*period] nphasebins : int The number of phase bins to use in the BLS run. mintransitduration : float The minimum transit duration in phase to consider. maxtransitduration : float The maximum transit duration to consider. ingressdurationfraction : float The fraction of the transit duration to use to generate an initial value of the transit ingress duration for the BLS model refit. This will be fit by this function. verbose : bool If True, will indicate progress and any problems encountered. Returns ------- dict A dict of the following form is returned:: {'period': the refit best period, 'epoch': the refit epoch (i.e. mid-transit time), 'snr':the SNR of the transit, 'transitdepth':the depth of the transit, 'transitduration':the duration of the transit, 'nphasebins':the input value of nphasebins, 'transingressbin':the phase bin containing transit ingress, 'transegressbin':the phase bin containing transit egress, 'blsmodel':the full BLS model used along with its parameters, 'subtractedmags':BLS model - phased light curve, 'phasedmags':the phase light curve, 'phases': the phase values} ''' # get rid of nans first and sigclip stimes, smags, serrs = sigclip_magseries(times, mags, errs, magsarefluxes=magsarefluxes,
python
{ "resource": "" }
q258869
massradius
validation
def massradius(age, planetdist, coremass, mass='massjupiter', radius='radiusjupiter'): '''This function gets the Fortney mass-radius relation for planets. Parameters ---------- age : float This should be one of: 0.3, 1.0, 4.5 [in Gyr]. planetdist : float This should be one of: 0.02, 0.045, 0.1, 1.0, 9.5 [in AU] coremass : int This should be one of: 0, 10, 25, 50, 100 [in Mearth] mass : {'massjupiter','massearth'} Sets the mass units. radius : str Sets the radius units. Only 'radiusjupiter' is used for now. Returns ------- dict A dict of the following form is returned:: {'mass': an array containing the masses to plot), 'radius': an array containing the radii to plot} These can be passed to a plotting routine to make mass-radius plot for the specified age, planet-star distance, and core-mass. ''' MR = {0.3:MASSESRADII_0_3GYR, 1.0:MASSESRADII_1_0GYR, 4.5:MASSESRADII_4_5GYR} if age not in MR:
python
{ "resource": "" }
q258870
_reform_templatelc_for_tfa
validation
def _reform_templatelc_for_tfa(task): ''' This is a parallel worker that reforms light curves for TFA. task[0] = lcfile task[1] = lcformat task[2] = lcformatdir task[3] = timecol task[4] = magcol task[5] = errcol task[6] = timebase task[7] = interpolate_type task[8] = sigclip ''' try: (lcfile, lcformat, lcformatdir, tcol, mcol, ecol, timebase, interpolate_type, sigclip) = task try: formatinfo = get_lcformat(lcformat, use_lcformat_dir=lcformatdir) if formatinfo: (dfileglob, readerfunc, dtimecols, dmagcols, derrcols, magsarefluxes, normfunc) = formatinfo else: LOGERROR("can't figure out the light curve format") return None except Exception as e: LOGEXCEPTION("can't figure out the light curve format") return None # get the LC into a dict lcdict = readerfunc(lcfile) # this should handle lists/tuples being returned by readerfunc # we assume that the first element is the actual lcdict # FIXME: figure out how to not need this assumption if ( (isinstance(lcdict, (list, tuple))) and (isinstance(lcdict[0], dict)) ): lcdict = lcdict[0] outdict = {} # dereference the columns and get them from the lcdict if '.' in tcol: tcolget = tcol.split('.') else: tcolget = [tcol] times = _dict_get(lcdict, tcolget) if '.' in mcol: mcolget = mcol.split('.') else: mcolget = [mcol] mags = _dict_get(lcdict, mcolget) if '.' in ecol: ecolget = ecol.split('.') else: ecolget = [ecol] errs = _dict_get(lcdict, ecolget) # normalize here if not using special normalization if normfunc is None: ntimes, nmags = normalize_magseries( times, mags, magsarefluxes=magsarefluxes )
python
{ "resource": "" }
q258871
parallel_tfa_lclist
validation
def parallel_tfa_lclist(lclist, templateinfo, timecols=None, magcols=None, errcols=None, lcformat='hat-sql', lcformatdir=None, interp='nearest', sigclip=5.0, mintemplatedist_arcmin=10.0, nworkers=NCPUS, maxworkertasks=1000): '''This applies TFA in parallel to all LCs in the given list of file names. Parameters ---------- lclist : str This is a list of light curve files to apply TFA correction to. templateinfo : dict or str This is either the dict produced by `tfa_templates_lclist` or the pickle produced by the same function. timecols : list of str or None The timecol keys to use from the lcdict in applying TFA corrections. magcols : list of str or None The magcol keys to use from the lcdict in applying TFA corrections. errcols : list of str or None The errcol keys to use from the lcdict in applying TFA corrections. lcformat : str This is the `formatkey` associated with your light curve format, which you previously passed in to the `lcproc.register_lcformat` function. This will be used to look up how to find and read the light curves specified in `basedir` or `use_list_of_filenames`. lcformatdir : str or None If this is provided, gives the path to a directory when you've stored your lcformat description JSONs, other than the usual directories lcproc knows to search for them in. Use this along with `lcformat` to specify an LC format JSON file that's not currently registered with lcproc. interp : str This is passed to scipy.interpolate.interp1d as the kind of interpolation to use when reforming the light curves to the timebase of the TFA templates. sigclip : float or sequence of two floats or None This is the sigma clip to apply to the light curves before running TFA on it. mintemplatedist_arcmin : float This sets the minimum distance required from the target object for objects in the TFA template ensemble. Objects closer than this distance will be removed from the ensemble. nworkers : int The number of parallel workers to launch maxworkertasks : int The maximum number of tasks per worker allowed before it's replaced by a fresh one. Returns ------- dict Contains the input file names and output TFA light curve filenames per
python
{ "resource": "" }
q258872
parallel_tfa_lcdir
validation
def parallel_tfa_lcdir(lcdir, templateinfo, lcfileglob=None, timecols=None, magcols=None, errcols=None, lcformat='hat-sql', lcformatdir=None, interp='nearest', sigclip=5.0, mintemplatedist_arcmin=10.0, nworkers=NCPUS, maxworkertasks=1000): '''This applies TFA in parallel to all LCs in a directory. Parameters ---------- lcdir : str This is the directory containing the light curve files to process.. templateinfo : dict or str This is either the dict produced by `tfa_templates_lclist` or the pickle produced by the same function. lcfileglob : str or None The UNIX file glob to use when searching for light curve files in `lcdir`. If None, the default file glob associated with registered LC format provided is used. timecols : list of str or None The timecol keys to use from the lcdict in applying TFA corrections. magcols : list of str or None The magcol keys to use from the lcdict in applying TFA corrections. errcols : list of str or None The errcol keys to use from the lcdict in applying TFA corrections. lcformat : str This is the `formatkey` associated with your light curve format, which you previously passed in to the `lcproc.register_lcformat` function. This will be used to look up how to find and read the light curves specified in `basedir` or `use_list_of_filenames`. lcformatdir : str or None If this is provided, gives the path to a directory when you've stored your lcformat description JSONs, other than the usual directories lcproc knows to search for them in. Use this along with `lcformat` to specify an LC format JSON file that's not currently registered with lcproc. interp : str This is passed to scipy.interpolate.interp1d as the kind of interpolation to use when reforming the light curves to the timebase of the TFA templates. sigclip : float or sequence of two floats or None This is the sigma clip to apply to the light curves before running TFA on it. mintemplatedist_arcmin : float This sets the minimum distance required from the target object for objects in the TFA template ensemble. Objects closer than this distance will be removed from the ensemble. nworkers : int The number of parallel workers to launch maxworkertasks : int The
python
{ "resource": "" }
q258873
_read_pklc
validation
def _read_pklc(lcfile): ''' This just reads a light curve pickle file. Parameters ---------- lcfile : str The file name of the pickle to open. Returns ------- dict This returns an lcdict. ''' if lcfile.endswith('.gz'): try: with gzip.open(lcfile,'rb') as infd: lcdict = pickle.load(infd) except UnicodeDecodeError: with gzip.open(lcfile,'rb') as infd: lcdict = pickle.load(infd, encoding='latin1') else:
python
{ "resource": "" }
q258874
_check_extmodule
validation
def _check_extmodule(module, formatkey): '''This imports the module specified. Used to dynamically import Python modules that are needed to support LC formats not natively supported by astrobase. Parameters ---------- module : str This is either: - a Python module import path, e.g. 'astrobase.lcproc.catalogs' or - a path to a Python file, e.g. '/astrobase/hatsurveys/hatlc.py' that contains the Python module that contains functions used to open (and optionally normalize) a custom LC format that's not natively supported by astrobase. formatkey : str A str used as the unique ID of this LC format for all lcproc functions and can be used to look it up later and import the correct functions needed to support it for lcproc operations. For example, we use 'kep-fits' as a the specifier for Kepler FITS light curves, which can be read by the `astrobase.astrokep.read_kepler_fitslc` function as specified by the `<astrobase install path>/data/lcformats/kep-fits.json` LC format specification JSON. Returns ------- Python module This returns a Python module if it's able to successfully import it. ''' try:
python
{ "resource": "" }
q258875
register_lcformat
validation
def register_lcformat(formatkey, fileglob, timecols, magcols, errcols, readerfunc_module, readerfunc, readerfunc_kwargs=None, normfunc_module=None, normfunc=None, normfunc_kwargs=None, magsarefluxes=False, overwrite_existing=False, lcformat_dir='~/.astrobase/lcformat-jsons'): '''This adds a new LC format to the astrobase LC format registry. Allows handling of custom format light curves for astrobase lcproc drivers. Once the format is successfully registered, light curves should work transparently with all of the functions in this module, by simply calling them with the `formatkey` in the `lcformat` keyword argument. LC format specifications are generated as JSON files. astrobase comes with several of these in `<astrobase install path>/data/lcformats`. LC formats you add by using this function will have their specifiers written to the `~/.astrobase/lcformat-jsons` directory in your home directory. Parameters ---------- formatkey : str A str used as the unique ID of this LC format for all lcproc functions and can be used to look it up later and import the correct functions needed to support it for lcproc operations. For example, we use 'kep-fits' as a the specifier for Kepler FITS light curves, which can be read by the `astrobase.astrokep.read_kepler_fitslc` function as specified by the `<astrobase install path>/data/lcformats/kep-fits.json` LC format specification JSON produced by `register_lcformat`. fileglob : str The default UNIX fileglob to use to search for light curve files in this LC format. This is a string like '*-whatever-???-*.*??-.lc'. timecols,magcols,errcols : list of str These are all lists of strings indicating which keys in the lcdict produced by your `lcreader_func` that will be extracted and used by lcproc functions for processing. The lists must all have the same dimensions, e.g. if timecols = ['timecol1','timecol2'], then magcols must be something like ['magcol1','magcol2'] and errcols must be something like ['errcol1', 'errcol2']. This allows you to process multiple apertures or multiple types of measurements in one go. Each element in these lists can be a simple key, e.g. 'time' (which would correspond to lcdict['time']), or a composite key, e.g. 'aperture1.times.rjd' (which would correspond to lcdict['aperture1']['times']['rjd']). See the examples in the lcformat specification JSON files in `<astrobase install path>/data/lcformats`. readerfunc_module : str This is either: - a Python module import path, e.g. 'astrobase.lcproc.catalogs' or - a path to a Python file, e.g. '/astrobase/hatsurveys/hatlc.py' that contains the Python module that contains functions used to open (and optionally normalize) a custom LC format that's not natively supported by astrobase. readerfunc : str This is the function name in `readerfunc_module` to use to read light curves in the custom format. This MUST always return a dictionary (the 'lcdict') with the following signature (the keys listed below are required, but others are allowed):: {'objectid': this object's identifier as a string, 'objectinfo':{'ra': this object's right ascension in decimal deg, 'decl': this object's declination in decimal deg, 'ndet': the number of observations in this LC, 'objectid': the object ID again for legacy reasons}, ...other time columns, mag columns go in as their own keys} normfunc_kwargs : dict or None This is a dictionary containing any kwargs to pass through to the light curve norm function. normfunc_module : str or None This is either: - a Python module import path, e.g. 'astrobase.lcproc.catalogs' or - a path to a Python file, e.g. '/astrobase/hatsurveys/hatlc.py' - None, in which case we'll use default normalization that contains the Python module that contains functions used to normalize a custom LC format that's not natively supported by astrobase. normfunc : str or None This is the function name in `normfunc_module` to use to normalize light curves in the custom format. If None, the default normalization method used by lcproc is to find gaps in the time-series, normalize measurements grouped by these gaps to zero, then normalize the entire magnitude time series to global time series median using the `astrobase.lcmath.normalize_magseries` function. If this is provided, the normalization function should take and return an lcdict of the same form as that produced by `readerfunc` above. For an example of a specific normalization function, see `normalize_lcdict_by_inst` in the `astrobase.hatsurveys.hatlc` module. normfunc_kwargs : dict or None This is a dictionary containing any kwargs to pass through to the light curve normalization function. magsarefluxes : bool If this is True, then all lcproc functions will treat the measurement columns in the lcdict produced by your `readerfunc` as flux instead of mags, so things like default normalization and sigma-clipping will be done correctly. If this is False, magnitudes will be treated as magnitudes. overwrite_existing : bool If this is True, this function will overwrite any existing LC format specification JSON with the same name as that provided in the
python
{ "resource": "" }
q258876
ec2_ssh
validation
def ec2_ssh(ip_address, keypem_file, username='ec2-user', raiseonfail=False): """This opens an SSH connection to the EC2 instance at `ip_address`. Parameters ---------- ip_address : str IP address of the AWS EC2 instance to connect to. keypem_file : str The path to the keypair PEM file generated by AWS to allow SSH connections. username : str The username to use to login to the EC2 instance. raiseonfail : bool If True, will re-raise whatever Exception caused the operation to fail and break out immediately. Returns ------- paramiko.SSHClient This has all the usual `paramiko` functionality: - Use `SSHClient.exec_command(command, environment=None)` to exec a shell command. - Use `SSHClient.open_sftp()` to get a `SFTPClient` for the server. Then
python
{ "resource": "" }
q258877
s3_get_file
validation
def s3_get_file(bucket, filename, local_file, altexts=None, client=None, raiseonfail=False): """This gets a file from an S3 bucket. Parameters ---------- bucket : str The AWS S3 bucket name. filename : str The full filename of the file to get from the bucket local_file : str Path to where the downloaded file will be stored. altexts : None or list of str If not None, this is a list of alternate extensions to try for the file other than the one provided in `filename`. For example, to get anything that's an .sqlite where .sqlite.gz is expected, use altexts=[''] to strip the .gz. client : boto3.Client or None If None, this function will instantiate a new `boto3.Client` object to use in its operations. Alternatively, pass in an existing `boto3.Client` instance to re-use it here. raiseonfail : bool If True, will re-raise whatever Exception caused the operation to fail and break out immediately. Returns ------- str Path to the downloaded filename or None if the download was unsuccessful. """ if not client: client = boto3.client('s3') try: client.download_file(bucket, filename, local_file)
python
{ "resource": "" }
q258878
s3_put_file
validation
def s3_put_file(local_file, bucket, client=None, raiseonfail=False): """This uploads a file to S3. Parameters ---------- local_file : str Path to the file to upload to S3. bucket : str The AWS S3 bucket to upload the file to. client : boto3.Client or None If None, this function will instantiate a new `boto3.Client` object to use in its operations. Alternatively, pass in an existing `boto3.Client` instance to re-use it here. raiseonfail : bool If True, will re-raise whatever Exception caused the operation to fail and break out immediately. Returns ------- str or None If the file upload is successful, returns the s3:// URL of the uploaded
python
{ "resource": "" }
q258879
s3_delete_file
validation
def s3_delete_file(bucket, filename, client=None, raiseonfail=False): """This deletes a file from S3. Parameters ---------- bucket : str The AWS S3 bucket to delete the file from. filename : str The full file name of the file to delete, including any prefixes. client : boto3.Client or None If None, this function will instantiate a new `boto3.Client` object to use in its operations. Alternatively, pass in an existing `boto3.Client` instance to re-use it here. raiseonfail : bool If True, will re-raise whatever Exception caused the operation to fail
python
{ "resource": "" }
q258880
sqs_create_queue
validation
def sqs_create_queue(queue_name, options=None, client=None): """ This creates an SQS queue. Parameters ---------- queue_name : str The name of the queue to create. options : dict or None A dict of options indicate extra attributes the queue should have. See the SQS docs for details. If None, no custom attributes will be attached to the queue. client : boto3.Client or None If None, this function will instantiate a new `boto3.Client` object to use in its operations. Alternatively, pass in an existing `boto3.Client` instance to re-use it here. Returns ------- dict This returns a dict of the form:: {'url': SQS URL of the queue, 'name': name of the queue} """ if not client: client = boto3.client('sqs') try: if isinstance(options, dict): resp = client.create_queue(QueueName=queue_name, Attributes=options) else:
python
{ "resource": "" }
q258881
sqs_delete_queue
validation
def sqs_delete_queue(queue_url, client=None): """This deletes an SQS queue given its URL Parameters ---------- queue_url : str The SQS URL of the queue to delete. client : boto3.Client or None If None, this function will instantiate a new `boto3.Client` object to use in its operations. Alternatively, pass in an existing `boto3.Client` instance to re-use it here. Returns ------- bool True if the queue was deleted successfully. False otherwise. """ if not client:
python
{ "resource": "" }
q258882
sqs_put_item
validation
def sqs_put_item(queue_url, item, delay_seconds=0, client=None, raiseonfail=False): """This pushes a dict serialized to JSON to the specified SQS queue. Parameters ---------- queue_url : str The SQS URL of the queue to push the object to. item : dict The dict passed in here will be serialized to JSON. delay_seconds : int The amount of time in seconds the pushed item will be held before going 'live' and being visible to all queue consumers. client : boto3.Client or None If None, this function will instantiate a new `boto3.Client` object to use in its operations. Alternatively, pass in an existing `boto3.Client` instance to re-use it here. raiseonfail : bool If True, will re-raise whatever Exception caused the operation to fail and break out immediately. Returns ------- boto3.Response or None If the item was successfully put on the queue, will return the response from the service. If it wasn't, will return None. """ if not client:
python
{ "resource": "" }
q258883
sqs_get_item
validation
def sqs_get_item(queue_url, max_items=1, wait_time_seconds=5, client=None, raiseonfail=False): """This gets a single item from the SQS queue. The `queue_url` is composed of some internal SQS junk plus a `queue_name`. For our purposes (`lcproc_aws.py`), the queue name will be something like:: lcproc_queue_<action> where action is one of:: runcp runpf The item is always a JSON object:: {'target': S3 bucket address of the file to process, 'action': the action to perform on the file ('runpf', 'runcp', etc.) 'args': the action's args as a tuple (not including filename, which is generated randomly as a temporary local file), 'kwargs': the action's kwargs as a dict, 'outbucket: S3 bucket to write the result to, 'outqueue': SQS queue to write the processed item's info to (optional)} The action MUST match the <action> in the queue name for this item to be processed. Parameters ---------- queue_url : str The SQS URL of the queue to get messages from. max_items : int The number of items to pull from the queue in this request. wait_time_seconds : int This specifies how long the function should block until a message is received on the queue. If the timeout expires, an empty list will be returned. If the timeout doesn't expire, the function will return a list of items received (up to `max_items`). client : boto3.Client or None If None, this function will instantiate a new `boto3.Client` object to use in its operations. Alternatively, pass in an existing `boto3.Client` instance to re-use it here. raiseonfail : bool If True, will re-raise whatever Exception caused the operation to fail and break out immediately. Returns ------- list of dicts or None For each item pulled from the queue in this request (up to `max_items`), a dict will be deserialized from the retrieved JSON, containing the message items and various metadata. The most important item of the metadata is the `receipt_handle`, which can be used to acknowledge receipt of all items in this request (see `sqs_delete_item` below). If the queue pull fails outright, returns None. If no messages are available for this queue pull, returns an empty list. """ if not client: client =
python
{ "resource": "" }
q258884
sqs_delete_item
validation
def sqs_delete_item(queue_url, receipt_handle, client=None, raiseonfail=False): """This deletes a message from the queue, effectively acknowledging its receipt. Call this only when all messages retrieved from the queue have been processed, since this will prevent redelivery of these messages to other queue workers pulling fromn the same queue channel. Parameters ---------- queue_url : str The SQS URL of the queue where we got the messages from. This should be the same queue used to retrieve the messages in `sqs_get_item`. receipt_handle : str The receipt handle of the queue message that we're responding to, and will acknowledge receipt of. This will be present in each message retrieved using `sqs_get_item`. client : boto3.Client or None If None, this function will instantiate a new `boto3.Client` object to
python
{ "resource": "" }
q258885
delete_ec2_nodes
validation
def delete_ec2_nodes( instance_id_list, client=None ): """This deletes EC2 nodes and terminates the instances. Parameters ---------- instance_id_list : list of str A list of EC2 instance IDs to terminate. client : boto3.Client or None If None, this function will instantiate a new `boto3.Client` object to use in its operations. Alternatively, pass in
python
{ "resource": "" }
q258886
delete_spot_fleet_cluster
validation
def delete_spot_fleet_cluster( spot_fleet_reqid, client=None, ): """ This deletes a spot-fleet cluster. Parameters ---------- spot_fleet_reqid : str The fleet request ID returned by `make_spot_fleet_cluster`. client : boto3.Client or None If None, this function will instantiate a new `boto3.Client` object to use in its operations. Alternatively, pass in an existing `boto3.Client`
python
{ "resource": "" }
q258887
gcs_put_file
validation
def gcs_put_file(local_file, bucketname, service_account_json=None, client=None, raiseonfail=False): """This puts a single file into a Google Cloud Storage bucket. Parameters ---------- local_file : str Path to the file to upload to GCS. bucket : str The GCS bucket to upload the file to. service_account_json : str Path to a downloaded GCS credentials JSON file. client : google.cloud.storage.Client instance The instance of the Client to use to perform the download operation. If this is None, a new Client will be used. If this is None and `service_account_json` points to a downloaded JSON file with GCS credentials, a new Client with the provided credentials will be used. If this is not None, the existing Client instance will be used. raiseonfail : bool If True, will re-raise whatever Exception caused the operation to fail and break out immediately. Returns ------- str or None If the file upload is successful, returns the gs:// URL of the uploaded file. If it failed, will return None. """ if not client: if (service_account_json
python
{ "resource": "" }
q258888
read_fakelc
validation
def read_fakelc(fakelcfile): ''' This just reads a pickled fake LC. Parameters ---------- fakelcfile : str The fake LC file to read. Returns ------- dict This returns an lcdict. ''' try: with open(fakelcfile,'rb') as infd:
python
{ "resource": "" }
q258889
get_varfeatures
validation
def get_varfeatures(simbasedir, mindet=1000, nworkers=None): '''This runs `lcproc.lcvfeatures.parallel_varfeatures` on fake LCs in `simbasedir`. Parameters ---------- simbasedir : str The directory containing the fake LCs to process. mindet : int The minimum number of detections needed to accept an LC and process it. nworkers : int or None The number of parallel workers to use when extracting variability features from the input light curves. Returns ------- str The path to the `varfeatures` pickle created after running the `lcproc.lcvfeatures.parallel_varfeatures` function. ''' # get the info from the simbasedir with open(os.path.join(simbasedir, 'fakelcs-info.pkl'),'rb') as infd: siminfo = pickle.load(infd) lcfpaths = siminfo['lcfpath'] varfeaturedir = os.path.join(simbasedir,'varfeatures') # get the column defs for the fakelcs timecols = siminfo['timecols'] magcols = siminfo['magcols'] errcols = siminfo['errcols'] # get the column defs for the fakelcs timecols = siminfo['timecols'] magcols = siminfo['magcols'] errcols = siminfo['errcols'] # register the fakelc pklc as a custom lcproc format # now we should be able to use all lcproc functions correctly fakelc_formatkey = 'fake-%s' % siminfo['lcformat'] lcproc.register_lcformat( fakelc_formatkey, '*-fakelc.pkl',
python
{ "resource": "" }
q258890
precision
validation
def precision(ntp, nfp): ''' This calculates precision. https://en.wikipedia.org/wiki/Precision_and_recall Parameters ---------- ntp : int The number of true positives. nfp : int The number of false positives. Returns -------
python
{ "resource": "" }
q258891
recall
validation
def recall(ntp, nfn): ''' This calculates recall. https://en.wikipedia.org/wiki/Precision_and_recall Parameters ---------- ntp : int The number of true positives. nfn : int The number of false negatives. Returns -------
python
{ "resource": "" }
q258892
matthews_correl_coeff
validation
def matthews_correl_coeff(ntp, ntn, nfp, nfn): ''' This calculates the Matthews correlation coefficent. https://en.wikipedia.org/wiki/Matthews_correlation_coefficient Parameters ---------- ntp : int The number of true positives. ntn : int The number of true negatives nfp : int The number of false positives. nfn : int The number of false negatives. Returns ------- float
python
{ "resource": "" }
q258893
magbin_varind_gridsearch_worker
validation
def magbin_varind_gridsearch_worker(task): ''' This is a parallel grid search worker for the function below. ''' simbasedir, gridpoint, magbinmedian = task try: res = get_recovered_variables_for_magbin(simbasedir, magbinmedian, stetson_stdev_min=gridpoint[0], inveta_stdev_min=gridpoint[1],
python
{ "resource": "" }
q258894
variable_index_gridsearch_magbin
validation
def variable_index_gridsearch_magbin(simbasedir, stetson_stdev_range=(1.0,20.0), inveta_stdev_range=(1.0,20.0), iqr_stdev_range=(1.0,20.0), ngridpoints=32, ngridworkers=None): '''This runs a variable index grid search per magbin. For each magbin, this does a grid search using the stetson and inveta ranges provided and tries to optimize the Matthews Correlation Coefficient (best value is +1.0), indicating the best possible separation of variables vs. nonvariables. The thresholds on these two variable indexes that produce the largest coeff for the collection of fake LCs will probably be the ones that work best for actual variable classification on the real LCs. https://en.wikipedia.org/wiki/Matthews_correlation_coefficient For each grid-point, calculates the true positives, false positives, true negatives, false negatives. Then gets the precision and recall, confusion matrix, and the ROC curve for variable vs. nonvariable. Once we've identified the best thresholds to use, we can then calculate variable object numbers: - as a function of magnitude - as a function of period - as a function of number of detections - as a function of amplitude of variability Writes everything back to `simbasedir/fakevar-recovery.pkl`. Use the plotting function below to make plots for the results. Parameters ---------- simbasedir : str The directory where the fake LCs are located. stetson_stdev_range : sequence of 2 floats The min and max values of the Stetson J variability index to generate a grid over these to test for the values of this index that produce the 'best' recovery rate for the injected variable stars. inveta_stdev_range : sequence of 2 floats The min and max values of the 1/eta variability index to generate a grid over these to test for the values of this index that produce the 'best' recovery rate for the injected variable stars. iqr_stdev_range : sequence of 2 floats The min and max values of the IQR variability index to generate a grid over these to test for the values of this index that produce the 'best' recovery rate for the injected variable stars. ngridpoints : int The number of grid points for each variability index grid. Remember that this function will be searching in 3D and will require lots of time to run if ngridpoints is too large. For the default number of grid points and 25000 simulated light curves, this takes about 3 days to run on a 40 (effective) core machine with 2 x Xeon E5-2650v3 CPUs. ngridworkers : int or None The number of parallel grid search workers that will be launched. Returns ------- dict The returned dict contains a list of recovery stats for each magbin and each grid point in the variability index grids that were used. This dict can be passed to the plotting function below to plot the results. ''' # make the output directory where all the pkls from the variability # threshold runs will go outdir = os.path.join(simbasedir,'recvar-threshold-pkls')
python
{ "resource": "" }
q258895
run_periodfinding
validation
def run_periodfinding(simbasedir, pfmethods=('gls','pdm','bls'), pfkwargs=({},{},{'startp':1.0,'maxtransitduration':0.3}), getblssnr=False, sigclip=5.0, nperiodworkers=10, ncontrolworkers=4, liststartindex=None, listmaxobjects=None): '''This runs periodfinding using several period-finders on a collection of fake LCs. As a rough benchmark, 25000 fake LCs with 10000--50000 points per LC take about 26 days in total to run on an invocation of this function using GLS+PDM+BLS and 10 periodworkers and 4 controlworkers (so all 40 'cores') on a 2 x Xeon E5-2660v3 machine. Parameters ---------- pfmethods : sequence of str This is used to specify which periodfinders to run. These must be in the `lcproc.periodsearch.PFMETHODS` dict. pfkwargs : sequence of dict This is used to provide optional kwargs to the period-finders. getblssnr : bool If this is True, will run BLS SNR calculations for each object and magcol. This takes a while to run, so it's disabled (False) by default. sigclip : float or int or sequence of two floats/ints or None If a single float or int, a symmetric sigma-clip will be performed using the number provided as the sigma-multiplier to cut out from the input time-series. If a list of two ints/floats is provided, the function will perform an 'asymmetric' sigma-clip. The first element in this list is the sigma value to use for fainter flux/mag values; the second element in this list is the sigma value to use for brighter flux/mag values. For example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma dimmings and greater than 3-sigma brightenings. Here the meaning of "dimming" and "brightening" is set by *physics* (not the magnitude system), which is why the `magsarefluxes` kwarg must be correctly set. If `sigclip` is None, no sigma-clipping will be performed, and the time-series (with non-finite elems removed) will be passed through to the output. nperiodworkers : int This is the number of parallel period-finding worker processes to use. ncontrolworkers : int This is the number of parallel period-finding control workers to use. Each control worker will launch `nperiodworkers` worker processes. liststartindex : int The starting index of processing. This refers to the filename list generated by running `glob.glob` on the fake LCs in `simbasedir`. maxobjects : int The maximum number of objects to process in this run. Use this with `liststartindex` to effectively distribute working on a large list of input light curves over several sessions or machines. Returns ------- str
python
{ "resource": "" }
q258896
periodrec_worker
validation
def periodrec_worker(task): '''This is a parallel worker for running period-recovery. Parameters ---------- task : tuple This is used to pass args to the `periodicvar_recovery` function:: task[0] = period-finding result pickle to work on task[1] = simbasedir task[2] = period_tolerance Returns ------- dict This is the dict produced by the `periodicvar_recovery` function for the input period-finding result pickle. ''' pfpkl, simbasedir, period_tolerance = task try:
python
{ "resource": "" }
q258897
parallel_periodicvar_recovery
validation
def parallel_periodicvar_recovery(simbasedir, period_tolerance=1.0e-3, liststartind=None, listmaxobjects=None, nworkers=None): '''This is a parallel driver for `periodicvar_recovery`. Parameters ---------- simbasedir : str The base directory where all of the fake LCs and period-finding results are. period_tolerance : float The maximum difference that this function will consider between an actual period (or its aliases) and a recovered period to consider it as as a 'recovered' period. liststartindex : int The starting index of processing. This refers to the filename list generated by running `glob.glob` on the period-finding result pickles in `simbasedir/periodfinding`. listmaxobjects : int The maximum number of objects to process in this run. Use this with `liststartindex` to effectively distribute working on a large list of input period-finding result pickles over several sessions or machines. nperiodworkers : int This is the number of parallel period-finding worker processes to use. Returns ------- str Returns the filename of the pickle produced containing all of the period recovery results. ''' # figure out the periodfinding pickles directory pfpkldir = os.path.join(simbasedir,'periodfinding') if not os.path.exists(pfpkldir): LOGERROR('no "periodfinding" subdirectory in %s, can\'t continue' % simbasedir) return None # find all the periodfinding pickles pfpkl_list = glob.glob(os.path.join(pfpkldir,'*periodfinding*pkl*')) if len(pfpkl_list) > 0: if liststartind: pfpkl_list = pfpkl_list[liststartind:] if listmaxobjects: pfpkl_list = pfpkl_list[:listmaxobjects] tasks = [(x, simbasedir, period_tolerance) for x in pfpkl_list] pool = mp.Pool(nworkers) results = pool.map(periodrec_worker, tasks) pool.close() pool.join() resdict = {x['objectid']:x for x in results if x is not None} actual_periodicvars = np.array( [x['objectid'] for x in results if (x is not None and x['actual_vartype'] in PERIODIC_VARTYPES)], dtype=np.unicode_ ) recovered_periodicvars = np.array( [x['objectid']
python
{ "resource": "" }
q258898
tic_conesearch
validation
def tic_conesearch( ra, decl, radius_arcmin=5.0, apiversion='v0', forcefetch=False, cachedir='~/.astrobase/mast-cache', verbose=True, timeout=10.0, refresh=5.0, maxtimeout=90.0, maxtries=3, jitter=5.0, raiseonfail=False ): '''This runs a TESS Input Catalog cone search on MAST. If you use this, please cite the TIC paper (Stassun et al 2018; http://adsabs.harvard.edu/abs/2018AJ....156..102S). Also see the "living" TESS input catalog docs: https://docs.google.com/document/d/1zdiKMs4Ld4cXZ2DW4lMX-fuxAF6hPHTjqjIwGqnfjqI Also see: https://mast.stsci.edu/api/v0/_t_i_cfields.html for the fields returned by the service and present in the result JSON file. Parameters ---------- ra,decl : float The center coordinates of the cone-search in decimal degrees. radius_arcmin : float The cone-search radius in arcminutes. apiversion : str The API version of the MAST service to use. This sets the URL that this function will call, using `apiversion` as key into the `MAST_URLS` dict above. forcefetch : bool If this is True, the query will be retried even if cached results for it exist. cachedir : str This points to the directory where results will be downloaded. verbose : bool If True, will indicate progress and warn of any issues. timeout : float This sets the amount of time in seconds to wait for the service to respond to our initial request. refresh : float This sets the amount of time in seconds to wait before checking if the result file is available. If the results file isn't available after `refresh` seconds have elapsed, the function will wait for `refresh` seconds continuously, until `maxtimeout` is reached or the results file becomes available. maxtimeout : float The maximum amount of time in seconds to wait for a result to become available after submitting our query request. maxtries : int The maximum number of tries (across all mirrors tried) to make to either submit the request or download the results, before giving up. jitter : float This is used to control the scale of the random wait in seconds before starting the query. Useful in parallelized
python
{ "resource": "" }
q258899
tic_xmatch
validation
def tic_xmatch( ra, decl, radius_arcsec=5.0, apiversion='v0', forcefetch=False, cachedir='~/.astrobase/mast-cache', verbose=True, timeout=90.0, refresh=5.0, maxtimeout=180.0, maxtries=3, jitter=5.0, raiseonfail=False ): '''This does a cross-match with TIC. Parameters ---------- ra,decl : np.arrays or lists of floats The coordinates that will be cross-matched against the TIC. radius_arcsec : float The cross-match radius in arcseconds. apiversion : str The API version of the MAST service to use. This sets the URL that this function will call, using `apiversion` as key into the `MAST_URLS` dict above. forcefetch : bool If this is True, the query will be retried even if cached results for it exist. cachedir : str This points to the directory where results will be downloaded. verbose : bool If True, will indicate progress and warn of any issues. timeout : float This sets the amount of time in seconds to wait for the service to respond to our initial request. refresh : float This sets the amount of time in seconds to wait before checking if the result file is available. If the results file isn't available after `refresh` seconds
python
{ "resource": "" }