_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q258700 | _parse_csv_header | validation | def _parse_csv_header(header):
'''
This parses the CSV header from the CSV HAT sqlitecurve.
Returns a dict that can be used to update an existing lcdict with the
relevant metadata info needed to form a full LC.
'''
# first, break into lines
headerlines = header.split('\n')
headerlines = [x.lstrip('# ') for x in headerlines]
# next, find the indices of the metadata sections
objectstart = headerlines.index('OBJECT')
metadatastart = headerlines.index('METADATA')
camfilterstart = headerlines.index('CAMFILTERS')
photaperturestart = headerlines.index('PHOTAPERTURES')
columnstart = headerlines.index('COLUMNS')
lcstart = headerlines.index('LIGHTCURVE')
# get the lines for the header sections
objectinfo = headerlines[objectstart+1:metadatastart-1]
metadatainfo = headerlines[metadatastart+1:camfilterstart-1]
camfilterinfo = headerlines[camfilterstart+1:photaperturestart-1]
photapertureinfo = headerlines[photaperturestart+1:columnstart-1]
columninfo = headerlines[columnstart+1:lcstart-1]
# parse the header sections and insert the appropriate key-val pairs into
# the lcdict
metadict = {'objectinfo':{}}
# first, the objectinfo section
objectinfo = [x.split(';') for x in objectinfo]
for elem in objectinfo:
for kvelem in elem:
key, val = kvelem.split(' = ',1)
metadict['objectinfo'][key.strip()] = (
_smartcast(val, METAKEYS[key.strip()])
)
# the objectid belongs at the top level
metadict['objectid'] = metadict['objectinfo']['objectid'][:]
del metadict['objectinfo']['objectid']
# get the lightcurve metadata
metadatainfo = [x.split(';') for x in metadatainfo]
for elem in metadatainfo:
for kvelem in elem:
try:
key, val = kvelem.split(' = ',1)
# get the lcbestaperture into a dict again
if key.strip() == 'lcbestaperture':
val = json.loads(val)
# get the lcversion and datarelease as integers
if key.strip() in ('datarelease', 'lcversion'):
val = int(val)
# get the lastupdated as a float
if key.strip() == 'lastupdated':
val = float(val)
# put the key-val into the dict
metadict[key.strip()] = val
except Exception as e:
LOGWARNING('could not understand header element "%s",'
' skipped.' % kvelem)
# get the camera filters
metadict['filters'] = []
for row in camfilterinfo:
filterid, filtername, filterdesc = row.split(' - ')
metadict['filters'].append((int(filterid),
filtername,
filterdesc))
# get the photometric apertures
metadict['lcapertures'] = {}
for row in photapertureinfo:
apnum, appix = row.split(' - ')
appix = float(appix.rstrip(' px'))
metadict['lcapertures'][apnum.strip()] = appix
# get the columns
metadict['columns'] = []
for row in columninfo:
colnum, colname, coldesc = row.split(' - ')
metadict['columns'].append(colname)
return metadict | python | {
"resource": ""
} |
q258701 | _parse_csv_header_lcc_csv_v1 | validation | def _parse_csv_header_lcc_csv_v1(headerlines):
'''
This parses the header of the LCC CSV V1 LC format.
'''
# the first three lines indicate the format name, comment char, separator
commentchar = headerlines[1]
separator = headerlines[2]
headerlines = [x.lstrip('%s ' % commentchar) for x in headerlines[3:]]
# next, find the indices of the various LC sections
metadatastart = headerlines.index('OBJECT METADATA')
columnstart = headerlines.index('COLUMN DEFINITIONS')
lcstart = headerlines.index('LIGHTCURVE')
metadata = ' ' .join(headerlines[metadatastart+1:columnstart-1])
columns = ' ' .join(headerlines[columnstart+1:lcstart-1])
metadata = json.loads(metadata)
columns = json.loads(columns)
return metadata, columns, separator | python | {
"resource": ""
} |
q258702 | describe_lcc_csv | validation | def describe_lcc_csv(lcdict, returndesc=False):
'''
This describes the LCC CSV format light curve file.
Parameters
----------
lcdict : dict
The input lcdict to parse for column and metadata info.
returndesc : bool
If True, returns the description string as an str instead of just
printing it to stdout.
Returns
-------
str or None
If returndesc is True, returns the description lines as a str, otherwise
returns nothing.
'''
metadata_lines = []
coldef_lines = []
if 'lcformat' in lcdict and 'lcc-csv' in lcdict['lcformat'].lower():
metadata = lcdict['metadata']
metakeys = lcdict['objectinfo'].keys()
coldefs = lcdict['coldefs']
for mk in metakeys:
metadata_lines.append(
'%20s | %s' % (
mk,
metadata[mk]['desc']
)
)
for ck in lcdict['columns']:
coldef_lines.append('column %02d | %8s | numpy dtype: %3s | %s'
% (coldefs[ck]['colnum'],
ck,
coldefs[ck]['dtype'],
coldefs[ck]['desc']))
desc = LCC_CSVLC_DESCTEMPLATE.format(
objectid=lcdict['objectid'],
metadata_desc='\n'.join(metadata_lines),
metadata=pformat(lcdict['objectinfo']),
columndefs='\n'.join(coldef_lines)
)
print(desc)
if returndesc:
return desc
else:
LOGERROR("this lcdict is not from an LCC CSV, can't figure it out...")
return None | python | {
"resource": ""
} |
q258703 | read_csvlc | validation | def read_csvlc(lcfile):
'''This reads a HAT data server or LCC-Server produced CSV light curve
into an lcdict.
This will automatically figure out the format of the file
provided. Currently, it can read:
- legacy HAT data server CSV LCs (e.g. from
https://hatsouth.org/planets/lightcurves.html) with an extension of the
form: `.hatlc.csv.gz`.
- all LCC-Server produced LCC-CSV-V1 LCs (e.g. from
https://data.hatsurveys.org) with an extension of the form: `-csvlc.gz`.
Parameters
----------
lcfile : str
The light curve file to read.
Returns
-------
dict
Returns an lcdict that can be read and used by many astrobase processing
functions.
'''
# read in the file and split by lines
if '.gz' in os.path.basename(lcfile):
LOGINFO('reading gzipped HATLC: %s' % lcfile)
infd = gzip.open(lcfile,'rb')
else:
LOGINFO('reading HATLC: %s' % lcfile)
infd = open(lcfile,'rb')
# this transparently reads LCC CSVLCs
lcformat_check = infd.read(12).decode()
if 'LCC-CSVLC' in lcformat_check:
infd.close()
return read_lcc_csvlc(lcfile)
else:
infd.seek(0)
# below is reading the HATLC v2 CSV LCs
lctext = infd.read().decode() # argh Python 3
infd.close()
# figure out the header and get the LC columns
lcstart = lctext.index('# LIGHTCURVE\n')
lcheader = lctext[:lcstart+12]
lccolumns = lctext[lcstart+13:].split('\n')
lccolumns = [x for x in lccolumns if len(x) > 0]
# initialize the lcdict and parse the CSV header
lcdict = _parse_csv_header(lcheader)
# tranpose the LC rows into columns
lccolumns = [x.split(',') for x in lccolumns]
lccolumns = list(zip(*lccolumns)) # argh more Python 3
# write the columns to the dict
for colind, col in enumerate(lcdict['columns']):
if (col.split('_')[0] in LC_MAG_COLUMNS or
col.split('_')[0] in LC_ERR_COLUMNS or
col.split('_')[0] in LC_FLAG_COLUMNS):
lcdict[col] = np.array([_smartcast(x,
COLUMNDEFS[col.split('_')[0]][2])
for x in lccolumns[colind]])
elif col in COLUMNDEFS:
lcdict[col] = np.array([_smartcast(x,COLUMNDEFS[col][2])
for x in lccolumns[colind]])
else:
LOGWARNING('lcdict col %s has no formatter available' % col)
continue
return lcdict | python | {
"resource": ""
} |
q258704 | find_lc_timegroups | validation | def find_lc_timegroups(lctimes, mingap=4.0):
'''This finds the time gaps in the light curve, so we can figure out which
times are for consecutive observations and which represent gaps
between seasons.
Parameters
----------
lctimes : np.array
This is the input array of times, assumed to be in some form of JD.
mingap : float
This defines how much the difference between consecutive measurements is
allowed to be to consider them as parts of different timegroups. By
default it is set to 4.0 days.
Returns
-------
tuple
A tuple of the form below is returned, containing the number of time
groups found and Python slice objects for each group::
(ngroups, [slice(start_ind_1, end_ind_1), ...])
'''
lc_time_diffs = [(lctimes[x] - lctimes[x-1]) for x in range(1,len(lctimes))]
lc_time_diffs = np.array(lc_time_diffs)
group_start_indices = np.where(lc_time_diffs > mingap)[0]
if len(group_start_indices) > 0:
group_indices = []
for i, gindex in enumerate(group_start_indices):
if i == 0:
group_indices.append(slice(0,gindex+1))
else:
group_indices.append(slice(group_start_indices[i-1]+1,gindex+1))
# at the end, add the slice for the last group to the end of the times
# array
group_indices.append(slice(group_start_indices[-1]+1,len(lctimes)))
# if there's no large gap in the LC, then there's only one group to worry
# about
else:
group_indices = [slice(0,len(lctimes))]
return len(group_indices), group_indices | python | {
"resource": ""
} |
q258705 | main | validation | def main():
'''
This is called when we're executed from the commandline.
The current usage from the command-line is described below::
usage: hatlc [-h] [--describe] hatlcfile
read a HAT LC of any format and output to stdout
positional arguments:
hatlcfile path to the light curve you want to read and pipe to stdout
optional arguments:
-h, --help show this help message and exit
--describe don't dump the columns, show only object info and LC metadata
'''
# handle SIGPIPE sent by less, head, et al.
import signal
signal.signal(signal.SIGPIPE, signal.SIG_DFL)
import argparse
aparser = argparse.ArgumentParser(
description='read a HAT LC of any format and output to stdout'
)
aparser.add_argument(
'hatlcfile',
action='store',
type=str,
help=("path to the light curve you want to read and pipe to stdout")
)
aparser.add_argument(
'--describe',
action='store_true',
default=False,
help=("don't dump the columns, show only object info and LC metadata")
)
args = aparser.parse_args()
filetoread = args.hatlcfile
if not os.path.exists(filetoread):
LOGERROR("file provided: %s doesn't seem to exist" % filetoread)
sys.exit(1)
# figure out the type of LC this is
filename = os.path.basename(filetoread)
# switch based on filetype
if filename.endswith('-hatlc.csv.gz') or filename.endswith('-csvlc.gz'):
if args.describe:
describe(read_csvlc(filename))
sys.exit(0)
else:
with gzip.open(filename,'rb') as infd:
for line in infd:
print(line.decode(),end='')
elif filename.endswith('-hatlc.sqlite.gz'):
lcdict, msg = read_and_filter_sqlitecurve(filetoread)
# dump the description
describe(lcdict, offsetwith='#')
# stop here if describe is True
if args.describe:
sys.exit(0)
# otherwise, continue to parse the cols, etc.
# get the aperture names
apertures = sorted(lcdict['lcapertures'].keys())
# update column defs per aperture
for aper in apertures:
COLUMNDEFS.update({'%s_%s' % (x, aper): COLUMNDEFS[x] for x in
LC_MAG_COLUMNS})
COLUMNDEFS.update({'%s_%s' % (x, aper): COLUMNDEFS[x] for x in
LC_ERR_COLUMNS})
COLUMNDEFS.update({'%s_%s' % (x, aper): COLUMNDEFS[x] for x in
LC_FLAG_COLUMNS})
formstr = ','.join([COLUMNDEFS[x][1] for x in lcdict['columns']])
ndet = lcdict['objectinfo']['ndet']
for ind in range(ndet):
line = [lcdict[x][ind] for x in lcdict['columns']]
formline = formstr % tuple(line)
print(formline)
else:
LOGERROR('unrecognized HATLC file: %s' % filetoread)
sys.exit(1) | python | {
"resource": ""
} |
q258706 | mdwarf_subtype_from_sdsscolor | validation | def mdwarf_subtype_from_sdsscolor(ri_color, iz_color):
'''This calculates the M-dwarf subtype given SDSS `r-i` and `i-z` colors.
Parameters
----------
ri_color : float
The SDSS `r-i` color of the object.
iz_color : float
The SDSS `i-z` color of the object.
Returns
-------
(subtype, index1, index2) : tuple
`subtype`: if the star appears to be an M dwarf, will return an int
between 0 and 9 indicating its subtype, e.g. will return 4 for an M4
dwarf. If the object isn't an M dwarf, will return None
`index1`, `index2`: the M-dwarf color locus value and spread of this
object calculated from the `r-i` and `i-z` colors.
'''
# calculate the spectral type index and the spectral type spread of the
# object. sti is calculated by fitting a line to the locus in r-i and i-z
# space for M dwarfs in West+ 2007
if np.isfinite(ri_color) and np.isfinite(iz_color):
obj_sti = 0.875274*ri_color + 0.483628*(iz_color + 0.00438)
obj_sts = -0.483628*ri_color + 0.875274*(iz_color + 0.00438)
else:
obj_sti = np.nan
obj_sts = np.nan
# possible M star if sti is >= 0.666 but <= 3.4559
if (np.isfinite(obj_sti) and np.isfinite(obj_sts) and
(obj_sti > 0.666) and (obj_sti < 3.4559)):
# decide which M subclass object this is
if ((obj_sti > 0.6660) and (obj_sti < 0.8592)):
m_class = 'M0'
if ((obj_sti > 0.8592) and (obj_sti < 1.0822)):
m_class = 'M1'
if ((obj_sti > 1.0822) and (obj_sti < 1.2998)):
m_class = 'M2'
if ((obj_sti > 1.2998) and (obj_sti < 1.6378)):
m_class = 'M3'
if ((obj_sti > 1.6378) and (obj_sti < 2.0363)):
m_class = 'M4'
if ((obj_sti > 2.0363) and (obj_sti < 2.2411)):
m_class = 'M5'
if ((obj_sti > 2.2411) and (obj_sti < 2.4126)):
m_class = 'M6'
if ((obj_sti > 2.4126) and (obj_sti < 2.9213)):
m_class = 'M7'
if ((obj_sti > 2.9213) and (obj_sti < 3.2418)):
m_class = 'M8'
if ((obj_sti > 3.2418) and (obj_sti < 3.4559)):
m_class = 'M9'
else:
m_class = None
return m_class, obj_sti, obj_sts | python | {
"resource": ""
} |
q258707 | parallel_epd_lclist | validation | def parallel_epd_lclist(lclist,
externalparams,
timecols=None,
magcols=None,
errcols=None,
lcformat='hat-sql',
lcformatdir=None,
epdsmooth_sigclip=3.0,
epdsmooth_windowsize=21,
epdsmooth_func=smooth_magseries_savgol,
epdsmooth_extraparams=None,
nworkers=NCPUS,
maxworkertasks=1000):
'''This applies EPD in parallel to all LCs in the input list.
Parameters
----------
lclist : list of str
This is the list of light curve files to run EPD on.
externalparams : dict or None
This is a dict that indicates which keys in the lcdict obtained from the
lcfile correspond to the required external parameters. As with timecol,
magcol, and errcol, these can be simple keys (e.g. 'rjd') or compound
keys ('magaperture1.mags'). The dict should look something like::
{'fsv':'<lcdict key>' array: S values for each observation,
'fdv':'<lcdict key>' array: D values for each observation,
'fkv':'<lcdict key>' array: K values for each observation,
'xcc':'<lcdict key>' array: x coords for each observation,
'ycc':'<lcdict key>' array: y coords for each observation,
'bgv':'<lcdict key>' array: sky background for each observation,
'bge':'<lcdict key>' array: sky background err for each observation,
'iha':'<lcdict key>' array: hour angle for each observation,
'izd':'<lcdict key>' array: zenith distance for each observation}
Alternatively, if these exact keys are already present in the lcdict,
indicate this by setting externalparams to None.
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 EPD process. If these are None, the
default values for `timecols`, `magcols`, and `errcols` for your light
curve format will be used here.
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 files.
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.
epdsmooth_sigclip : float or int or sequence of two floats/ints or None
This specifies how to sigma-clip the input LC before fitting the EPD
function to it.
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.
epdsmooth_windowsize : int
This is the number of LC points to smooth over to generate a smoothed
light curve that will be used to fit the EPD function.
epdsmooth_func : Python function
This sets the smoothing filter function to use. A Savitsky-Golay filter
is used to smooth the light curve by default. The functions that can be
used with this kwarg are listed in `varbase.trends`. If you want to use
your own function, it MUST have the following signature::
def smoothfunc(mags_array, window_size, **extraparams)
and return a numpy array of the same size as `mags_array` with the
smoothed time-series. Any extra params can be provided using the
`extraparams` dict.
epdsmooth_extraparams : dict
This is a dict of any extra filter params to supply to the smoothing
function.
nworkers : int
The number of parallel workers to launch when processing the LCs.
maxworkertasks : int
The maximum number of tasks a parallel worker will complete before it is
replaced with a new one (sometimes helps with memory-leaks).
Returns
-------
dict
Returns a dict organized by all the keys in the input `magcols` list,
containing lists of EPD pickle light curves for that `magcol`.
Notes
-----
- S -> measure of PSF sharpness (~1/sigma^2 sosmaller S = wider PSF)
- D -> measure of PSF ellipticity in xy direction
- K -> measure of PSF ellipticity in cross direction
S, D, K are related to the PSF's variance and covariance, see eqn 30-33 in
A. Pal's thesis: https://arxiv.org/abs/0906.3486
'''
try:
formatinfo = get_lcformat(lcformat,
use_lcformat_dir=lcformatdir)
if formatinfo:
(fileglob, 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
# override the default timecols, magcols, and errcols
# using the ones provided to the function
if timecols is None:
timecols = dtimecols
if magcols is None:
magcols = dmagcols
if errcols is None:
errcols = derrcols
outdict = {}
# run by magcol
for t, m, e in zip(timecols, magcols, errcols):
tasks = [(x, t, m, e, externalparams, lcformat, lcformatdir,
epdsmooth_sigclip, epdsmooth_windowsize,
epdsmooth_func, epdsmooth_extraparams) for
x in lclist]
pool = mp.Pool(nworkers, maxtasksperchild=maxworkertasks)
results = pool.map(parallel_epd_worker, tasks)
pool.close()
pool.join()
outdict[m] = results
return outdict | python | {
"resource": ""
} |
q258708 | parallel_epd_lcdir | validation | def parallel_epd_lcdir(
lcdir,
externalparams,
lcfileglob=None,
timecols=None,
magcols=None,
errcols=None,
lcformat='hat-sql',
lcformatdir=None,
epdsmooth_sigclip=3.0,
epdsmooth_windowsize=21,
epdsmooth_func=smooth_magseries_savgol,
epdsmooth_extraparams=None,
nworkers=NCPUS,
maxworkertasks=1000
):
'''This applies EPD in parallel to all LCs in a directory.
Parameters
----------
lcdir : str
The light curve directory to process.
externalparams : dict or None
This is a dict that indicates which keys in the lcdict obtained from the
lcfile correspond to the required external parameters. As with timecol,
magcol, and errcol, these can be simple keys (e.g. 'rjd') or compound
keys ('magaperture1.mags'). The dict should look something like::
{'fsv':'<lcdict key>' array: S values for each observation,
'fdv':'<lcdict key>' array: D values for each observation,
'fkv':'<lcdict key>' array: K values for each observation,
'xcc':'<lcdict key>' array: x coords for each observation,
'ycc':'<lcdict key>' array: y coords for each observation,
'bgv':'<lcdict key>' array: sky background for each observation,
'bge':'<lcdict key>' array: sky background err for each observation,
'iha':'<lcdict key>' array: hour angle for each observation,
'izd':'<lcdict key>' array: zenith distance for each observation}
lcfileglob : str or None
A UNIX fileglob to use to select light curve files in `lcdir`. If this
is not None, the value provided will override the default fileglob for
your light curve format.
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 EPD process. If these are None, the
default values for `timecols`, `magcols`, and `errcols` for your light
curve format will be used here.
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.
epdsmooth_sigclip : float or int or sequence of two floats/ints or None
This specifies how to sigma-clip the input LC before fitting the EPD
function to it.
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.
epdsmooth_windowsize : int
This is the number of LC points to smooth over to generate a smoothed
light curve that will be used to fit the EPD function.
epdsmooth_func : Python function
This sets the smoothing filter function to use. A Savitsky-Golay filter
is used to smooth the light curve by default. The functions that can be
used with this kwarg are listed in `varbase.trends`. If you want to use
your own function, it MUST have the following signature::
def smoothfunc(mags_array, window_size, **extraparams)
and return a numpy array of the same size as `mags_array` with the
smoothed time-series. Any extra params can be provided using the
`extraparams` dict.
epdsmooth_extraparams : dict
This is a dict of any extra filter params to supply to the smoothing
function.
nworkers : int
The number of parallel workers to launch when processing the LCs.
maxworkertasks : int
The maximum number of tasks a parallel worker will complete before it is
replaced with a new one (sometimes helps with memory-leaks).
Returns
-------
dict
Returns a dict organized by all the keys in the input `magcols` list,
containing lists of EPD pickle light curves for that `magcol`.
Notes
-----
- S -> measure of PSF sharpness (~1/sigma^2 sosmaller S = wider PSF)
- D -> measure of PSF ellipticity in xy direction
- K -> measure of PSF ellipticity in cross direction
S, D, K are related to the PSF's variance and covariance, see eqn 30-33 in
A. Pal's thesis: https://arxiv.org/abs/0906.3486
'''
try:
formatinfo = get_lcformat(lcformat,
use_lcformat_dir=lcformatdir)
if formatinfo:
(fileglob, 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
# find all the files matching the lcglob in lcdir
if lcfileglob is None:
lcfileglob = fileglob
lclist = sorted(glob.glob(os.path.join(lcdir, lcfileglob)))
return parallel_epd_lclist(
lclist,
externalparams,
timecols=timecols,
magcols=magcols,
errcols=errcols,
lcformat=lcformat,
epdsmooth_sigclip=epdsmooth_sigclip,
epdsmooth_windowsize=epdsmooth_windowsize,
epdsmooth_func=epdsmooth_func,
epdsmooth_extraparams=epdsmooth_extraparams,
nworkers=nworkers,
maxworkertasks=maxworkertasks
) | python | {
"resource": ""
} |
q258709 | _parallel_bls_worker | validation | def _parallel_bls_worker(task):
'''
This wraps Astropy's BoxLeastSquares for use with bls_parallel_pfind below.
`task` is a tuple::
task[0] = times
task[1] = mags
task[2] = errs
task[3] = magsarefluxes
task[4] = minfreq
task[5] = nfreq
task[6] = stepsize
task[7] = ndurations
task[8] = mintransitduration
task[9] = maxtransitduration
task[10] = blsobjective
task[11] = blsmethod
task[12] = blsoversample
'''
try:
times, mags, errs = task[:3]
magsarefluxes = task[3]
minfreq, nfreq, stepsize = task[4:7]
ndurations, mintransitduration, maxtransitduration = task[7:10]
blsobjective, blsmethod, blsoversample = task[10:]
frequencies = minfreq + nparange(nfreq)*stepsize
periods = 1.0/frequencies
# astropy's BLS requires durations in units of time
durations = nplinspace(mintransitduration*periods.min(),
maxtransitduration*periods.min(),
ndurations)
# set up the correct units for the BLS model
if magsarefluxes:
blsmodel = BoxLeastSquares(
times*u.day,
mags*u.dimensionless_unscaled,
dy=errs*u.dimensionless_unscaled
)
else:
blsmodel = BoxLeastSquares(
times*u.day,
mags*u.mag,
dy=errs*u.mag
)
blsresult = blsmodel.power(
periods*u.day,
durations*u.day,
objective=blsobjective,
method=blsmethod,
oversample=blsoversample
)
return {
'blsresult': blsresult,
'blsmodel': blsmodel,
'durations': durations,
'power': nparray(blsresult.power)
}
except Exception as e:
LOGEXCEPTION('BLS for frequency chunk: (%.6f, %.6f) failed.' %
(frequencies[0], frequencies[-1]))
return {
'blsresult': None,
'blsmodel': None,
'durations': durations,
'power': nparray([npnan for x in range(nfreq)]),
} | python | {
"resource": ""
} |
q258710 | read_csv_lightcurve | validation | def read_csv_lightcurve(lcfile):
'''
This reads in a K2 lightcurve in CSV format. Transparently reads gzipped
files.
Parameters
----------
lcfile : str
The light curve file to read.
Returns
-------
dict
Returns an lcdict.
'''
# read in the file first
if '.gz' in os.path.basename(lcfile):
LOGINFO('reading gzipped K2 LC: %s' % lcfile)
infd = gzip.open(lcfile,'rb')
else:
LOGINFO('reading K2 LC: %s' % lcfile)
infd = open(lcfile,'rb')
lctext = infd.read().decode()
infd.close()
# figure out the header and get the LC columns
lcstart = lctext.index('# LIGHTCURVE\n')
lcheader = lctext[:lcstart+12]
lccolumns = lctext[lcstart+13:].split('\n')
lccolumns = [x.split(',') for x in lccolumns if len(x) > 0]
# initialize the lcdict and parse the CSV header
lcdict = _parse_csv_header(lcheader)
# tranpose the LC rows into columns
lccolumns = list(zip(*lccolumns))
# write the columns to the dict
for colind, col in enumerate(lcdict['columns']):
# this picks out the caster to use when reading each column using the
# definitions in the lcutils.COLUMNDEFS dictionary
lcdict[col.lower()] = np.array([COLUMNDEFS[col][2](x)
for x in lccolumns[colind]])
lcdict['columns'] = [x.lower() for x in lcdict['columns']]
return lcdict | python | {
"resource": ""
} |
q258711 | _starfeatures_worker | validation | def _starfeatures_worker(task):
'''
This wraps starfeatures.
'''
try:
(lcfile, outdir, kdtree, objlist,
lcflist, neighbor_radius_arcsec,
deredden, custom_bandpasses, lcformat, lcformatdir) = task
return get_starfeatures(lcfile, outdir,
kdtree, objlist, lcflist,
neighbor_radius_arcsec,
deredden=deredden,
custom_bandpasses=custom_bandpasses,
lcformat=lcformat,
lcformatdir=lcformatdir)
except Exception as e:
return None | python | {
"resource": ""
} |
q258712 | serial_starfeatures | validation | def serial_starfeatures(lclist,
outdir,
lc_catalog_pickle,
neighbor_radius_arcsec,
maxobjects=None,
deredden=True,
custom_bandpasses=None,
lcformat='hat-sql',
lcformatdir=None):
'''This drives the `get_starfeatures` function for a collection of LCs.
Parameters
----------
lclist : list of str
The list of light curve file names to process.
outdir : str
The output directory where the results will be placed.
lc_catalog_pickle : str
The path to a catalog containing at a dict with least:
- an object ID array accessible with `dict['objects']['objectid']`
- an LC filename array accessible with `dict['objects']['lcfname']`
- a `scipy.spatial.KDTree` or `cKDTree` object to use for finding
neighbors for each object accessible with `dict['kdtree']`
A catalog pickle of the form needed can be produced using
:py:func:`astrobase.lcproc.catalogs.make_lclist` or
:py:func:`astrobase.lcproc.catalogs.filter_lclist`.
neighbor_radius_arcsec : float
This indicates the radius in arcsec to search for neighbors for this
object using the light curve catalog's `kdtree`, `objlist`, `lcflist`,
and in GAIA.
maxobjects : int
The number of objects to process from `lclist`.
deredden : bool
This controls if the colors and any color classifications will be
dereddened using 2MASS DUST.
custom_bandpasses : dict or None
This is a dict used to define any custom bandpasses in the
`in_objectinfo` dict you want to make this function aware of and
generate colors for. Use the format below for this dict::
{
'<bandpass_key_1>':{'dustkey':'<twomass_dust_key_1>',
'label':'<band_label_1>'
'colors':[['<bandkey1>-<bandkey2>',
'<BAND1> - <BAND2>'],
['<bandkey3>-<bandkey4>',
'<BAND3> - <BAND4>']]},
.
...
.
'<bandpass_key_N>':{'dustkey':'<twomass_dust_key_N>',
'label':'<band_label_N>'
'colors':[['<bandkey1>-<bandkey2>',
'<BAND1> - <BAND2>'],
['<bandkey3>-<bandkey4>',
'<BAND3> - <BAND4>']]},
}
Where:
`bandpass_key` is a key to use to refer to this bandpass in the
`objectinfo` dict, e.g. 'sdssg' for SDSS g band
`twomass_dust_key` is the key to use in the 2MASS DUST result table for
reddening per band-pass. For example, given the following DUST result
table (using http://irsa.ipac.caltech.edu/applications/DUST/)::
|Filter_name|LamEff |A_over_E_B_V_SandF|A_SandF|A_over_E_B_V_SFD|A_SFD|
|char |float |float |float |float |float|
| |microns| |mags | |mags |
CTIO U 0.3734 4.107 0.209 4.968 0.253
CTIO B 0.4309 3.641 0.186 4.325 0.221
CTIO V 0.5517 2.682 0.137 3.240 0.165
.
.
...
The `twomass_dust_key` for 'vmag' would be 'CTIO V'. If you want to
skip DUST lookup and want to pass in a specific reddening magnitude
for your bandpass, use a float for the value of
`twomass_dust_key`. If you want to skip DUST lookup entirely for
this bandpass, use None for the value of `twomass_dust_key`.
`band_label` is the label to use for this bandpass, e.g. 'W1' for
WISE-1 band, 'u' for SDSS u, etc.
The 'colors' list contains color definitions for all colors you want
to generate using this bandpass. this list contains elements of the
form::
['<bandkey1>-<bandkey2>','<BAND1> - <BAND2>']
where the the first item is the bandpass keys making up this color,
and the second item is the label for this color to be used by the
frontends. An example::
['sdssu-sdssg','u - g']
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.
Returns
-------
list of str
A list of all star features pickles produced.
'''
# make sure to make the output directory if it doesn't exist
if not os.path.exists(outdir):
os.makedirs(outdir)
if maxobjects:
lclist = lclist[:maxobjects]
# read in the kdtree pickle
with open(lc_catalog_pickle, 'rb') as infd:
kdt_dict = pickle.load(infd)
kdt = kdt_dict['kdtree']
objlist = kdt_dict['objects']['objectid']
objlcfl = kdt_dict['objects']['lcfname']
tasks = [(x, outdir, kdt, objlist, objlcfl,
neighbor_radius_arcsec,
deredden, custom_bandpasses,
lcformat, lcformatdir) for x in lclist]
for task in tqdm(tasks):
result = _starfeatures_worker(task)
return result | python | {
"resource": ""
} |
q258713 | parallel_starfeatures | validation | def parallel_starfeatures(lclist,
outdir,
lc_catalog_pickle,
neighbor_radius_arcsec,
maxobjects=None,
deredden=True,
custom_bandpasses=None,
lcformat='hat-sql',
lcformatdir=None,
nworkers=NCPUS):
'''This runs `get_starfeatures` in parallel for all light curves in `lclist`.
Parameters
----------
lclist : list of str
The list of light curve file names to process.
outdir : str
The output directory where the results will be placed.
lc_catalog_pickle : str
The path to a catalog containing at a dict with least:
- an object ID array accessible with `dict['objects']['objectid']`
- an LC filename array accessible with `dict['objects']['lcfname']`
- a `scipy.spatial.KDTree` or `cKDTree` object to use for finding
neighbors for each object accessible with `dict['kdtree']`
A catalog pickle of the form needed can be produced using
:py:func:`astrobase.lcproc.catalogs.make_lclist` or
:py:func:`astrobase.lcproc.catalogs.filter_lclist`.
neighbor_radius_arcsec : float
This indicates the radius in arcsec to search for neighbors for this
object using the light curve catalog's `kdtree`, `objlist`, `lcflist`,
and in GAIA.
maxobjects : int
The number of objects to process from `lclist`.
deredden : bool
This controls if the colors and any color classifications will be
dereddened using 2MASS DUST.
custom_bandpasses : dict or None
This is a dict used to define any custom bandpasses in the
`in_objectinfo` dict you want to make this function aware of and
generate colors for. Use the format below for this dict::
{
'<bandpass_key_1>':{'dustkey':'<twomass_dust_key_1>',
'label':'<band_label_1>'
'colors':[['<bandkey1>-<bandkey2>',
'<BAND1> - <BAND2>'],
['<bandkey3>-<bandkey4>',
'<BAND3> - <BAND4>']]},
.
...
.
'<bandpass_key_N>':{'dustkey':'<twomass_dust_key_N>',
'label':'<band_label_N>'
'colors':[['<bandkey1>-<bandkey2>',
'<BAND1> - <BAND2>'],
['<bandkey3>-<bandkey4>',
'<BAND3> - <BAND4>']]},
}
Where:
`bandpass_key` is a key to use to refer to this bandpass in the
`objectinfo` dict, e.g. 'sdssg' for SDSS g band
`twomass_dust_key` is the key to use in the 2MASS DUST result table for
reddening per band-pass. For example, given the following DUST result
table (using http://irsa.ipac.caltech.edu/applications/DUST/)::
|Filter_name|LamEff |A_over_E_B_V_SandF|A_SandF|A_over_E_B_V_SFD|A_SFD|
|char |float |float |float |float |float|
| |microns| |mags | |mags |
CTIO U 0.3734 4.107 0.209 4.968 0.253
CTIO B 0.4309 3.641 0.186 4.325 0.221
CTIO V 0.5517 2.682 0.137 3.240 0.165
.
.
...
The `twomass_dust_key` for 'vmag' would be 'CTIO V'. If you want to
skip DUST lookup and want to pass in a specific reddening magnitude
for your bandpass, use a float for the value of
`twomass_dust_key`. If you want to skip DUST lookup entirely for
this bandpass, use None for the value of `twomass_dust_key`.
`band_label` is the label to use for this bandpass, e.g. 'W1' for
WISE-1 band, 'u' for SDSS u, etc.
The 'colors' list contains color definitions for all colors you want
to generate using this bandpass. this list contains elements of the
form::
['<bandkey1>-<bandkey2>','<BAND1> - <BAND2>']
where the the first item is the bandpass keys making up this color,
and the second item is the label for this color to be used by the
frontends. An example::
['sdssu-sdssg','u - g']
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.
nworkers : int
The number of parallel workers to launch.
Returns
-------
dict
A dict with key:val pairs of the input light curve filename and the
output star features pickle for each LC processed.
'''
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
# make sure to make the output directory if it doesn't exist
if not os.path.exists(outdir):
os.makedirs(outdir)
if maxobjects:
lclist = lclist[:maxobjects]
# read in the kdtree pickle
with open(lc_catalog_pickle, 'rb') as infd:
kdt_dict = pickle.load(infd)
kdt = kdt_dict['kdtree']
objlist = kdt_dict['objects']['objectid']
objlcfl = kdt_dict['objects']['lcfname']
tasks = [(x, outdir, kdt, objlist, objlcfl,
neighbor_radius_arcsec,
deredden, custom_bandpasses, lcformat) for x in lclist]
with ProcessPoolExecutor(max_workers=nworkers) as executor:
resultfutures = executor.map(_starfeatures_worker, tasks)
results = [x for x in resultfutures]
resdict = {os.path.basename(x):y for (x,y) in zip(lclist, results)}
return resdict | python | {
"resource": ""
} |
q258714 | parallel_starfeatures_lcdir | validation | def parallel_starfeatures_lcdir(lcdir,
outdir,
lc_catalog_pickle,
neighbor_radius_arcsec,
fileglob=None,
maxobjects=None,
deredden=True,
custom_bandpasses=None,
lcformat='hat-sql',
lcformatdir=None,
nworkers=NCPUS,
recursive=True):
'''This runs parallel star feature extraction for a directory of LCs.
Parameters
----------
lcdir : list of str
The directory to search for light curves.
outdir : str
The output directory where the results will be placed.
lc_catalog_pickle : str
The path to a catalog containing at a dict with least:
- an object ID array accessible with `dict['objects']['objectid']`
- an LC filename array accessible with `dict['objects']['lcfname']`
- a `scipy.spatial.KDTree` or `cKDTree` object to use for finding
neighbors for each object accessible with `dict['kdtree']`
A catalog pickle of the form needed can be produced using
:py:func:`astrobase.lcproc.catalogs.make_lclist` or
:py:func:`astrobase.lcproc.catalogs.filter_lclist`.
neighbor_radius_arcsec : float
This indicates the radius in arcsec to search for neighbors for this
object using the light curve catalog's `kdtree`, `objlist`, `lcflist`,
and in GAIA.
fileglob : str
The UNIX file glob to use to search for the light curves in `lcdir`. If
None, the default value for the light curve format specified will be
used.
maxobjects : int
The number of objects to process from `lclist`.
deredden : bool
This controls if the colors and any color classifications will be
dereddened using 2MASS DUST.
custom_bandpasses : dict or None
This is a dict used to define any custom bandpasses in the
`in_objectinfo` dict you want to make this function aware of and
generate colors for. Use the format below for this dict::
{
'<bandpass_key_1>':{'dustkey':'<twomass_dust_key_1>',
'label':'<band_label_1>'
'colors':[['<bandkey1>-<bandkey2>',
'<BAND1> - <BAND2>'],
['<bandkey3>-<bandkey4>',
'<BAND3> - <BAND4>']]},
.
...
.
'<bandpass_key_N>':{'dustkey':'<twomass_dust_key_N>',
'label':'<band_label_N>'
'colors':[['<bandkey1>-<bandkey2>',
'<BAND1> - <BAND2>'],
['<bandkey3>-<bandkey4>',
'<BAND3> - <BAND4>']]},
}
Where:
`bandpass_key` is a key to use to refer to this bandpass in the
`objectinfo` dict, e.g. 'sdssg' for SDSS g band
`twomass_dust_key` is the key to use in the 2MASS DUST result table for
reddening per band-pass. For example, given the following DUST result
table (using http://irsa.ipac.caltech.edu/applications/DUST/)::
|Filter_name|LamEff |A_over_E_B_V_SandF|A_SandF|A_over_E_B_V_SFD|A_SFD|
|char |float |float |float |float |float|
| |microns| |mags | |mags |
CTIO U 0.3734 4.107 0.209 4.968 0.253
CTIO B 0.4309 3.641 0.186 4.325 0.221
CTIO V 0.5517 2.682 0.137 3.240 0.165
.
.
...
The `twomass_dust_key` for 'vmag' would be 'CTIO V'. If you want to
skip DUST lookup and want to pass in a specific reddening magnitude
for your bandpass, use a float for the value of
`twomass_dust_key`. If you want to skip DUST lookup entirely for
this bandpass, use None for the value of `twomass_dust_key`.
`band_label` is the label to use for this bandpass, e.g. 'W1' for
WISE-1 band, 'u' for SDSS u, etc.
The 'colors' list contains color definitions for all colors you want
to generate using this bandpass. this list contains elements of the
form::
['<bandkey1>-<bandkey2>','<BAND1> - <BAND2>']
where the the first item is the bandpass keys making up this color,
and the second item is the label for this color to be used by the
frontends. An example::
['sdssu-sdssg','u - g']
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.
nworkers : int
The number of parallel workers to launch.
Returns
-------
dict
A dict with key:val pairs of the input light curve filename and the
output star features pickle for each LC processed.
'''
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
if not fileglob:
fileglob = dfileglob
# now find the files
LOGINFO('searching for %s light curves in %s ...' % (lcformat, lcdir))
if recursive is False:
matching = glob.glob(os.path.join(lcdir, fileglob))
else:
# use recursive glob for Python 3.5+
if sys.version_info[:2] > (3,4):
matching = glob.glob(os.path.join(lcdir,
'**',
fileglob),recursive=True)
# otherwise, use os.walk and glob
else:
# use os.walk to go through the directories
walker = os.walk(lcdir)
matching = []
for root, dirs, _files in walker:
for sdir in dirs:
searchpath = os.path.join(root,
sdir,
fileglob)
foundfiles = glob.glob(searchpath)
if foundfiles:
matching.extend(foundfiles)
# now that we have all the files, process them
if matching and len(matching) > 0:
LOGINFO('found %s light curves, getting starfeatures...' %
len(matching))
return parallel_starfeatures(matching,
outdir,
lc_catalog_pickle,
neighbor_radius_arcsec,
deredden=deredden,
custom_bandpasses=custom_bandpasses,
maxobjects=maxobjects,
lcformat=lcformat,
lcformatdir=lcformatdir,
nworkers=nworkers)
else:
LOGERROR('no light curve files in %s format found in %s' % (lcformat,
lcdir))
return None | python | {
"resource": ""
} |
q258715 | pwd_phasebin | validation | def pwd_phasebin(phases, mags, binsize=0.002, minbin=9):
'''
This bins the phased mag series using the given binsize.
'''
bins = np.arange(0.0, 1.0, binsize)
binnedphaseinds = npdigitize(phases, bins)
binnedphases, binnedmags = [], []
for x in npunique(binnedphaseinds):
thisbin_inds = binnedphaseinds == x
thisbin_phases = phases[thisbin_inds]
thisbin_mags = mags[thisbin_inds]
if thisbin_inds.size > minbin:
binnedphases.append(npmedian(thisbin_phases))
binnedmags.append(npmedian(thisbin_mags))
return np.array(binnedphases), np.array(binnedmags) | python | {
"resource": ""
} |
q258716 | pdw_worker | validation | def pdw_worker(task):
'''
This is the parallel worker for the function below.
task[0] = frequency for this worker
task[1] = times array
task[2] = mags array
task[3] = fold_time
task[4] = j_range
task[5] = keep_threshold_1
task[6] = keep_threshold_2
task[7] = phasebinsize
we don't need errs for the worker.
'''
frequency = task[0]
times, modmags = task[1], task[2]
fold_time = task[3]
j_range = range(task[4])
keep_threshold_1 = task[5]
keep_threshold_2 = task[6]
phasebinsize = task[7]
try:
period = 1.0/frequency
# use the common phaser to phase and sort the mag
phased = phase_magseries(times,
modmags,
period,
fold_time,
wrap=False,
sort=True)
# bin in phase if requested, this turns this into a sort of PDM method
if phasebinsize is not None and phasebinsize > 0:
bphased = pwd_phasebin(phased['phase'],
phased['mags'],
binsize=phasebinsize)
phase_sorted = bphased[0]
mod_mag_sorted = bphased[1]
j_range = range(len(mod_mag_sorted) - 1)
else:
phase_sorted = phased['phase']
mod_mag_sorted = phased['mags']
# now calculate the string length
rolledmags = nproll(mod_mag_sorted,1)
rolledphases = nproll(phase_sorted,1)
strings = (
(rolledmags - mod_mag_sorted)*(rolledmags - mod_mag_sorted) +
(rolledphases - phase_sorted)*(rolledphases - phase_sorted)
)
strings[0] = (
((mod_mag_sorted[0] - mod_mag_sorted[-1]) *
(mod_mag_sorted[0] - mod_mag_sorted[-1])) +
((phase_sorted[0] - phase_sorted[-1] + 1) *
(phase_sorted[0] - phase_sorted[-1] + 1))
)
strlen = npsum(npsqrt(strings))
if (keep_threshold_1 < strlen < keep_threshold_2):
p_goodflag = True
else:
p_goodflag = False
return (period, strlen, p_goodflag)
except Exception as e:
LOGEXCEPTION('error in DWP')
return(period, npnan, False) | python | {
"resource": ""
} |
q258717 | _periodicfeatures_worker | validation | def _periodicfeatures_worker(task):
'''
This is a parallel worker for the drivers below.
'''
pfpickle, lcbasedir, outdir, starfeatures, kwargs = task
try:
return get_periodicfeatures(pfpickle,
lcbasedir,
outdir,
starfeatures=starfeatures,
**kwargs)
except Exception as e:
LOGEXCEPTION('failed to get periodicfeatures for %s' % pfpickle) | python | {
"resource": ""
} |
q258718 | serial_periodicfeatures | validation | def serial_periodicfeatures(pfpkl_list,
lcbasedir,
outdir,
starfeaturesdir=None,
fourierorder=5,
# these are depth, duration, ingress duration
transitparams=(-0.01,0.1,0.1),
# these are depth, duration, depth ratio, secphase
ebparams=(-0.2,0.3,0.7,0.5),
pdiff_threshold=1.0e-4,
sidereal_threshold=1.0e-4,
sampling_peak_multiplier=5.0,
sampling_startp=None,
sampling_endp=None,
starfeatures=None,
timecols=None,
magcols=None,
errcols=None,
lcformat='hat-sql',
lcformatdir=None,
sigclip=10.0,
verbose=False,
maxobjects=None):
'''This drives the periodicfeatures collection for a list of periodfinding
pickles.
Parameters
----------
pfpkl_list : list of str
The list of period-finding pickles to use.
lcbasedir : str
The base directory where the associated light curves are located.
outdir : str
The directory where the results will be written.
starfeaturesdir : str or None
The directory containing the `starfeatures-<objectid>.pkl` files for
each object to use calculate neighbor proximity light curve features.
fourierorder : int
The Fourier order to use to generate sinusoidal function and fit that to
the phased light curve.
transitparams : list of floats
The transit depth, duration, and ingress duration to use to generate a
trapezoid planet transit model fit to the phased light curve. The period
used is the one provided in `period`, while the epoch is automatically
obtained from a spline fit to the phased light curve.
ebparams : list of floats
The primary eclipse depth, eclipse duration, the primary-secondary depth
ratio, and the phase of the secondary eclipse to use to generate an
eclipsing binary model fit to the phased light curve. The period used is
the one provided in `period`, while the epoch is automatically obtained
from a spline fit to the phased light curve.
pdiff_threshold : float
This is the max difference between periods to consider them the same.
sidereal_threshold : float
This is the max difference between any of the 'best' periods and the
sidereal day periods to consider them the same.
sampling_peak_multiplier : float
This is the minimum multiplicative factor of a 'best' period's
normalized periodogram peak over the sampling periodogram peak at the
same period required to accept the 'best' period as possibly real.
sampling_startp, sampling_endp : float
If the `pgramlist` doesn't have a time-sampling Lomb-Scargle
periodogram, it will be obtained automatically. Use these kwargs to
control the minimum and maximum period interval to be searched when
generating this periodogram.
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.
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.
verbose : bool
If True, will indicate progress while working.
maxobjects : int
The total number of objects to process from `pfpkl_list`.
Returns
-------
Nothing.
'''
try:
formatinfo = get_lcformat(lcformat,
use_lcformat_dir=lcformatdir)
if formatinfo:
(fileglob, 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
# make sure to make the output directory if it doesn't exist
if not os.path.exists(outdir):
os.makedirs(outdir)
if maxobjects:
pfpkl_list = pfpkl_list[:maxobjects]
LOGINFO('%s periodfinding pickles to process' % len(pfpkl_list))
# if the starfeaturedir is provided, try to find a starfeatures pickle for
# each periodfinding pickle in pfpkl_list
if starfeaturesdir and os.path.exists(starfeaturesdir):
starfeatures_list = []
LOGINFO('collecting starfeatures pickles...')
for pfpkl in pfpkl_list:
sfpkl1 = os.path.basename(pfpkl).replace('periodfinding',
'starfeatures')
sfpkl2 = sfpkl1.replace('.gz','')
sfpath1 = os.path.join(starfeaturesdir, sfpkl1)
sfpath2 = os.path.join(starfeaturesdir, sfpkl2)
if os.path.exists(sfpath1):
starfeatures_list.append(sfpkl1)
elif os.path.exists(sfpath2):
starfeatures_list.append(sfpkl2)
else:
starfeatures_list.append(None)
else:
starfeatures_list = [None for x in pfpkl_list]
# generate the task list
kwargs = {'fourierorder':fourierorder,
'transitparams':transitparams,
'ebparams':ebparams,
'pdiff_threshold':pdiff_threshold,
'sidereal_threshold':sidereal_threshold,
'sampling_peak_multiplier':sampling_peak_multiplier,
'sampling_startp':sampling_startp,
'sampling_endp':sampling_endp,
'timecols':timecols,
'magcols':magcols,
'errcols':errcols,
'lcformat':lcformat,
'lcformatdir':lcformatdir,
'sigclip':sigclip,
'verbose':verbose}
tasks = [(x, lcbasedir, outdir, y, kwargs) for (x,y) in
zip(pfpkl_list, starfeatures_list)]
LOGINFO('processing periodfinding pickles...')
for task in tqdm(tasks):
_periodicfeatures_worker(task) | python | {
"resource": ""
} |
q258719 | parallel_periodicfeatures | validation | def parallel_periodicfeatures(pfpkl_list,
lcbasedir,
outdir,
starfeaturesdir=None,
fourierorder=5,
# these are depth, duration, ingress duration
transitparams=(-0.01,0.1,0.1),
# these are depth, duration, depth ratio, secphase
ebparams=(-0.2,0.3,0.7,0.5),
pdiff_threshold=1.0e-4,
sidereal_threshold=1.0e-4,
sampling_peak_multiplier=5.0,
sampling_startp=None,
sampling_endp=None,
timecols=None,
magcols=None,
errcols=None,
lcformat='hat-sql',
lcformatdir=None,
sigclip=10.0,
verbose=False,
maxobjects=None,
nworkers=NCPUS):
'''This runs periodic feature generation in parallel for all periodfinding
pickles in the input list.
Parameters
----------
pfpkl_list : list of str
The list of period-finding pickles to use.
lcbasedir : str
The base directory where the associated light curves are located.
outdir : str
The directory where the results will be written.
starfeaturesdir : str or None
The directory containing the `starfeatures-<objectid>.pkl` files for
each object to use calculate neighbor proximity light curve features.
fourierorder : int
The Fourier order to use to generate sinusoidal function and fit that to
the phased light curve.
transitparams : list of floats
The transit depth, duration, and ingress duration to use to generate a
trapezoid planet transit model fit to the phased light curve. The period
used is the one provided in `period`, while the epoch is automatically
obtained from a spline fit to the phased light curve.
ebparams : list of floats
The primary eclipse depth, eclipse duration, the primary-secondary depth
ratio, and the phase of the secondary eclipse to use to generate an
eclipsing binary model fit to the phased light curve. The period used is
the one provided in `period`, while the epoch is automatically obtained
from a spline fit to the phased light curve.
pdiff_threshold : float
This is the max difference between periods to consider them the same.
sidereal_threshold : float
This is the max difference between any of the 'best' periods and the
sidereal day periods to consider them the same.
sampling_peak_multiplier : float
This is the minimum multiplicative factor of a 'best' period's
normalized periodogram peak over the sampling periodogram peak at the
same period required to accept the 'best' period as possibly real.
sampling_startp, sampling_endp : float
If the `pgramlist` doesn't have a time-sampling Lomb-Scargle
periodogram, it will be obtained automatically. Use these kwargs to
control the minimum and maximum period interval to be searched when
generating this periodogram.
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.
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.
verbose : bool
If True, will indicate progress while working.
maxobjects : int
The total number of objects to process from `pfpkl_list`.
nworkers : int
The number of parallel workers to launch to process the input.
Returns
-------
dict
A dict containing key: val pairs of the input period-finder result and
the output periodic feature result pickles for each input pickle is
returned.
'''
# make sure to make the output directory if it doesn't exist
if not os.path.exists(outdir):
os.makedirs(outdir)
if maxobjects:
pfpkl_list = pfpkl_list[:maxobjects]
LOGINFO('%s periodfinding pickles to process' % len(pfpkl_list))
# if the starfeaturedir is provided, try to find a starfeatures pickle for
# each periodfinding pickle in pfpkl_list
if starfeaturesdir and os.path.exists(starfeaturesdir):
starfeatures_list = []
LOGINFO('collecting starfeatures pickles...')
for pfpkl in pfpkl_list:
sfpkl1 = os.path.basename(pfpkl).replace('periodfinding',
'starfeatures')
sfpkl2 = sfpkl1.replace('.gz','')
sfpath1 = os.path.join(starfeaturesdir, sfpkl1)
sfpath2 = os.path.join(starfeaturesdir, sfpkl2)
if os.path.exists(sfpath1):
starfeatures_list.append(sfpkl1)
elif os.path.exists(sfpath2):
starfeatures_list.append(sfpkl2)
else:
starfeatures_list.append(None)
else:
starfeatures_list = [None for x in pfpkl_list]
# generate the task list
kwargs = {'fourierorder':fourierorder,
'transitparams':transitparams,
'ebparams':ebparams,
'pdiff_threshold':pdiff_threshold,
'sidereal_threshold':sidereal_threshold,
'sampling_peak_multiplier':sampling_peak_multiplier,
'sampling_startp':sampling_startp,
'sampling_endp':sampling_endp,
'timecols':timecols,
'magcols':magcols,
'errcols':errcols,
'lcformat':lcformat,
'lcformatdir':lcformat,
'sigclip':sigclip,
'verbose':verbose}
tasks = [(x, lcbasedir, outdir, y, kwargs) for (x,y) in
zip(pfpkl_list, starfeatures_list)]
LOGINFO('processing periodfinding pickles...')
with ProcessPoolExecutor(max_workers=nworkers) as executor:
resultfutures = executor.map(_periodicfeatures_worker, tasks)
results = [x for x in resultfutures]
resdict = {os.path.basename(x):y for (x,y) in zip(pfpkl_list, results)}
return resdict | python | {
"resource": ""
} |
q258720 | parallel_periodicfeatures_lcdir | validation | def parallel_periodicfeatures_lcdir(
pfpkl_dir,
lcbasedir,
outdir,
pfpkl_glob='periodfinding-*.pkl*',
starfeaturesdir=None,
fourierorder=5,
# these are depth, duration, ingress duration
transitparams=(-0.01,0.1,0.1),
# these are depth, duration, depth ratio, secphase
ebparams=(-0.2,0.3,0.7,0.5),
pdiff_threshold=1.0e-4,
sidereal_threshold=1.0e-4,
sampling_peak_multiplier=5.0,
sampling_startp=None,
sampling_endp=None,
timecols=None,
magcols=None,
errcols=None,
lcformat='hat-sql',
lcformatdir=None,
sigclip=10.0,
verbose=False,
maxobjects=None,
nworkers=NCPUS,
recursive=True,
):
'''This runs parallel periodicfeature extraction for a directory of
periodfinding result pickles.
Parameters
----------
pfpkl_dir : str
The directory containing the pickles to process.
lcbasedir : str
The directory where all of the associated light curve files are located.
outdir : str
The directory where all the output will be written.
pfpkl_glob : str
The UNIX file glob to use to search for period-finder result pickles in
`pfpkl_dir`.
starfeaturesdir : str or None
The directory containing the `starfeatures-<objectid>.pkl` files for
each object to use calculate neighbor proximity light curve features.
fourierorder : int
The Fourier order to use to generate sinusoidal function and fit that to
the phased light curve.
transitparams : list of floats
The transit depth, duration, and ingress duration to use to generate a
trapezoid planet transit model fit to the phased light curve. The period
used is the one provided in `period`, while the epoch is automatically
obtained from a spline fit to the phased light curve.
ebparams : list of floats
The primary eclipse depth, eclipse duration, the primary-secondary depth
ratio, and the phase of the secondary eclipse to use to generate an
eclipsing binary model fit to the phased light curve. The period used is
the one provided in `period`, while the epoch is automatically obtained
from a spline fit to the phased light curve.
pdiff_threshold : float
This is the max difference between periods to consider them the same.
sidereal_threshold : float
This is the max difference between any of the 'best' periods and the
sidereal day periods to consider them the same.
sampling_peak_multiplier : float
This is the minimum multiplicative factor of a 'best' period's
normalized periodogram peak over the sampling periodogram peak at the
same period required to accept the 'best' period as possibly real.
sampling_startp, sampling_endp : float
If the `pgramlist` doesn't have a time-sampling Lomb-Scargle
periodogram, it will be obtained automatically. Use these kwargs to
control the minimum and maximum period interval to be searched when
generating this periodogram.
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.
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.
verbose : bool
If True, will indicate progress while working.
maxobjects : int
The total number of objects to process from `pfpkl_list`.
nworkers : int
The number of parallel workers to launch to process the input.
Returns
-------
dict
A dict containing key: val pairs of the input period-finder result and
the output periodic feature result pickles for each input pickle is
returned.
'''
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
fileglob = pfpkl_glob
# now find the files
LOGINFO('searching for periodfinding pickles in %s ...' % pfpkl_dir)
if recursive is False:
matching = glob.glob(os.path.join(pfpkl_dir, fileglob))
else:
# use recursive glob for Python 3.5+
if sys.version_info[:2] > (3,4):
matching = glob.glob(os.path.join(pfpkl_dir,
'**',
fileglob),recursive=True)
# otherwise, use os.walk and glob
else:
# use os.walk to go through the directories
walker = os.walk(pfpkl_dir)
matching = []
for root, dirs, _files in walker:
for sdir in dirs:
searchpath = os.path.join(root,
sdir,
fileglob)
foundfiles = glob.glob(searchpath)
if foundfiles:
matching.extend(foundfiles)
# now that we have all the files, process them
if matching and len(matching) > 0:
LOGINFO('found %s periodfinding pickles, getting periodicfeatures...' %
len(matching))
return parallel_periodicfeatures(
matching,
lcbasedir,
outdir,
starfeaturesdir=starfeaturesdir,
fourierorder=fourierorder,
transitparams=transitparams,
ebparams=ebparams,
pdiff_threshold=pdiff_threshold,
sidereal_threshold=sidereal_threshold,
sampling_peak_multiplier=sampling_peak_multiplier,
sampling_startp=sampling_startp,
sampling_endp=sampling_endp,
timecols=timecols,
magcols=magcols,
errcols=errcols,
lcformat=lcformat,
lcformatdir=lcformatdir,
sigclip=sigclip,
verbose=verbose,
maxobjects=maxobjects,
nworkers=nworkers,
)
else:
LOGERROR('no periodfinding pickles found in %s' % (pfpkl_dir))
return None | python | {
"resource": ""
} |
q258721 | _parse_xmatch_catalog_header | validation | def _parse_xmatch_catalog_header(xc, xk):
'''
This parses the header for a catalog file and returns it as a file object.
Parameters
----------
xc : str
The file name of an xmatch catalog prepared previously.
xk : list of str
This is a list of column names to extract from the xmatch catalog.
Returns
-------
tuple
The tuple returned is of the form::
(infd: the file object associated with the opened xmatch catalog,
catdefdict: a dict describing the catalog column definitions,
catcolinds: column number indices of the catalog,
catcoldtypes: the numpy dtypes of the catalog columns,
catcolnames: the names of each catalog column,
catcolunits: the units associated with each catalog column)
'''
catdef = []
# read in this catalog and transparently handle gzipped files
if xc.endswith('.gz'):
infd = gzip.open(xc,'rb')
else:
infd = open(xc,'rb')
# read in the defs
for line in infd:
if line.decode().startswith('#'):
catdef.append(
line.decode().replace('#','').strip().rstrip('\n')
)
if not line.decode().startswith('#'):
break
if not len(catdef) > 0:
LOGERROR("catalog definition not parseable "
"for catalog: %s, skipping..." % xc)
return None
catdef = ' '.join(catdef)
catdefdict = json.loads(catdef)
catdefkeys = [x['key'] for x in catdefdict['columns']]
catdefdtypes = [x['dtype'] for x in catdefdict['columns']]
catdefnames = [x['name'] for x in catdefdict['columns']]
catdefunits = [x['unit'] for x in catdefdict['columns']]
# get the correct column indices and dtypes for the requested columns
# from the catdefdict
catcolinds = []
catcoldtypes = []
catcolnames = []
catcolunits = []
for xkcol in xk:
if xkcol in catdefkeys:
xkcolind = catdefkeys.index(xkcol)
catcolinds.append(xkcolind)
catcoldtypes.append(catdefdtypes[xkcolind])
catcolnames.append(catdefnames[xkcolind])
catcolunits.append(catdefunits[xkcolind])
return (infd, catdefdict,
catcolinds, catcoldtypes, catcolnames, catcolunits) | python | {
"resource": ""
} |
q258722 | load_xmatch_external_catalogs | validation | def load_xmatch_external_catalogs(xmatchto, xmatchkeys, outfile=None):
'''This loads the external xmatch catalogs into a dict for use in an xmatch.
Parameters
----------
xmatchto : list of str
This is a list of paths to all the catalog text files that will be
loaded.
The text files must be 'CSVs' that use the '|' character as the
separator betwen columns. These files should all begin with a header in
JSON format on lines starting with the '#' character. this header will
define the catalog and contains the name of the catalog and the column
definitions. Column definitions must have the column name and the numpy
dtype of the columns (in the same format as that expected for the
numpy.genfromtxt function). Any line that does not begin with '#' is
assumed to be part of the columns in the catalog. An example is shown
below::
# {"name":"NSVS catalog of variable stars",
# "columns":[
# {"key":"objectid", "dtype":"U20", "name":"Object ID", "unit": null},
# {"key":"ra", "dtype":"f8", "name":"RA", "unit":"deg"},
# {"key":"decl","dtype":"f8", "name": "Declination", "unit":"deg"},
# {"key":"sdssr","dtype":"f8","name":"SDSS r", "unit":"mag"},
# {"key":"vartype","dtype":"U20","name":"Variable type", "unit":null}
# ],
# "colra":"ra",
# "coldec":"decl",
# "description":"Contains variable stars from the NSVS catalog"}
objectid1 | 45.0 | -20.0 | 12.0 | detached EB
objectid2 | 145.0 | 23.0 | 10.0 | RRab
objectid3 | 12.0 | 11.0 | 14.0 | Cepheid
.
.
.
xmatchkeys : list of lists
This is the list of lists of column names (as str) to get out of each
`xmatchto` catalog. This should be the same length as `xmatchto` and
each element here will apply to the respective file in `xmatchto`.
outfile : str or None
If this is not None, set this to the name of the pickle to write the
collected xmatch catalogs to. this pickle can then be loaded
transparently by the :py:func:`astrobase.checkplot.pkl.checkplot_dict`,
:py:func:`astrobase.checkplot.pkl.checkplot_pickle` functions to provide
xmatch info to the
:py:func:`astrobase.checkplot.pkl_xmatch.xmatch_external_catalogs`
function below.
If this is None, will return the loaded xmatch catalogs directly. This
will be a huge dict, so make sure you have enough RAM.
Returns
-------
str or dict
Based on the `outfile` kwarg, will either return the path to a collected
xmatch pickle file or the collected xmatch dict.
'''
outdict = {}
for xc, xk in zip(xmatchto, xmatchkeys):
parsed_catdef = _parse_xmatch_catalog_header(xc, xk)
if not parsed_catdef:
continue
(infd, catdefdict,
catcolinds, catcoldtypes,
catcolnames, catcolunits) = parsed_catdef
# get the specified columns out of the catalog
catarr = np.genfromtxt(infd,
usecols=catcolinds,
names=xk,
dtype=','.join(catcoldtypes),
comments='#',
delimiter='|',
autostrip=True)
infd.close()
catshortname = os.path.splitext(os.path.basename(xc))[0]
catshortname = catshortname.replace('.csv','')
#
# make a kdtree for this catalog
#
# get the ra and decl columns
objra, objdecl = (catarr[catdefdict['colra']],
catarr[catdefdict['coldec']])
# get the xyz unit vectors from ra,decl
cosdecl = np.cos(np.radians(objdecl))
sindecl = np.sin(np.radians(objdecl))
cosra = np.cos(np.radians(objra))
sinra = np.sin(np.radians(objra))
xyz = np.column_stack((cosra*cosdecl,sinra*cosdecl, sindecl))
# generate the kdtree
kdt = cKDTree(xyz,copy_data=True)
# generate the outdict element for this catalog
catoutdict = {'kdtree':kdt,
'data':catarr,
'columns':xk,
'colnames':catcolnames,
'colunits':catcolunits,
'name':catdefdict['name'],
'desc':catdefdict['description']}
outdict[catshortname] = catoutdict
if outfile is not None:
# if we're on OSX, we apparently need to save the file in chunks smaller
# than 2 GB to make it work right. can't load pickles larger than 4 GB
# either, but 3 GB < total size < 4 GB appears to be OK when loading.
# also see: https://bugs.python.org/issue24658.
# fix adopted from: https://stackoverflow.com/a/38003910
if sys.platform == 'darwin':
dumpbytes = pickle.dumps(outdict, protocol=pickle.HIGHEST_PROTOCOL)
max_bytes = 2**31 - 1
with open(outfile, 'wb') as outfd:
for idx in range(0, len(dumpbytes), max_bytes):
outfd.write(dumpbytes[idx:idx+max_bytes])
else:
with open(outfile, 'wb') as outfd:
pickle.dump(outdict, outfd, pickle.HIGHEST_PROTOCOL)
return outfile
else:
return outdict | python | {
"resource": ""
} |
q258723 | angle_wrap | validation | def angle_wrap(angle, radians=False):
'''Wraps the input angle to 360.0 degrees.
Parameters
----------
angle : float
The angle to wrap around 360.0 deg.
radians : bool
If True, will assume that the input is in radians. The output will then
also be in radians.
Returns
-------
float
Wrapped angle. If radians is True: input is assumed to be in radians,
output is also in radians.
'''
if radians:
wrapped = angle % (2.0*pi_value)
if wrapped < 0.0:
wrapped = 2.0*pi_value + wrapped
else:
wrapped = angle % 360.0
if wrapped < 0.0:
wrapped = 360.0 + wrapped
return wrapped | python | {
"resource": ""
} |
q258724 | hms_to_decimal | validation | def hms_to_decimal(hours, minutes, seconds, returndeg=True):
'''Converts from HH, MM, SS to a decimal value.
Parameters
----------
hours : int
The HH part of a RA coordinate.
minutes : int
The MM part of a RA coordinate.
seconds : float
The SS.sss part of a RA coordinate.
returndeg : bool
If this is True, then will return decimal degrees as the output.
If this is False, then will return decimal HOURS as the output.
Decimal hours are sometimes used in FITS headers.
Returns
-------
float
The right ascension value in either decimal degrees or decimal hours
depending on `returndeg`.
'''
if hours > 24:
return None
else:
dec_hours = fabs(hours) + fabs(minutes)/60.0 + fabs(seconds)/3600.0
if returndeg:
dec_deg = dec_hours*15.0
if dec_deg < 0:
dec_deg = dec_deg + 360.0
dec_deg = dec_deg % 360.0
return dec_deg
else:
return dec_hours | python | {
"resource": ""
} |
q258725 | great_circle_dist | validation | def great_circle_dist(ra1, dec1, ra2, dec2):
'''Calculates the great circle angular distance between two coords.
This calculates the great circle angular distance in arcseconds between two
coordinates (ra1,dec1) and (ra2,dec2). This is basically a clone of GCIRC
from the IDL Astrolib.
Parameters
----------
ra1,dec1 : float or array-like
The first coordinate's right ascension and declination value(s) in
decimal degrees.
ra2,dec2 : float or array-like
The second coordinate's right ascension and declination value(s) in
decimal degrees.
Returns
-------
float or array-like
Great circle distance between the two coordinates in arseconds.
Notes
-----
If (`ra1`, `dec1`) is scalar and (`ra2`, `dec2`) is scalar: the result is a
float distance in arcseconds.
If (`ra1`, `dec1`) is scalar and (`ra2`, `dec2`) is array-like: the result
is an np.array with distance in arcseconds between (`ra1`, `dec1`) and each
element of (`ra2`, `dec2`).
If (`ra1`, `dec1`) is array-like and (`ra2`, `dec2`) is scalar: the result
is an np.array with distance in arcseconds between (`ra2`, `dec2`) and each
element of (`ra1`, `dec1`).
If (`ra1`, `dec1`) and (`ra2`, `dec2`) are both array-like: the result is an
np.array with the pair-wise distance in arcseconds between each element of
the two coordinate lists. In this case, if the input array-likes are not the
same length, then excess elements of the longer one will be ignored.
'''
# wrap RA if negative or larger than 360.0 deg
in_ra1 = ra1 % 360.0
in_ra1 = in_ra1 + 360.0*(in_ra1 < 0.0)
in_ra2 = ra2 % 360.0
in_ra2 = in_ra2 + 360.0*(in_ra1 < 0.0)
# convert to radians
ra1_rad, dec1_rad = np.deg2rad(in_ra1), np.deg2rad(dec1)
ra2_rad, dec2_rad = np.deg2rad(in_ra2), np.deg2rad(dec2)
del_dec2 = (dec2_rad - dec1_rad)/2.0
del_ra2 = (ra2_rad - ra1_rad)/2.0
sin_dist = np.sqrt(np.sin(del_dec2) * np.sin(del_dec2) +
np.cos(dec1_rad) * np.cos(dec2_rad) *
np.sin(del_ra2) * np.sin(del_ra2))
dist_rad = 2.0 * np.arcsin(sin_dist)
# return the distance in arcseconds
return np.rad2deg(dist_rad)*3600.0 | python | {
"resource": ""
} |
q258726 | total_proper_motion | validation | def total_proper_motion(pmra, pmdecl, decl):
'''This calculates the total proper motion of an object.
Parameters
----------
pmra : float or array-like
The proper motion(s) in right ascension, measured in mas/yr.
pmdecl : float or array-like
The proper motion(s) in declination, measured in mas/yr.
decl : float or array-like
The declination of the object(s) in decimal degrees.
Returns
-------
float or array-like
The total proper motion(s) of the object(s) in mas/yr.
'''
pm = np.sqrt( pmdecl*pmdecl + pmra*pmra*np.cos(np.radians(decl)) *
np.cos(np.radians(decl)) )
return pm | python | {
"resource": ""
} |
q258727 | equatorial_to_galactic | validation | def equatorial_to_galactic(ra, decl, equinox='J2000'):
'''This converts from equatorial coords to galactic coords.
Parameters
----------
ra : float or array-like
Right ascension values(s) in decimal degrees.
decl : float or array-like
Declination value(s) in decimal degrees.
equinox : str
The equinox that the coordinates are measured at. This must be
recognizable by Astropy's `SkyCoord` class.
Returns
-------
tuple of (float, float) or tuple of (np.array, np.array)
The galactic coordinates (l, b) for each element of the input
(`ra`, `decl`).
'''
# convert the ra/decl to gl, gb
radecl = SkyCoord(ra=ra*u.degree, dec=decl*u.degree, equinox=equinox)
gl = radecl.galactic.l.degree
gb = radecl.galactic.b.degree
return gl, gb | python | {
"resource": ""
} |
q258728 | galactic_to_equatorial | validation | def galactic_to_equatorial(gl, gb):
'''This converts from galactic coords to equatorial coordinates.
Parameters
----------
gl : float or array-like
Galactic longitude values(s) in decimal degrees.
gb : float or array-like
Galactic latitude value(s) in decimal degrees.
Returns
-------
tuple of (float, float) or tuple of (np.array, np.array)
The equatorial coordinates (RA, DEC) for each element of the input
(`gl`, `gb`) in decimal degrees. These are reported in the ICRS frame.
'''
gal = SkyCoord(gl*u.degree, gl*u.degree, frame='galactic')
transformed = gal.transform_to('icrs')
return transformed.ra.degree, transformed.dec.degree | python | {
"resource": ""
} |
q258729 | xieta_from_radecl | validation | def xieta_from_radecl(inra, indecl,
incenterra, incenterdecl,
deg=True):
'''This returns the image-plane projected xi-eta coords for inra, indecl.
Parameters
----------
inra,indecl : array-like
The equatorial coordinates to get the xi, eta coordinates for in decimal
degrees or radians.
incenterra,incenterdecl : float
The center coordinate values to use to calculate the plane-projected
coordinates around.
deg : bool
If this is True, the input angles are assumed to be in degrees and the
output is in degrees as well.
Returns
-------
tuple of np.arrays
This is the (`xi`, `eta`) coordinate pairs corresponding to the
image-plane projected coordinates for each pair of input equatorial
coordinates in (`inra`, `indecl`).
'''
if deg:
ra = np.radians(inra)
decl = np.radians(indecl)
centerra = np.radians(incenterra)
centerdecl = np.radians(incenterdecl)
else:
ra = inra
decl = indecl
centerra = incenterra
centerdecl = incenterdecl
cdecc = np.cos(centerdecl)
sdecc = np.sin(centerdecl)
crac = np.cos(centerra)
srac = np.sin(centerra)
uu = np.cos(decl)*np.cos(ra)
vv = np.cos(decl)*np.sin(ra)
ww = np.sin(decl)
uun = uu*cdecc*crac + vv*cdecc*srac + ww*sdecc
vvn = -uu*srac + vv*crac
wwn = -uu*sdecc*crac - vv*sdecc*srac + ww*cdecc
denom = vvn*vvn + wwn*wwn
aunn = np.zeros_like(uun)
aunn[uun >= 1.0] = 0.0
aunn[uun < 1.0] = np.arccos(uun)
xi, eta = np.zeros_like(aunn), np.zeros_like(aunn)
xi[(aunn <= 0.0) | (denom <= 0.0)] = 0.0
eta[(aunn <= 0.0) | (denom <= 0.0)] = 0.0
sdenom = np.sqrt(denom)
xi[(aunn > 0.0) | (denom > 0.0)] = aunn*vvn/sdenom
eta[(aunn > 0.0) | (denom > 0.0)] = aunn*wwn/sdenom
if deg:
return np.degrees(xi), np.degrees(eta)
else:
return xi, eta | python | {
"resource": ""
} |
q258730 | generate_transit_lightcurve | validation | def generate_transit_lightcurve(
times,
mags=None,
errs=None,
paramdists={'transitperiod':sps.uniform(loc=0.1,scale=49.9),
'transitdepth':sps.uniform(loc=1.0e-4,scale=2.0e-2),
'transitduration':sps.uniform(loc=0.01,scale=0.29)},
magsarefluxes=False,
):
'''This generates fake planet transit light curves.
Parameters
----------
times : np.array
This is an array of time values that will be used as the time base.
mags,errs : np.array
These arrays will have the model added to them. If either is
None, `np.full_like(times, 0.0)` will used as a substitute and the model
light curve will be centered around 0.0.
paramdists : dict
This is a dict containing parameter distributions to use for the
model params, containing the following keys ::
{'transitperiod', 'transitdepth', 'transitduration'}
The values of these keys should all be 'frozen' scipy.stats distribution
objects, e.g.:
https://docs.scipy.org/doc/scipy/reference/stats.html#continuous-distributions
The variability epoch will be automatically chosen from a uniform
distribution between `times.min()` and `times.max()`.
The ingress duration will be automatically chosen from a uniform
distribution ranging from 0.05 to 0.5 of the transitduration.
The transitdepth will be flipped automatically as appropriate if
`magsarefluxes=True`.
magsarefluxes : bool
If the generated time series is meant to be a flux time-series, set this
to True to get the correct sign of variability amplitude.
Returns
-------
dict
A dict of the form below is returned::
{'vartype': 'planet',
'params': {'transitperiod': generated value of period,
'transitepoch': generated value of epoch,
'transitdepth': generated value of transit depth,
'transitduration': generated value of transit duration,
'ingressduration': generated value of transit ingress
duration},
'times': the model times,
'mags': the model mags,
'errs': the model errs,
'varperiod': the generated period of variability == 'transitperiod'
'varamplitude': the generated amplitude of
variability == 'transitdepth'}
'''
if mags is None:
mags = np.full_like(times, 0.0)
if errs is None:
errs = np.full_like(times, 0.0)
# choose the epoch
epoch = npr.random()*(times.max() - times.min()) + times.min()
# choose the period, depth, duration
period = paramdists['transitperiod'].rvs(size=1)
depth = paramdists['transitdepth'].rvs(size=1)
duration = paramdists['transitduration'].rvs(size=1)
# figure out the ingress duration
ingduration = npr.random()*(0.5*duration - 0.05*duration) + 0.05*duration
# fix the transit depth if it needs to be flipped
if magsarefluxes and depth < 0.0:
depth = -depth
elif not magsarefluxes and depth > 0.0:
depth = -depth
# generate the model
modelmags, phase, ptimes, pmags, perrs = (
transits.trapezoid_transit_func([period, epoch, depth,
duration, ingduration],
times,
mags,
errs)
)
# resort in original time order
timeind = np.argsort(ptimes)
mtimes = ptimes[timeind]
mmags = modelmags[timeind]
merrs = perrs[timeind]
# return a dict with everything
modeldict = {
'vartype':'planet',
'params':{x:np.asscalar(y) for x,y in zip(['transitperiod',
'transitepoch',
'transitdepth',
'transitduration',
'ingressduration'],
[period,
epoch,
depth,
duration,
ingduration])},
'times':mtimes,
'mags':mmags,
'errs':merrs,
# these are standard keys that help with later characterization of
# variability as a function period, variability amplitude, object mag,
# ndet, etc.
'varperiod':period,
'varamplitude':depth
}
return modeldict | python | {
"resource": ""
} |
q258731 | generate_eb_lightcurve | validation | def generate_eb_lightcurve(
times,
mags=None,
errs=None,
paramdists={'period':sps.uniform(loc=0.2,scale=99.8),
'pdepth':sps.uniform(loc=1.0e-4,scale=0.7),
'pduration':sps.uniform(loc=0.01,scale=0.44),
'depthratio':sps.uniform(loc=0.01,scale=0.99),
'secphase':sps.norm(loc=0.5,scale=0.1)},
magsarefluxes=False,
):
'''This generates fake EB light curves.
Parameters
----------
times : np.array
This is an array of time values that will be used as the time base.
mags,errs : np.array
These arrays will have the model added to them. If either is
None, `np.full_like(times, 0.0)` will used as a substitute and the model
light curve will be centered around 0.0.
paramdists : dict
This is a dict containing parameter distributions to use for the
model params, containing the following keys ::
{'period', 'pdepth', 'pduration', 'depthratio', 'secphase'}
The values of these keys should all be 'frozen' scipy.stats distribution
objects, e.g.:
https://docs.scipy.org/doc/scipy/reference/stats.html#continuous-distributions
The variability epoch will be automatically chosen from a uniform
distribution between `times.min()` and `times.max()`.
The `pdepth` will be flipped automatically as appropriate if
`magsarefluxes=True`.
magsarefluxes : bool
If the generated time series is meant to be a flux time-series, set this
to True to get the correct sign of variability amplitude.
Returns
-------
dict
A dict of the form below is returned::
{'vartype': 'EB',
'params': {'period': generated value of period,
'epoch': generated value of epoch,
'pdepth': generated value of priary eclipse depth,
'pduration': generated value of prim eclipse duration,
'depthratio': generated value of prim/sec eclipse
depth ratio},
'times': the model times,
'mags': the model mags,
'errs': the model errs,
'varperiod': the generated period of variability == 'period'
'varamplitude': the generated amplitude of
variability == 'pdepth'}
'''
if mags is None:
mags = np.full_like(times, 0.0)
if errs is None:
errs = np.full_like(times, 0.0)
# choose the epoch
epoch = npr.random()*(times.max() - times.min()) + times.min()
# choose the period, pdepth, duration, depthratio
period = paramdists['period'].rvs(size=1)
pdepth = paramdists['pdepth'].rvs(size=1)
pduration = paramdists['pduration'].rvs(size=1)
depthratio = paramdists['depthratio'].rvs(size=1)
secphase = paramdists['secphase'].rvs(size=1)
# fix the transit depth if it needs to be flipped
if magsarefluxes and pdepth < 0.0:
pdepth = -pdepth
elif not magsarefluxes and pdepth > 0.0:
pdepth = -pdepth
# generate the model
modelmags, phase, ptimes, pmags, perrs = (
eclipses.invgauss_eclipses_func([period, epoch, pdepth,
pduration, depthratio, secphase],
times,
mags,
errs)
)
# resort in original time order
timeind = np.argsort(ptimes)
mtimes = ptimes[timeind]
mmags = modelmags[timeind]
merrs = perrs[timeind]
# return a dict with everything
modeldict = {
'vartype':'EB',
'params':{x:np.asscalar(y) for x,y in zip(['period',
'epoch',
'pdepth',
'pduration',
'depthratio'],
[period,
epoch,
pdepth,
pduration,
depthratio])},
'times':mtimes,
'mags':mmags,
'errs':merrs,
'varperiod':period,
'varamplitude':pdepth,
}
return modeldict | python | {
"resource": ""
} |
q258732 | generate_flare_lightcurve | validation | def generate_flare_lightcurve(
times,
mags=None,
errs=None,
paramdists={
# flare peak amplitude from 0.01 mag to 1.0 mag above median. this
# is tuned for redder bands, flares are much stronger in bluer
# bands, so tune appropriately for your situation.
'amplitude':sps.uniform(loc=0.01,scale=0.99),
# up to 5 flares per LC and at least 1
'nflares':[1,5],
# 10 minutes to 1 hour for rise stdev
'risestdev':sps.uniform(loc=0.007, scale=0.04),
# 1 hour to 4 hours for decay time constant
'decayconst':sps.uniform(loc=0.04, scale=0.163)
},
magsarefluxes=False,
):
'''This generates fake flare light curves.
Parameters
----------
times : np.array
This is an array of time values that will be used as the time base.
mags,errs : np.array
These arrays will have the model added to them. If either is
None, `np.full_like(times, 0.0)` will used as a substitute and the model
light curve will be centered around 0.0.
paramdists : dict
This is a dict containing parameter distributions to use for the
model params, containing the following keys ::
{'amplitude', 'nflares', 'risestdev', 'decayconst'}
The values of these keys should all be 'frozen' scipy.stats distribution
objects, e.g.:
https://docs.scipy.org/doc/scipy/reference/stats.html#continuous-distributions
The `flare_peak_time` for each flare will be generated automatically
between `times.min()` and `times.max()` using a uniform distribution.
The `amplitude` will be flipped automatically as appropriate if
`magsarefluxes=True`.
magsarefluxes : bool
If the generated time series is meant to be a flux time-series, set this
to True to get the correct sign of variability amplitude.
Returns
-------
dict
A dict of the form below is returned::
{'vartype': 'flare',
'params': {'amplitude': generated value of flare amplitudes,
'nflares': generated value of number of flares,
'risestdev': generated value of stdev of rise time,
'decayconst': generated value of decay constant,
'peaktime': generated value of flare peak time},
'times': the model times,
'mags': the model mags,
'errs': the model errs,
'varamplitude': the generated amplitude of
variability == 'amplitude'}
'''
if mags is None:
mags = np.full_like(times, 0.0)
if errs is None:
errs = np.full_like(times, 0.0)
nflares = npr.randint(paramdists['nflares'][0],
high=paramdists['nflares'][1])
# generate random flare peak times based on the number of flares
flarepeaktimes = (
npr.random(
size=nflares
)*(times.max() - times.min()) + times.min()
)
# now add the flares to the time-series
params = {'nflares':nflares}
for flareind, peaktime in zip(range(nflares), flarepeaktimes):
# choose the amplitude, rise stdev and decay time constant
amp = paramdists['amplitude'].rvs(size=1)
risestdev = paramdists['risestdev'].rvs(size=1)
decayconst = paramdists['decayconst'].rvs(size=1)
# fix the transit depth if it needs to be flipped
if magsarefluxes and amp < 0.0:
amp = -amp
elif not magsarefluxes and amp > 0.0:
amp = -amp
# add this flare to the light curve
modelmags, ptimes, pmags, perrs = (
flares.flare_model(
[amp, peaktime, risestdev, decayconst],
times,
mags,
errs
)
)
# update the mags
mags = modelmags
# add the flare params to the modeldict
params[flareind] = {'peaktime':peaktime,
'amplitude':amp,
'risestdev':risestdev,
'decayconst':decayconst}
#
# done with all flares
#
# return a dict with everything
modeldict = {
'vartype':'flare',
'params':params,
'times':times,
'mags':mags,
'errs':errs,
'varperiod':None,
# FIXME: this is complicated because we can have multiple flares
# figure out a good way to handle this upstream
'varamplitude':[params[x]['amplitude']
for x in range(params['nflares'])],
}
return modeldict | python | {
"resource": ""
} |
q258733 | generate_sinusoidal_lightcurve | validation | def generate_sinusoidal_lightcurve(
times,
mags=None,
errs=None,
paramdists={
'period':sps.uniform(loc=0.04,scale=500.0),
'fourierorder':[2,10],
'amplitude':sps.uniform(loc=0.1,scale=0.9),
'phioffset':0.0,
},
magsarefluxes=False
):
'''This generates fake sinusoidal light curves.
This can be used for a variety of sinusoidal variables, e.g. RRab, RRc,
Cepheids, Miras, etc. The functions that generate these model LCs below
implement the following table::
## FOURIER PARAMS FOR SINUSOIDAL VARIABLES
#
# type fourier period [days]
# order dist limits dist
# RRab 8 to 10 uniform 0.45--0.80 uniform
# RRc 3 to 6 uniform 0.10--0.40 uniform
# HADS 7 to 9 uniform 0.04--0.10 uniform
# rotator 2 to 5 uniform 0.80--120.0 uniform
# LPV 2 to 5 uniform 250--500.0 uniform
FIXME: for better model LCs, figure out how scipy.signal.butter works and
low-pass filter using scipy.signal.filtfilt.
Parameters
----------
times : np.array
This is an array of time values that will be used as the time base.
mags,errs : np.array
These arrays will have the model added to them. If either is
None, `np.full_like(times, 0.0)` will used as a substitute and the model
light curve will be centered around 0.0.
paramdists : dict
This is a dict containing parameter distributions to use for the
model params, containing the following keys ::
{'period', 'fourierorder', 'amplitude', 'phioffset'}
The values of these keys should all be 'frozen' scipy.stats distribution
objects, e.g.:
https://docs.scipy.org/doc/scipy/reference/stats.html#continuous-distributions
The variability epoch will be automatically chosen from a uniform
distribution between `times.min()` and `times.max()`.
The `amplitude` will be flipped automatically as appropriate if
`magsarefluxes=True`.
magsarefluxes : bool
If the generated time series is meant to be a flux time-series, set this
to True to get the correct sign of variability amplitude.
Returns
-------
dict
A dict of the form below is returned::
{'vartype': 'sinusoidal',
'params': {'period': generated value of period,
'epoch': generated value of epoch,
'amplitude': generated value of amplitude,
'fourierorder': generated value of fourier order,
'fourieramps': generated values of fourier amplitudes,
'fourierphases': generated values of fourier phases},
'times': the model times,
'mags': the model mags,
'errs': the model errs,
'varperiod': the generated period of variability == 'period'
'varamplitude': the generated amplitude of
variability == 'amplitude'}
'''
if mags is None:
mags = np.full_like(times, 0.0)
if errs is None:
errs = np.full_like(times, 0.0)
# choose the epoch
epoch = npr.random()*(times.max() - times.min()) + times.min()
# choose the period, fourierorder, and amplitude
period = paramdists['period'].rvs(size=1)
fourierorder = npr.randint(paramdists['fourierorder'][0],
high=paramdists['fourierorder'][1])
amplitude = paramdists['amplitude'].rvs(size=1)
# fix the amplitude if it needs to be flipped
if magsarefluxes and amplitude < 0.0:
amplitude = -amplitude
elif not magsarefluxes and amplitude > 0.0:
amplitude = -amplitude
# generate the amplitudes and phases of the Fourier components
ampcomps = [abs(amplitude/2.0)/float(x)
for x in range(1,fourierorder+1)]
phacomps = [paramdists['phioffset']*float(x)
for x in range(1,fourierorder+1)]
# now that we have our amp and pha components, generate the light curve
modelmags, phase, ptimes, pmags, perrs = sinusoidal.sine_series_sum(
[period, epoch, ampcomps, phacomps],
times,
mags,
errs
)
# resort in original time order
timeind = np.argsort(ptimes)
mtimes = ptimes[timeind]
mmags = modelmags[timeind]
merrs = perrs[timeind]
mphase = phase[timeind]
# return a dict with everything
modeldict = {
'vartype':'sinusoidal',
'params':{x:y for x,y in zip(['period',
'epoch',
'amplitude',
'fourierorder',
'fourieramps',
'fourierphases'],
[period,
epoch,
amplitude,
fourierorder,
ampcomps,
phacomps])},
'times':mtimes,
'mags':mmags,
'errs':merrs,
'phase':mphase,
# these are standard keys that help with later characterization of
# variability as a function period, variability amplitude, object mag,
# ndet, etc.
'varperiod':period,
'varamplitude':amplitude
}
return modeldict | python | {
"resource": ""
} |
q258734 | generate_rrab_lightcurve | validation | def generate_rrab_lightcurve(
times,
mags=None,
errs=None,
paramdists={
'period':sps.uniform(loc=0.45,scale=0.35),
'fourierorder':[8,11],
'amplitude':sps.uniform(loc=0.4,scale=0.5),
'phioffset':np.pi,
},
magsarefluxes=False
):
'''This generates fake RRab light curves.
Parameters
----------
times : np.array
This is an array of time values that will be used as the time base.
mags,errs : np.array
These arrays will have the model added to them. If either is
None, `np.full_like(times, 0.0)` will used as a substitute and the model
light curve will be centered around 0.0.
paramdists : dict
This is a dict containing parameter distributions to use for the
model params, containing the following keys ::
{'period', 'fourierorder', 'amplitude'}
The values of these keys should all be 'frozen' scipy.stats distribution
objects, e.g.:
https://docs.scipy.org/doc/scipy/reference/stats.html#continuous-distributions
The variability epoch will be automatically chosen from a uniform
distribution between `times.min()` and `times.max()`.
The `amplitude` will be flipped automatically as appropriate if
`magsarefluxes=True`.
magsarefluxes : bool
If the generated time series is meant to be a flux time-series, set this
to True to get the correct sign of variability amplitude.
Returns
-------
dict
A dict of the form below is returned::
{'vartype': 'RRab',
'params': {'period': generated value of period,
'epoch': generated value of epoch,
'amplitude': generated value of amplitude,
'fourierorder': generated value of fourier order,
'fourieramps': generated values of fourier amplitudes,
'fourierphases': generated values of fourier phases},
'times': the model times,
'mags': the model mags,
'errs': the model errs,
'varperiod': the generated period of variability == 'period'
'varamplitude': the generated amplitude of
variability == 'amplitude'}
'''
modeldict = generate_sinusoidal_lightcurve(times,
mags=mags,
errs=errs,
paramdists=paramdists,
magsarefluxes=magsarefluxes)
modeldict['vartype'] = 'RRab'
return modeldict | python | {
"resource": ""
} |
q258735 | collection_worker | validation | def collection_worker(task):
'''
This wraps `process_fakelc` for `make_fakelc_collection` below.
Parameters
----------
task : tuple
This is of the form::
task[0] = lcfile
task[1] = outdir
task[2] = magrms
task[3] = dict with keys: {'lcformat', 'timecols', 'magcols',
'errcols', 'randomizeinfo'}
Returns
-------
tuple
This returns a tuple of the form::
(fakelc_fpath,
fakelc_lcdict['columns'],
fakelc_lcdict['objectinfo'],
fakelc_lcdict['moments'])
'''
lcfile, outdir, kwargs = task
try:
fakelcresults = make_fakelc(
lcfile,
outdir,
**kwargs
)
return fakelcresults
except Exception as e:
LOGEXCEPTION('could not process %s into a fakelc' % lcfile)
return None | python | {
"resource": ""
} |
q258736 | add_variability_to_fakelc_collection | validation | def add_variability_to_fakelc_collection(simbasedir,
override_paramdists=None,
overwrite_existingvar=False):
'''This adds variability and noise to all fake LCs in `simbasedir`.
If an object is marked as variable in the `fakelcs-info`.pkl file in
`simbasedir`, a variable signal will be added to its light curve based on
its selected type, default period and amplitude distribution, the
appropriate params, etc. the epochs for each variable object will be chosen
uniformly from its time-range (and may not necessarily fall on a actual
observed time). Nonvariable objects will only have noise added as determined
by their params, but no variable signal will be added.
Parameters
----------
simbasedir : str
The directory containing the fake LCs to process.
override_paramdists : dict
This can be used to override the stored variable parameters in each fake
LC. It should be a dict of the following form::
{'<vartype1>': {'<param1>: a scipy.stats distribution function or
the np.random.randint function,
.
.
.
'<paramN>: a scipy.stats distribution function
or the np.random.randint function}
for any vartype in VARTYPE_LCGEN_MAP. These are used to override the
default parameter distributions for each variable type.
overwrite_existingvar : bool
If this is True, then will overwrite any existing variability in the
input fake LCs in `simbasedir`.
Returns
-------
dict
This returns a dict containing the fake LC filenames as keys and
variability info for each as values.
'''
# open the fakelcs-info.pkl
infof = os.path.join(simbasedir,'fakelcs-info.pkl')
with open(infof, 'rb') as infd:
lcinfo = pickle.load(infd)
lclist = lcinfo['lcfpath']
varflag = lcinfo['isvariable']
vartypes = lcinfo['vartype']
vartind = 0
varinfo = {}
# go through all the LCs and add the required type of variability
for lc, varf, _lcind in zip(lclist, varflag, range(len(lclist))):
# if this object is variable, add variability
if varf:
thisvartype = vartypes[vartind]
if (override_paramdists and
isinstance(override_paramdists, dict) and
thisvartype in override_paramdists and
isinstance(override_paramdists[thisvartype], dict)):
thisoverride_paramdists = override_paramdists[thisvartype]
else:
thisoverride_paramdists = None
varlc = add_fakelc_variability(
lc, thisvartype,
override_paramdists=thisoverride_paramdists,
overwrite=overwrite_existingvar
)
varinfo[varlc['objectid']] = {'params': varlc['actual_varparams'],
'vartype': varlc['actual_vartype']}
# update vartind
vartind = vartind + 1
else:
varlc = add_fakelc_variability(
lc, None,
overwrite=overwrite_existingvar
)
varinfo[varlc['objectid']] = {'params': varlc['actual_varparams'],
'vartype': varlc['actual_vartype']}
#
# done with all objects
#
# write the varinfo back to the dict and fakelcs-info.pkl
lcinfo['varinfo'] = varinfo
tempoutf = '%s.%s' % (infof, md5(npr.bytes(4)).hexdigest()[-8:])
with open(tempoutf, 'wb') as outfd:
pickle.dump(lcinfo, outfd, pickle.HIGHEST_PROTOCOL)
if os.path.exists(tempoutf):
shutil.copy(tempoutf, infof)
os.remove(tempoutf)
else:
LOGEXCEPTION('could not write output light curve file to dir: %s' %
os.path.dirname(tempoutf))
# fail here
raise
return lcinfo | python | {
"resource": ""
} |
q258737 | simple_flare_find | validation | def simple_flare_find(times, mags, errs,
smoothbinsize=97,
flare_minsigma=4.0,
flare_maxcadencediff=1,
flare_mincadencepoints=3,
magsarefluxes=False,
savgol_polyorder=2,
**savgol_kwargs):
'''This finds flares in time series using the method in Walkowicz+ 2011.
FIXME: finish this.
Parameters
----------
times,mags,errs : np.array
The input time-series to find flares in.
smoothbinsize : int
The number of consecutive light curve points to smooth over in the time
series using a Savitsky-Golay filter. The smoothed light curve is then
subtracted from the actual light curve to remove trends that potentially
last `smoothbinsize` light curve points. The default value is chosen as
~6.5 hours (97 x 4 minute cadence for HATNet/HATSouth).
flare_minsigma : float
The minimum sigma above the median LC level to designate points as
belonging to possible flares.
flare_maxcadencediff : int
The maximum number of light curve points apart each possible flare event
measurement is allowed to be. If this is 1, then we'll look for
consecutive measurements.
flare_mincadencepoints : int
The minimum number of light curve points (each `flare_maxcadencediff`
points apart) required that are at least `flare_minsigma` above the
median light curve level to call an event a flare.
magsarefluxes: bool
If True, indicates that mags is actually an array of fluxes.
savgol_polyorder: int
The polynomial order of the function used by the Savitsky-Golay filter.
savgol_kwargs : extra kwargs
Any remaining keyword arguments are passed directly to the
`savgol_filter` function from `scipy.signal`.
Returns
-------
(nflares, flare_indices) : tuple
Returns the total number of flares found and their time-indices (start,
end) as tuples.
'''
# if no errs are given, assume 0.1% errors
if errs is None:
errs = 0.001*mags
# get rid of nans first
finiteind = np.isfinite(times) & np.isfinite(mags) & np.isfinite(errs)
ftimes = times[finiteind]
fmags = mags[finiteind]
ferrs = errs[finiteind]
# now get the smoothed mag series using the filter
# kwargs are provided to the savgol_filter function
smoothed = savgol_filter(fmags,
smoothbinsize,
savgol_polyorder,
**savgol_kwargs)
subtracted = fmags - smoothed
# calculate some stats
# the series_median is ~zero after subtraction
series_mad = np.median(np.abs(subtracted))
series_stdev = 1.483*series_mad
# find extreme positive deviations
if magsarefluxes:
extind = np.where(subtracted > (flare_minsigma*series_stdev))
else:
extind = np.where(subtracted < (-flare_minsigma*series_stdev))
# see if there are any extrema
if extind and extind[0]:
extrema_indices = extind[0]
flaregroups = []
# find the deviations within the requested flaremaxcadencediff
for ind, extrema_index in enumerate(extrema_indices):
# FIXME: finish this
pass | python | {
"resource": ""
} |
q258738 | _get_acf_peakheights | validation | def _get_acf_peakheights(lags, acf, npeaks=20, searchinterval=1):
'''This calculates the relative peak heights for first npeaks in ACF.
Usually, the first peak or the second peak (if its peak height > first peak)
corresponds to the correct lag. When we know the correct lag, the period is
then::
bestperiod = time[lags == bestlag] - time[0]
Parameters
----------
lags : np.array
An array of lags that the ACF is calculated at.
acf : np.array
The array containing the ACF values.
npeaks : int
THe maximum number of peaks to consider when finding peak heights.
searchinterval : int
From `scipy.signal.argrelmax`: "How many points on each side to use for
the comparison to consider comparator(n, n+x) to be True." This
effectively sets how many points on each of the current peak will be
used to check if the current peak is the local maximum.
Returns
-------
dict
This returns a dict of the following form::
{'maxinds':the indices of the lag array where maxes are,
'maxacfs':the ACF values at each max,
'maxlags':the lag values at each max,
'mininds':the indices of the lag array where mins are,
'minacfs':the ACF values at each min,
'minlags':the lag values at each min,
'relpeakheights':the relative peak heights of each rel. ACF peak,
'relpeaklags':the lags at each rel. ACF peak found,
'peakindices':the indices of arrays where each rel. ACF peak is,
'bestlag':the lag value with the largest rel. ACF peak height,
'bestpeakheight':the largest rel. ACF peak height,
'bestpeakindex':the largest rel. ACF peak's number in all peaks}
'''
maxinds = argrelmax(acf, order=searchinterval)[0]
maxacfs = acf[maxinds]
maxlags = lags[maxinds]
mininds = argrelmin(acf, order=searchinterval)[0]
minacfs = acf[mininds]
minlags = lags[mininds]
relpeakheights = npzeros(npeaks)
relpeaklags = npzeros(npeaks,dtype=npint64)
peakindices = npzeros(npeaks,dtype=npint64)
for peakind, mxi in enumerate(maxinds[:npeaks]):
# check if there are no mins to the left
# throw away this peak because it's probably spurious
# (FIXME: is this OK?)
if npall(mxi < mininds):
continue
leftminind = mininds[mininds < mxi][-1] # the last index to the left
rightminind = mininds[mininds > mxi][0] # the first index to the right
relpeakheights[peakind] = (
acf[mxi] - (acf[leftminind] + acf[rightminind])/2.0
)
relpeaklags[peakind] = lags[mxi]
peakindices[peakind] = peakind
# figure out the bestperiod if possible
if relpeakheights[0] > relpeakheights[1]:
bestlag = relpeaklags[0]
bestpeakheight = relpeakheights[0]
bestpeakindex = peakindices[0]
else:
bestlag = relpeaklags[1]
bestpeakheight = relpeakheights[1]
bestpeakindex = peakindices[1]
return {'maxinds':maxinds,
'maxacfs':maxacfs,
'maxlags':maxlags,
'mininds':mininds,
'minacfs':minacfs,
'minlags':minlags,
'relpeakheights':relpeakheights,
'relpeaklags':relpeaklags,
'peakindices':peakindices,
'bestlag':bestlag,
'bestpeakheight':bestpeakheight,
'bestpeakindex':bestpeakindex} | python | {
"resource": ""
} |
q258739 | _autocorr_func1 | validation | def _autocorr_func1(mags, lag, maglen, magmed, magstd):
'''Calculates the autocorr of mag series for specific lag.
This version of the function is taken from: Kim et al. (`2011
<https://dx.doi.org/10.1088/0004-637X/735/2/68>`_)
Parameters
----------
mags : np.array
This is the magnitudes array. MUST NOT have any nans.
lag : float
The specific lag value to calculate the auto-correlation for. This MUST
be less than total number of observations in `mags`.
maglen : int
The number of elements in the `mags` array.
magmed : float
The median of the `mags` array.
magstd : float
The standard deviation of the `mags` array.
Returns
-------
float
The auto-correlation at this specific `lag` value.
'''
lagindex = nparange(1,maglen-lag)
products = (mags[lagindex] - magmed) * (mags[lagindex+lag] - magmed)
acorr = (1.0/((maglen - lag)*magstd)) * npsum(products)
return acorr | python | {
"resource": ""
} |
q258740 | _autocorr_func2 | validation | def _autocorr_func2(mags, lag, maglen, magmed, magstd):
'''
This is an alternative function to calculate the autocorrelation.
This version is from (first definition):
https://en.wikipedia.org/wiki/Correlogram#Estimation_of_autocorrelations
Parameters
----------
mags : np.array
This is the magnitudes array. MUST NOT have any nans.
lag : float
The specific lag value to calculate the auto-correlation for. This MUST
be less than total number of observations in `mags`.
maglen : int
The number of elements in the `mags` array.
magmed : float
The median of the `mags` array.
magstd : float
The standard deviation of the `mags` array.
Returns
-------
float
The auto-correlation at this specific `lag` value.
'''
lagindex = nparange(0,maglen-lag)
products = (mags[lagindex] - magmed) * (mags[lagindex+lag] - magmed)
autocovarfunc = npsum(products)/lagindex.size
varfunc = npsum(
(mags[lagindex] - magmed)*(mags[lagindex] - magmed)
)/mags.size
acorr = autocovarfunc/varfunc
return acorr | python | {
"resource": ""
} |
q258741 | _autocorr_func3 | validation | def _autocorr_func3(mags, lag, maglen, magmed, magstd):
'''
This is yet another alternative to calculate the autocorrelation.
Taken from: `Bayesian Methods for Hackers by Cameron Pilon <http://nbviewer.jupyter.org/github/CamDavidsonPilon/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers/blob/master/Chapter3_MCMC/Chapter3.ipynb#Autocorrelation>`_
(This should be the fastest method to calculate ACFs.)
Parameters
----------
mags : np.array
This is the magnitudes array. MUST NOT have any nans.
lag : float
The specific lag value to calculate the auto-correlation for. This MUST
be less than total number of observations in `mags`.
maglen : int
The number of elements in the `mags` array.
magmed : float
The median of the `mags` array.
magstd : float
The standard deviation of the `mags` array.
Returns
-------
float
The auto-correlation at this specific `lag` value.
'''
# from http://tinyurl.com/afz57c4
result = npcorrelate(mags, mags, mode='full')
result = result / npmax(result)
return result[int(result.size / 2):] | python | {
"resource": ""
} |
q258742 | autocorr_magseries | validation | def autocorr_magseries(times, mags, errs,
maxlags=1000,
func=_autocorr_func3,
fillgaps=0.0,
filterwindow=11,
forcetimebin=None,
sigclip=3.0,
magsarefluxes=False,
verbose=True):
'''This calculates the ACF of a light curve.
This will pre-process the light curve to fill in all the gaps and normalize
everything to zero. If `fillgaps = 'noiselevel'`, fills the gaps with the
noise level obtained via the procedure above. If `fillgaps = 'nan'`, fills
the gaps with `np.nan`.
Parameters
----------
times,mags,errs : np.array
The measurement time-series and associated errors.
maxlags : int
The maximum number of lags to calculate.
func : Python function
This is a function to calculate the lags.
fillgaps : 'noiselevel' or float
This sets what to use to fill in gaps in the time series. If this is
'noiselevel', will smooth the light curve using a point window size of
`filterwindow` (this should be an odd integer), subtract the smoothed LC
from the actual LC and estimate the RMS. This RMS will be used to fill
in the gaps. Other useful values here are 0.0, and npnan.
filterwindow : int
The light curve's smoothing filter window size to use if
`fillgaps='noiselevel`'.
forcetimebin : None or float
This is used to force a particular cadence in the light curve other than
the automatically determined cadence. This effectively rebins the light
curve to this cadence. This should be in the same time units as `times`.
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 your input measurements in `mags` are actually fluxes instead of
mags, set this is True.
verbose : bool
If True, will indicate progress and report errors.
Returns
-------
dict
A dict of the following form is returned::
{'itimes': the interpolated time values after gap-filling,
'imags': the interpolated mag/flux values after gap-filling,
'ierrs': the interpolated mag/flux values after gap-filling,
'cadence': the cadence of the output mag/flux time-series,
'minitime': the minimum value of the interpolated times array,
'lags': the lags used to calculate the auto-correlation function,
'acf': the value of the ACF at each lag used}
'''
# get the gap-filled timeseries
interpolated = fill_magseries_gaps(times, mags, errs,
fillgaps=fillgaps,
forcetimebin=forcetimebin,
sigclip=sigclip,
magsarefluxes=magsarefluxes,
filterwindow=filterwindow,
verbose=verbose)
if not interpolated:
print('failed to interpolate light curve to minimum cadence!')
return None
itimes, imags = interpolated['itimes'], interpolated['imags'],
# calculate the lags up to maxlags
if maxlags:
lags = nparange(0, maxlags)
else:
lags = nparange(itimes.size)
series_stdev = 1.483*npmedian(npabs(imags))
if func != _autocorr_func3:
# get the autocorrelation as a function of the lag of the mag series
autocorr = nparray([func(imags, x, imags.size, 0.0, series_stdev)
for x in lags])
# this doesn't need a lags array
else:
autocorr = _autocorr_func3(imags, lags[0], imags.size,
0.0, series_stdev)
# return only the maximum number of lags
if maxlags is not None:
autocorr = autocorr[:maxlags]
interpolated.update({'minitime':itimes.min(),
'lags':lags,
'acf':autocorr})
return interpolated | python | {
"resource": ""
} |
q258743 | aovhm_theta | validation | def aovhm_theta(times, mags, errs, frequency,
nharmonics, magvariance):
'''This calculates the harmonic AoV theta statistic for a frequency.
This is a mostly faithful translation of the inner loop in `aovper.f90`. See
the following for details:
- http://users.camk.edu.pl/alex/
- Schwarzenberg-Czerny (`1996
<http://iopscience.iop.org/article/10.1086/309985/meta>`_)
Schwarzenberg-Czerny (1996) equation 11::
theta_prefactor = (K - 2N - 1)/(2N)
theta_top = sum(c_n*c_n) (from n=0 to n=2N)
theta_bot = variance(timeseries) - sum(c_n*c_n) (from n=0 to n=2N)
theta = theta_prefactor * (theta_top/theta_bot)
N = number of harmonics (nharmonics)
K = length of time series (times.size)
Parameters
----------
times,mags,errs : np.array
The input time-series to calculate the test statistic for. These should
all be of nans/infs and be normalized to zero.
frequency : float
The test frequency to calculate the statistic for.
nharmonics : int
The number of harmonics to calculate up to.The recommended range is 4 to
8.
magvariance : float
This is the (weighted by errors) variance of the magnitude time
series. We provide it as a pre-calculated value here so we don't have to
re-calculate it for every worker.
Returns
-------
aov_harmonic_theta : float
THe value of the harmonic AoV theta for the specified test `frequency`.
'''
period = 1.0/frequency
ndet = times.size
two_nharmonics = nharmonics + nharmonics
# phase with test period
phasedseries = phase_magseries_with_errs(
times, mags, errs, period, times[0],
sort=True, wrap=False
)
# get the phased quantities
phase = phasedseries['phase']
pmags = phasedseries['mags']
perrs = phasedseries['errs']
# this is sqrt(1.0/errs^2) -> the weights
pweights = 1.0/perrs
# multiply by 2.0*PI (for omega*time)
phase = phase * 2.0 * pi_value
# this is the z complex vector
z = npcos(phase) + 1.0j*npsin(phase)
# multiply phase with N
phase = nharmonics * phase
# this is the psi complex vector
psi = pmags * pweights * (npcos(phase) + 1j*npsin(phase))
# this is the initial value of z^n
zn = 1.0 + 0.0j
# this is the initial value of phi
phi = pweights + 0.0j
# initialize theta to zero
theta_aov = 0.0
# go through all the harmonics now up to 2N
for _ in range(two_nharmonics):
# this is <phi, phi>
phi_dot_phi = npsum(phi * phi.conjugate())
# this is the alpha_n numerator
alpha = npsum(pweights * z * phi)
# this is <phi, psi>. make sure to use npvdot and NOT npdot to get
# complex conjugate of first vector as expected for complex vectors
phi_dot_psi = npvdot(phi, psi)
# make sure phi_dot_phi is not zero
phi_dot_phi = npmax([phi_dot_phi, 10.0e-9])
# this is the expression for alpha_n
alpha = alpha / phi_dot_phi
# update theta_aov for this harmonic
theta_aov = (theta_aov +
npabs(phi_dot_psi) * npabs(phi_dot_psi) / phi_dot_phi)
# use the recurrence relation to find the next phi
phi = phi * z - alpha * zn * phi.conjugate()
# update z^n
zn = zn * z
# done with all harmonics, calculate the theta_aov for this freq
# the max below makes sure that magvariance - theta_aov > zero
theta_aov = ( (ndet - two_nharmonics - 1.0) * theta_aov /
(two_nharmonics * npmax([magvariance - theta_aov,
1.0e-9])) )
return theta_aov | python | {
"resource": ""
} |
q258744 | LCDB.open | validation | def open(self, database, user, password, host):
'''This opens a new database connection.
Parameters
----------
database : str
Name of the database to connect to.
user : str
User name of the database server user.
password : str
Password for the database server user.
host : str
Database hostname or IP address to connect to.
'''
try:
self.connection = pg.connect(user=user,
password=password,
database=database,
host=host)
LOGINFO('postgres connection successfully '
'created, using DB %s, user %s' % (database,
user))
self.database = database
self.user = user
except Exception as e:
LOGEXCEPTION('postgres connection failed, '
'using DB %s, user %s' % (database,
user))
self.database = None
self.user = None | python | {
"resource": ""
} |
q258745 | LCDB.autocommit | validation | def autocommit(self):
'''
This sets the database connection to autocommit. Must be called before
any cursors have been instantiated.
'''
if len(self.cursors.keys()) == 0:
self.connection.autocommit = True
else:
raise AttributeError('database cursors are already active, '
'cannot switch to autocommit now') | python | {
"resource": ""
} |
q258746 | LCDB.cursor | validation | def cursor(self, handle, dictcursor=False):
'''This gets or creates a DB cursor for the current DB connection.
Parameters
----------
handle : str
The name of the cursor to look up in the existing list or if it
doesn't exist, the name to be used for a new cursor to be returned.
dictcursor : bool
If True, returns a cursor where each returned row can be addressed
as a dictionary by column name.
Returns
-------
psycopg2.Cursor instance
'''
if handle in self.cursors:
return self.cursors[handle]
else:
if dictcursor:
self.cursors[handle] = self.connection.cursor(
cursor_factory=psycopg2.extras.DictCursor
)
else:
self.cursors[handle] = self.connection.cursor()
return self.cursors[handle] | python | {
"resource": ""
} |
q258747 | LCDB.newcursor | validation | def newcursor(self, dictcursor=False):
'''
This creates a DB cursor for the current DB connection using a
randomly generated handle. Returns a tuple with cursor and handle.
Parameters
----------
dictcursor : bool
If True, returns a cursor where each returned row can be addressed
as a dictionary by column name.
Returns
-------
tuple
The tuple is of the form (handle, psycopg2.Cursor instance).
'''
handle = hashlib.sha256(os.urandom(12)).hexdigest()
if dictcursor:
self.cursors[handle] = self.connection.cursor(
cursor_factory=psycopg2.extras.DictCursor
)
else:
self.cursors[handle] = self.connection.cursor()
return (self.cursors[handle], handle) | python | {
"resource": ""
} |
q258748 | LCDB.close_cursor | validation | def close_cursor(self, handle):
'''
Closes the cursor specified and removes it from the `self.cursors`
dictionary.
'''
if handle in self.cursors:
self.cursors[handle].close()
else:
raise KeyError('cursor with handle %s was not found' % handle) | python | {
"resource": ""
} |
q258749 | trapezoid_transit_func | validation | def trapezoid_transit_func(transitparams, times, mags, errs,
get_ntransitpoints=False):
'''This returns a trapezoid transit-shaped function.
Suitable for first order modeling of transit signals.
Parameters
----------
transitparams : list of float
This contains the transiting planet trapezoid model::
transitparams = [transitperiod (time),
transitepoch (time),
transitdepth (flux or mags),
transitduration (phase),
ingressduration (phase)]
All of these will then have fitted values after the fit is done.
- for magnitudes -> `transitdepth` should be < 0
- for fluxes -> `transitdepth` should be > 0
times,mags,errs : np.array
The input time-series of measurements and associated errors for which
the transit model will be generated. The times will be used to generate
model mags, and the input `times`, `mags`, and `errs` will be resorted
by model phase and returned.
Returns
-------
(modelmags, phase, ptimes, pmags, perrs) : tuple
Returns the model mags and phase values. Also returns the input `times`,
`mags`, and `errs` sorted by the model's phase.
'''
(transitperiod,
transitepoch,
transitdepth,
transitduration,
ingressduration) = transitparams
# generate the phases
iphase = (times - transitepoch)/transitperiod
iphase = iphase - np.floor(iphase)
phasesortind = np.argsort(iphase)
phase = iphase[phasesortind]
ptimes = times[phasesortind]
pmags = mags[phasesortind]
perrs = errs[phasesortind]
zerolevel = np.median(pmags)
modelmags = np.full_like(phase, zerolevel)
halftransitduration = transitduration/2.0
bottomlevel = zerolevel - transitdepth
slope = transitdepth/ingressduration
# the four contact points of the eclipse
firstcontact = 1.0 - halftransitduration
secondcontact = firstcontact + ingressduration
thirdcontact = halftransitduration - ingressduration
fourthcontact = halftransitduration
## the phase indices ##
# during ingress
ingressind = (phase > firstcontact) & (phase < secondcontact)
# at transit bottom
bottomind = (phase > secondcontact) | (phase < thirdcontact)
# during egress
egressind = (phase > thirdcontact) & (phase < fourthcontact)
# count the number of points in transit
in_transit_points = ingressind | bottomind | egressind
n_transit_points = np.sum(in_transit_points)
# set the mags
modelmags[ingressind] = zerolevel - slope*(phase[ingressind] - firstcontact)
modelmags[bottomind] = bottomlevel
modelmags[egressind] = bottomlevel + slope*(phase[egressind] - thirdcontact)
if get_ntransitpoints:
return modelmags, phase, ptimes, pmags, perrs, n_transit_points
else:
return modelmags, phase, ptimes, pmags, perrs | python | {
"resource": ""
} |
q258750 | xmatch_cplist_external_catalogs | validation | def xmatch_cplist_external_catalogs(cplist,
xmatchpkl,
xmatchradiusarcsec=2.0,
updateexisting=True,
resultstodir=None):
'''This xmatches external catalogs to a collection of checkplots.
Parameters
----------
cplist : list of str
This is the list of checkplot pickle files to process.
xmatchpkl : str
The filename of a pickle prepared beforehand with the
`checkplot.pkl_xmatch.load_xmatch_external_catalogs` function,
containing collected external catalogs to cross-match the objects in the
input `cplist` against.
xmatchradiusarcsec : float
The match radius to use for the cross-match in arcseconds.
updateexisting : bool
If this is True, will only update the `xmatch` dict in each checkplot
pickle with any new cross-matches to the external catalogs. If False,
will overwrite the `xmatch` dict with results from the current run.
resultstodir : str or None
If this is provided, then it must be a directory to write the resulting
checkplots to after xmatch is done. This can be used to keep the
original checkplots in pristine condition for some reason.
Returns
-------
dict
Returns a dict with keys = input checkplot pickle filenames and vals =
xmatch status dict for each checkplot pickle.
'''
# load the external catalog
with open(xmatchpkl,'rb') as infd:
xmd = pickle.load(infd)
# match each object. this is fairly fast, so this is not parallelized at the
# moment
status_dict = {}
for cpf in cplist:
cpd = _read_checkplot_picklefile(cpf)
try:
# match in place
xmatch_external_catalogs(cpd, xmd,
xmatchradiusarcsec=xmatchradiusarcsec,
updatexmatch=updateexisting)
for xmi in cpd['xmatch']:
if cpd['xmatch'][xmi]['found']:
LOGINFO('checkplot %s: %s matched to %s, '
'match dist: %s arcsec' %
(os.path.basename(cpf),
cpd['objectid'],
cpd['xmatch'][xmi]['name'],
cpd['xmatch'][xmi]['distarcsec']))
if not resultstodir:
outcpf = _write_checkplot_picklefile(cpd,
outfile=cpf)
else:
xcpf = os.path.join(resultstodir, os.path.basename(cpf))
outcpf = _write_checkplot_picklefile(cpd,
outfile=xcpf)
status_dict[cpf] = outcpf
except Exception as e:
LOGEXCEPTION('failed to match objects for %s' % cpf)
status_dict[cpf] = None
return status_dict | python | {
"resource": ""
} |
q258751 | xmatch_cpdir_external_catalogs | validation | def xmatch_cpdir_external_catalogs(cpdir,
xmatchpkl,
cpfileglob='checkplot-*.pkl*',
xmatchradiusarcsec=2.0,
updateexisting=True,
resultstodir=None):
'''This xmatches external catalogs to all checkplots in a directory.
Parameters
-----------
cpdir : str
This is the directory to search in for checkplots.
xmatchpkl : str
The filename of a pickle prepared beforehand with the
`checkplot.pkl_xmatch.load_xmatch_external_catalogs` function,
containing collected external catalogs to cross-match the objects in the
input `cplist` against.
cpfileglob : str
This is the UNIX fileglob to use in searching for checkplots.
xmatchradiusarcsec : float
The match radius to use for the cross-match in arcseconds.
updateexisting : bool
If this is True, will only update the `xmatch` dict in each checkplot
pickle with any new cross-matches to the external catalogs. If False,
will overwrite the `xmatch` dict with results from the current run.
resultstodir : str or None
If this is provided, then it must be a directory to write the resulting
checkplots to after xmatch is done. This can be used to keep the
original checkplots in pristine condition for some reason.
Returns
-------
dict
Returns a dict with keys = input checkplot pickle filenames and vals =
xmatch status dict for each checkplot pickle.
'''
cplist = glob.glob(os.path.join(cpdir, cpfileglob))
return xmatch_cplist_external_catalogs(
cplist,
xmatchpkl,
xmatchradiusarcsec=xmatchradiusarcsec,
updateexisting=updateexisting,
resultstodir=resultstodir
) | python | {
"resource": ""
} |
q258752 | colormagdiagram_cplist | validation | def colormagdiagram_cplist(cplist,
outpkl,
color_mag1=['gaiamag','sdssg'],
color_mag2=['kmag','kmag'],
yaxis_mag=['gaia_absmag','rpmj']):
'''This makes color-mag diagrams for all checkplot pickles in the provided
list.
Can make an arbitrary number of CMDs given lists of x-axis colors and y-axis
mags to use.
Parameters
----------
cplist : list of str
This is the list of checkplot pickles to process.
outpkl : str
The filename of the output pickle that will contain the color-mag
information for all objects in the checkplots specified in `cplist`.
color_mag1 : list of str
This a list of the keys in each checkplot's `objectinfo` dict that will
be used as color_1 in the equation::
x-axis color = color_mag1 - color_mag2
color_mag2 : list of str
This a list of the keys in each checkplot's `objectinfo` dict that will
be used as color_2 in the equation::
x-axis color = color_mag1 - color_mag2
yaxis_mag : list of str
This is a list of the keys in each checkplot's `objectinfo` dict that
will be used as the (absolute) magnitude y-axis of the color-mag
diagrams.
Returns
-------
str
The path to the generated CMD pickle file for the collection of objects
in the input checkplot list.
Notes
-----
This can make many CMDs in one go. For example, the default kwargs for
`color_mag`, `color_mag2`, and `yaxis_mag` result in two CMDs generated and
written to the output pickle file:
- CMD1 -> gaiamag - kmag on the x-axis vs gaia_absmag on the y-axis
- CMD2 -> sdssg - kmag on the x-axis vs rpmj (J reduced PM) on the y-axis
'''
# first, we'll collect all of the info
cplist_objectids = []
cplist_mags = []
cplist_colors = []
for cpf in cplist:
cpd = _read_checkplot_picklefile(cpf)
cplist_objectids.append(cpd['objectid'])
thiscp_mags = []
thiscp_colors = []
for cm1, cm2, ym in zip(color_mag1, color_mag2, yaxis_mag):
if (ym in cpd['objectinfo'] and
cpd['objectinfo'][ym] is not None):
thiscp_mags.append(cpd['objectinfo'][ym])
else:
thiscp_mags.append(np.nan)
if (cm1 in cpd['objectinfo'] and
cpd['objectinfo'][cm1] is not None and
cm2 in cpd['objectinfo'] and
cpd['objectinfo'][cm2] is not None):
thiscp_colors.append(cpd['objectinfo'][cm1] -
cpd['objectinfo'][cm2])
else:
thiscp_colors.append(np.nan)
cplist_mags.append(thiscp_mags)
cplist_colors.append(thiscp_colors)
# convert these to arrays
cplist_objectids = np.array(cplist_objectids)
cplist_mags = np.array(cplist_mags)
cplist_colors = np.array(cplist_colors)
# prepare the outdict
cmddict = {'objectids':cplist_objectids,
'mags':cplist_mags,
'colors':cplist_colors,
'color_mag1':color_mag1,
'color_mag2':color_mag2,
'yaxis_mag':yaxis_mag}
# save the pickled figure and dict for fast retrieval later
with open(outpkl,'wb') as outfd:
pickle.dump(cmddict, outfd, pickle.HIGHEST_PROTOCOL)
plt.close('all')
return cmddict | python | {
"resource": ""
} |
q258753 | colormagdiagram_cpdir | validation | def colormagdiagram_cpdir(
cpdir,
outpkl,
cpfileglob='checkplot*.pkl*',
color_mag1=['gaiamag','sdssg'],
color_mag2=['kmag','kmag'],
yaxis_mag=['gaia_absmag','rpmj']
):
'''This makes CMDs for all checkplot pickles in the provided directory.
Can make an arbitrary number of CMDs given lists of x-axis colors and y-axis
mags to use.
Parameters
----------
cpdir : list of str
This is the directory to get the list of input checkplot pickles from.
outpkl : str
The filename of the output pickle that will contain the color-mag
information for all objects in the checkplots specified in `cplist`.
cpfileglob : str
The UNIX fileglob to use to search for checkplot pickle files.
color_mag1 : list of str
This a list of the keys in each checkplot's `objectinfo` dict that will
be used as color_1 in the equation::
x-axis color = color_mag1 - color_mag2
color_mag2 : list of str
This a list of the keys in each checkplot's `objectinfo` dict that will
be used as color_2 in the equation::
x-axis color = color_mag1 - color_mag2
yaxis_mag : list of str
This is a list of the keys in each checkplot's `objectinfo` dict that
will be used as the (absolute) magnitude y-axis of the color-mag
diagrams.
Returns
-------
str
The path to the generated CMD pickle file for the collection of objects
in the input checkplot directory.
Notes
-----
This can make many CMDs in one go. For example, the default kwargs for
`color_mag`, `color_mag2`, and `yaxis_mag` result in two CMDs generated and
written to the output pickle file:
- CMD1 -> gaiamag - kmag on the x-axis vs gaia_absmag on the y-axis
- CMD2 -> sdssg - kmag on the x-axis vs rpmj (J reduced PM) on the y-axis
'''
cplist = glob.glob(os.path.join(cpdir, cpfileglob))
return colormagdiagram_cplist(cplist,
outpkl,
color_mag1=color_mag1,
color_mag2=color_mag2,
yaxis_mag=yaxis_mag) | python | {
"resource": ""
} |
q258754 | add_cmds_cplist | validation | def add_cmds_cplist(cplist, cmdpkl,
require_cmd_magcolor=True,
save_cmd_pngs=False):
'''This adds CMDs for each object in cplist.
Parameters
----------
cplist : list of str
This is the input list of checkplot pickles to add the CMDs to.
cmdpkl : str
This is the filename of the CMD pickle created previously.
require_cmd_magcolor : bool
If this is True, a CMD plot will not be made if the color and mag keys
required by the CMD are not present or are nan in each checkplot's
objectinfo dict.
save_cmd_pngs : bool
If this is True, then will save the CMD plots that were generated and
added back to the checkplotdict as PNGs to the same directory as
`cpx`.
Returns
-------
Nothing.
'''
# load the CMD first to save on IO
with open(cmdpkl,'rb') as infd:
cmd = pickle.load(infd)
for cpf in cplist:
add_cmd_to_checkplot(cpf, cmd,
require_cmd_magcolor=require_cmd_magcolor,
save_cmd_pngs=save_cmd_pngs) | python | {
"resource": ""
} |
q258755 | add_cmds_cpdir | validation | def add_cmds_cpdir(cpdir,
cmdpkl,
cpfileglob='checkplot*.pkl*',
require_cmd_magcolor=True,
save_cmd_pngs=False):
'''This adds CMDs for each object in cpdir.
Parameters
----------
cpdir : list of str
This is the directory to search for checkplot pickles.
cmdpkl : str
This is the filename of the CMD pickle created previously.
cpfileglob : str
The UNIX fileglob to use when searching for checkplot pickles to operate
on.
require_cmd_magcolor : bool
If this is True, a CMD plot will not be made if the color and mag keys
required by the CMD are not present or are nan in each checkplot's
objectinfo dict.
save_cmd_pngs : bool
If this is True, then will save the CMD plots that were generated and
added back to the checkplotdict as PNGs to the same directory as
`cpx`.
Returns
-------
Nothing.
'''
cplist = glob.glob(os.path.join(cpdir, cpfileglob))
return add_cmds_cplist(cplist,
cmdpkl,
require_cmd_magcolor=require_cmd_magcolor,
save_cmd_pngs=save_cmd_pngs) | python | {
"resource": ""
} |
q258756 | cp_objectinfo_worker | validation | def cp_objectinfo_worker(task):
'''This is a parallel worker for `parallel_update_cp_objectinfo`.
Parameters
----------
task : tuple
- task[0] = checkplot pickle file
- task[1] = kwargs
Returns
-------
str
The name of the checkplot file that was updated. None if the update
fails for some reason.
'''
cpf, cpkwargs = task
try:
newcpf = update_checkplot_objectinfo(cpf, **cpkwargs)
return newcpf
except Exception as e:
LOGEXCEPTION('failed to update objectinfo for %s' % cpf)
return None | python | {
"resource": ""
} |
q258757 | parallel_update_objectinfo_cplist | validation | def parallel_update_objectinfo_cplist(
cplist,
liststartindex=None,
maxobjects=None,
nworkers=NCPUS,
fast_mode=False,
findercmap='gray_r',
finderconvolve=None,
deredden_object=True,
custom_bandpasses=None,
gaia_submit_timeout=10.0,
gaia_submit_tries=3,
gaia_max_timeout=180.0,
gaia_mirror=None,
complete_query_later=True,
lclistpkl=None,
nbrradiusarcsec=60.0,
maxnumneighbors=5,
plotdpi=100,
findercachedir='~/.astrobase/stamp-cache',
verbose=True
):
'''
This updates objectinfo for a list of checkplots.
Useful in cases where a previous round of GAIA/finderchart/external catalog
acquisition failed. This will preserve the following keys in the checkplots
if they exist:
comments
varinfo
objectinfo.objecttags
Parameters
----------
cplist : list of str
A list of checkplot pickle file names to update.
liststartindex : int
The index of the input list to start working at.
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 checkplot pickles over several sessions or machines.
nworkers : int
The number of parallel workers that will work on the checkplot
update process.
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. See the docstring for
`checkplot.pkl_utils._pkl_finder_objectinfo` for details on how this
works. If this is True, will run in "fast" mode with default timeouts (5
seconds in most cases). If this is a float, will run in "fast" mode with
the provided timeout value in seconds.
findercmap : str or matplotlib.cm.Colormap object
findercmap : str or matplotlib.cm.ColorMap object
The Colormap object to use for the finder chart image.
finderconvolve : astropy.convolution.Kernel object or None
If not None, the Kernel object to use for convolving the finder image.
deredden_objects : bool
If this is True, will use the 2MASS DUST service to get extinction
coefficients in various bands, and then try to deredden the magnitudes
and colors of the object already present in the checkplot's objectinfo
dict.
custom_bandpasses : dict
This is a dict used to provide custom bandpass definitions for any
magnitude measurements in the objectinfo dict that are not automatically
recognized by the `varclass.starfeatures.color_features` function. See
its docstring for details on the required format.
gaia_submit_timeout : float
Sets the timeout in seconds to use when submitting a request to look up
the object's information to the GAIA service. Note that if `fast_mode`
is set, this is ignored.
gaia_submit_tries : int
Sets the maximum number of times the GAIA services will be contacted to
obtain this object's information. If `fast_mode` is set, this is
ignored, and the services will be contacted only once (meaning that a
failure to respond will be silently ignored and no GAIA data will be
added to the checkplot's objectinfo dict).
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
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.
complete_query_later : bool
If this is True, saves the state of GAIA queries that are not yet
complete when `gaia_max_timeout` is reached while waiting for the GAIA
service to respond to our request. A later call for GAIA info on the
same object will attempt to pick up the results from the existing query
if it's completed. If `fast_mode` is True, this is ignored.
lclistpkl : dict or str
If this is provided, must be a dict resulting from reading a catalog
produced by the `lcproc.catalogs.make_lclist` function or a str path
pointing to the pickle file produced by that function. This catalog is
used to find neighbors of the current object in the current light curve
collection. Looking at neighbors of the object within the radius
specified by `nbrradiusarcsec` is useful for light curves produced by
instruments that have a large pixel scale, so are susceptible to
blending of variability and potential confusion of neighbor variability
with that of the actual object being looked at. If this is None, no
neighbor lookups will be performed.
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.
plotdpi : int
The resolution in DPI of the plots to generate in this function
(e.g. the finder chart, etc.)
findercachedir : str
The path to the astrobase cache directory for finder chart downloads
from the NASA SkyView service.
verbose : bool
If True, will indicate progress and warn about potential problems.
Returns
-------
list of str
Paths to the updated checkplot pickle file.
'''
# work around the Darwin segfault after fork if no network activity in
# main thread bug: https://bugs.python.org/issue30385#msg293958
if sys.platform == 'darwin':
import requests
requests.get('http://captive.apple.com/hotspot-detect.html')
# handle the start and end indices
if (liststartindex is not None) and (maxobjects is None):
cplist = cplist[liststartindex:]
elif (liststartindex is None) and (maxobjects is not None):
cplist = cplist[:maxobjects]
elif (liststartindex is not None) and (maxobjects is not None):
cplist = (
cplist[liststartindex:liststartindex+maxobjects]
)
tasks = [(x, {'fast_mode':fast_mode,
'findercmap':findercmap,
'finderconvolve':finderconvolve,
'deredden_object':deredden_object,
'custom_bandpasses':custom_bandpasses,
'gaia_submit_timeout':gaia_submit_timeout,
'gaia_submit_tries':gaia_submit_tries,
'gaia_max_timeout':gaia_max_timeout,
'gaia_mirror':gaia_mirror,
'complete_query_later':complete_query_later,
'lclistpkl':lclistpkl,
'nbrradiusarcsec':nbrradiusarcsec,
'maxnumneighbors':maxnumneighbors,
'plotdpi':plotdpi,
'findercachedir':findercachedir,
'verbose':verbose}) for x in cplist]
resultfutures = []
results = []
with ProcessPoolExecutor(max_workers=nworkers) as executor:
resultfutures = executor.map(cp_objectinfo_worker, tasks)
results = [x for x in resultfutures]
executor.shutdown()
return results | python | {
"resource": ""
} |
q258758 | parallel_update_objectinfo_cpdir | validation | def parallel_update_objectinfo_cpdir(cpdir,
cpglob='checkplot-*.pkl*',
liststartindex=None,
maxobjects=None,
nworkers=NCPUS,
fast_mode=False,
findercmap='gray_r',
finderconvolve=None,
deredden_object=True,
custom_bandpasses=None,
gaia_submit_timeout=10.0,
gaia_submit_tries=3,
gaia_max_timeout=180.0,
gaia_mirror=None,
complete_query_later=True,
lclistpkl=None,
nbrradiusarcsec=60.0,
maxnumneighbors=5,
plotdpi=100,
findercachedir='~/.astrobase/stamp-cache',
verbose=True):
'''This updates the objectinfo for a directory of checkplot pickles.
Useful in cases where a previous round of GAIA/finderchart/external catalog
acquisition failed. This will preserve the following keys in the checkplots
if they exist:
comments
varinfo
objectinfo.objecttags
Parameters
----------
cpdir : str
The directory to look for checkplot pickles in.
cpglob : str
The UNIX fileglob to use when searching for checkplot pickle files.
liststartindex : int
The index of the input list to start working at.
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 checkplot pickles over several sessions or machines.
nworkers : int
The number of parallel workers that will work on the checkplot
update process.
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. See the docstring for
`checkplot.pkl_utils._pkl_finder_objectinfo` for details on how this
works. If this is True, will run in "fast" mode with default timeouts (5
seconds in most cases). If this is a float, will run in "fast" mode with
the provided timeout value in seconds.
findercmap : str or matplotlib.cm.Colormap object
findercmap : str or matplotlib.cm.ColorMap object
The Colormap object to use for the finder chart image.
finderconvolve : astropy.convolution.Kernel object or None
If not None, the Kernel object to use for convolving the finder image.
deredden_objects : bool
If this is True, will use the 2MASS DUST service to get extinction
coefficients in various bands, and then try to deredden the magnitudes
and colors of the object already present in the checkplot's objectinfo
dict.
custom_bandpasses : dict
This is a dict used to provide custom bandpass definitions for any
magnitude measurements in the objectinfo dict that are not automatically
recognized by the `varclass.starfeatures.color_features` function. See
its docstring for details on the required format.
gaia_submit_timeout : float
Sets the timeout in seconds to use when submitting a request to look up
the object's information to the GAIA service. Note that if `fast_mode`
is set, this is ignored.
gaia_submit_tries : int
Sets the maximum number of times the GAIA services will be contacted to
obtain this object's information. If `fast_mode` is set, this is
ignored, and the services will be contacted only once (meaning that a
failure to respond will be silently ignored and no GAIA data will be
added to the checkplot's objectinfo dict).
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
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.
complete_query_later : bool
If this is True, saves the state of GAIA queries that are not yet
complete when `gaia_max_timeout` is reached while waiting for the GAIA
service to respond to our request. A later call for GAIA info on the
same object will attempt to pick up the results from the existing query
if it's completed. If `fast_mode` is True, this is ignored.
lclistpkl : dict or str
If this is provided, must be a dict resulting from reading a catalog
produced by the `lcproc.catalogs.make_lclist` function or a str path
pointing to the pickle file produced by that function. This catalog is
used to find neighbors of the current object in the current light curve
collection. Looking at neighbors of the object within the radius
specified by `nbrradiusarcsec` is useful for light curves produced by
instruments that have a large pixel scale, so are susceptible to
blending of variability and potential confusion of neighbor variability
with that of the actual object being looked at. If this is None, no
neighbor lookups will be performed.
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.
plotdpi : int
The resolution in DPI of the plots to generate in this function
(e.g. the finder chart, etc.)
findercachedir : str
The path to the astrobase cache directory for finder chart downloads
from the NASA SkyView service.
verbose : bool
If True, will indicate progress and warn about potential problems.
Returns
-------
list of str
Paths to the updated checkplot pickle file.
'''
cplist = sorted(glob.glob(os.path.join(cpdir, cpglob)))
return parallel_update_objectinfo_cplist(
cplist,
liststartindex=liststartindex,
maxobjects=maxobjects,
nworkers=nworkers,
fast_mode=fast_mode,
findercmap=findercmap,
finderconvolve=finderconvolve,
deredden_object=deredden_object,
custom_bandpasses=custom_bandpasses,
gaia_submit_timeout=gaia_submit_timeout,
gaia_submit_tries=gaia_submit_tries,
gaia_max_timeout=gaia_max_timeout,
gaia_mirror=gaia_mirror,
complete_query_later=complete_query_later,
lclistpkl=lclistpkl,
nbrradiusarcsec=nbrradiusarcsec,
maxnumneighbors=maxnumneighbors,
plotdpi=plotdpi,
findercachedir=findercachedir,
verbose=verbose
) | python | {
"resource": ""
} |
q258759 | checkplot_infokey_worker | validation | def checkplot_infokey_worker(task):
'''This gets the required keys from the requested file.
Parameters
----------
task : tuple
Task is a two element tuple::
- task[0] is the dict to work on
- task[1] is a list of lists of str indicating all the key address to
extract items from the dict for
Returns
-------
list
This is a list of all of the items at the requested key addresses.
'''
cpf, keys = task
cpd = _read_checkplot_picklefile(cpf)
resultkeys = []
for k in keys:
try:
resultkeys.append(_dict_get(cpd, k))
except Exception as e:
resultkeys.append(np.nan)
return resultkeys | python | {
"resource": ""
} |
q258760 | _gaussian | validation | def _gaussian(x, amp, loc, std):
'''This is a simple gaussian.
Parameters
----------
x : np.array
The items at which the Gaussian is evaluated.
amp : float
The amplitude of the Gaussian.
loc : float
The central value of the Gaussian.
std : float
The standard deviation of the Gaussian.
Returns
-------
np.array
Returns the Gaussian evaluated at the items in `x`, using the provided
parameters of `amp`, `loc`, and `std`.
'''
return amp * np.exp(-((x - loc)*(x - loc))/(2.0*std*std)) | python | {
"resource": ""
} |
q258761 | _double_inverted_gaussian | validation | def _double_inverted_gaussian(x,
amp1, loc1, std1,
amp2, loc2, std2):
'''This is a double inverted gaussian.
Parameters
----------
x : np.array
The items at which the Gaussian is evaluated.
amp1,amp2 : float
The amplitude of Gaussian 1 and Gaussian 2.
loc1,loc2 : float
The central value of Gaussian 1 and Gaussian 2.
std1,std2 : float
The standard deviation of Gaussian 1 and Gaussian 2.
Returns
-------
np.array
Returns a double inverted Gaussian function evaluated at the items in
`x`, using the provided parameters of `amp`, `loc`, and `std` for two
component Gaussians 1 and 2.
'''
gaussian1 = -_gaussian(x,amp1,loc1,std1)
gaussian2 = -_gaussian(x,amp2,loc2,std2)
return gaussian1 + gaussian2 | python | {
"resource": ""
} |
q258762 | invgauss_eclipses_func | validation | def invgauss_eclipses_func(ebparams, times, mags, errs):
'''This returns a double eclipse shaped function.
Suitable for first order modeling of eclipsing binaries.
Parameters
----------
ebparams : list of float
This contains the parameters for the eclipsing binary::
ebparams = [period (time),
epoch (time),
pdepth: primary eclipse depth (mags),
pduration: primary eclipse duration (phase),
psdepthratio: primary-secondary eclipse depth ratio,
secondaryphase: center phase of the secondary eclipse]
`period` is the period in days.
`epoch` is the time of minimum in JD.
`pdepth` is the depth of the primary eclipse.
- for magnitudes -> pdepth should be < 0
- for fluxes -> pdepth should be > 0
`pduration` is the length of the primary eclipse in phase.
`psdepthratio` is the ratio in the eclipse depths:
`depth_secondary/depth_primary`. This is generally the same as the ratio
of the `T_effs` of the two stars.
`secondaryphase` is the phase at which the minimum of the secondary
eclipse is located. This effectively parameterizes eccentricity.
All of these will then have fitted values after the fit is done.
times,mags,errs : np.array
The input time-series of measurements and associated errors for which
the eclipse model will be generated. The times will be used to generate
model mags, and the input `times`, `mags`, and `errs` will be resorted
by model phase and returned.
Returns
-------
(modelmags, phase, ptimes, pmags, perrs) : tuple
Returns the model mags and phase values. Also returns the input `times`,
`mags`, and `errs` sorted by the model's phase.
'''
(period, epoch, pdepth, pduration, depthratio, secondaryphase) = ebparams
# generate the phases
iphase = (times - epoch)/period
iphase = iphase - np.floor(iphase)
phasesortind = np.argsort(iphase)
phase = iphase[phasesortind]
ptimes = times[phasesortind]
pmags = mags[phasesortind]
perrs = errs[phasesortind]
zerolevel = np.median(pmags)
modelmags = np.full_like(phase, zerolevel)
primaryecl_amp = -pdepth
secondaryecl_amp = -pdepth * depthratio
primaryecl_std = pduration/5.0 # we use 5-sigma as full-width -> duration
secondaryecl_std = pduration/5.0 # secondary eclipse has the same duration
halfduration = pduration/2.0
# phase indices
primary_eclipse_ingress = (
(phase >= (1.0 - halfduration)) & (phase <= 1.0)
)
primary_eclipse_egress = (
(phase >= 0.0) & (phase <= halfduration)
)
secondary_eclipse_phase = (
(phase >= (secondaryphase - halfduration)) &
(phase <= (secondaryphase + halfduration))
)
# put in the eclipses
modelmags[primary_eclipse_ingress] = (
zerolevel + _gaussian(phase[primary_eclipse_ingress],
primaryecl_amp,
1.0,
primaryecl_std)
)
modelmags[primary_eclipse_egress] = (
zerolevel + _gaussian(phase[primary_eclipse_egress],
primaryecl_amp,
0.0,
primaryecl_std)
)
modelmags[secondary_eclipse_phase] = (
zerolevel + _gaussian(phase[secondary_eclipse_phase],
secondaryecl_amp,
secondaryphase,
secondaryecl_std)
)
return modelmags, phase, ptimes, pmags, perrs | python | {
"resource": ""
} |
q258763 | jhk_to_bmag | validation | def jhk_to_bmag(jmag, hmag, kmag):
'''Converts given J, H, Ks mags to a B magnitude value.
Parameters
----------
jmag,hmag,kmag : float
2MASS J, H, Ks mags of the object.
Returns
-------
float
The converted B band magnitude.
'''
return convert_constants(jmag,hmag,kmag,
BJHK,
BJH, BJK, BHK,
BJ, BH, BK) | python | {
"resource": ""
} |
q258764 | jhk_to_vmag | validation | def jhk_to_vmag(jmag,hmag,kmag):
'''Converts given J, H, Ks mags to a V magnitude value.
Parameters
----------
jmag,hmag,kmag : float
2MASS J, H, Ks mags of the object.
Returns
-------
float
The converted V band magnitude.
'''
return convert_constants(jmag,hmag,kmag,
VJHK,
VJH, VJK, VHK,
VJ, VH, VK) | python | {
"resource": ""
} |
q258765 | jhk_to_rmag | validation | def jhk_to_rmag(jmag,hmag,kmag):
'''Converts given J, H, Ks mags to an R magnitude value.
Parameters
----------
jmag,hmag,kmag : float
2MASS J, H, Ks mags of the object.
Returns
-------
float
The converted R band magnitude.
'''
return convert_constants(jmag,hmag,kmag,
RJHK,
RJH, RJK, RHK,
RJ, RH, RK) | python | {
"resource": ""
} |
q258766 | jhk_to_imag | validation | def jhk_to_imag(jmag,hmag,kmag):
'''Converts given J, H, Ks mags to an I magnitude value.
Parameters
----------
jmag,hmag,kmag : float
2MASS J, H, Ks mags of the object.
Returns
-------
float
The converted I band magnitude.
'''
return convert_constants(jmag,hmag,kmag,
IJHK,
IJH, IJK, IHK,
IJ, IH, IK) | python | {
"resource": ""
} |
q258767 | jhk_to_sdssu | validation | def jhk_to_sdssu(jmag,hmag,kmag):
'''Converts given J, H, Ks mags to an SDSS u magnitude value.
Parameters
----------
jmag,hmag,kmag : float
2MASS J, H, Ks mags of the object.
Returns
-------
float
The converted SDSS u band magnitude.
'''
return convert_constants(jmag,hmag,kmag,
SDSSU_JHK,
SDSSU_JH, SDSSU_JK, SDSSU_HK,
SDSSU_J, SDSSU_H, SDSSU_K) | python | {
"resource": ""
} |
q258768 | jhk_to_sdssg | validation | def jhk_to_sdssg(jmag,hmag,kmag):
'''Converts given J, H, Ks mags to an SDSS g magnitude value.
Parameters
----------
jmag,hmag,kmag : float
2MASS J, H, Ks mags of the object.
Returns
-------
float
The converted SDSS g band magnitude.
'''
return convert_constants(jmag,hmag,kmag,
SDSSG_JHK,
SDSSG_JH, SDSSG_JK, SDSSG_HK,
SDSSG_J, SDSSG_H, SDSSG_K) | python | {
"resource": ""
} |
q258769 | jhk_to_sdssr | validation | def jhk_to_sdssr(jmag,hmag,kmag):
'''Converts given J, H, Ks mags to an SDSS r magnitude value.
Parameters
----------
jmag,hmag,kmag : float
2MASS J, H, Ks mags of the object.
Returns
-------
float
The converted SDSS r band magnitude.
'''
return convert_constants(jmag,hmag,kmag,
SDSSR_JHK,
SDSSR_JH, SDSSR_JK, SDSSR_HK,
SDSSR_J, SDSSR_H, SDSSR_K) | python | {
"resource": ""
} |
q258770 | jhk_to_sdssi | validation | def jhk_to_sdssi(jmag,hmag,kmag):
'''Converts given J, H, Ks mags to an SDSS i magnitude value.
Parameters
----------
jmag,hmag,kmag : float
2MASS J, H, Ks mags of the object.
Returns
-------
float
The converted SDSS i band magnitude.
'''
return convert_constants(jmag,hmag,kmag,
SDSSI_JHK,
SDSSI_JH, SDSSI_JK, SDSSI_HK,
SDSSI_J, SDSSI_H, SDSSI_K) | python | {
"resource": ""
} |
q258771 | jhk_to_sdssz | validation | def jhk_to_sdssz(jmag,hmag,kmag):
'''Converts given J, H, Ks mags to an SDSS z magnitude value.
Parameters
----------
jmag,hmag,kmag : float
2MASS J, H, Ks mags of the object.
Returns
-------
float
The converted SDSS z band magnitude.
'''
return convert_constants(jmag,hmag,kmag,
SDSSZ_JHK,
SDSSZ_JH, SDSSZ_JK, SDSSZ_HK,
SDSSZ_J, SDSSZ_H, SDSSZ_K) | python | {
"resource": ""
} |
q258772 | aov_theta | validation | def aov_theta(times, mags, errs, frequency,
binsize=0.05, minbin=9):
'''Calculates the Schwarzenberg-Czerny AoV statistic at a test frequency.
Parameters
----------
times,mags,errs : np.array
The input time-series and associated errors.
frequency : float
The test frequency to calculate the theta statistic at.
binsize : float
The phase bin size to use.
minbin : int
The minimum number of items in a phase bin to consider in the
calculation of the statistic.
Returns
-------
theta_aov : float
The value of the AoV statistic at the specified `frequency`.
'''
period = 1.0/frequency
fold_time = times[0]
phased = phase_magseries(times,
mags,
period,
fold_time,
wrap=False,
sort=True)
phases = phased['phase']
pmags = phased['mags']
bins = nparange(0.0, 1.0, binsize)
ndets = phases.size
binnedphaseinds = npdigitize(phases, bins)
bin_s1_tops = []
bin_s2_tops = []
binndets = []
goodbins = 0
all_xbar = npmedian(pmags)
for x in npunique(binnedphaseinds):
thisbin_inds = binnedphaseinds == x
thisbin_mags = pmags[thisbin_inds]
if thisbin_mags.size > minbin:
thisbin_ndet = thisbin_mags.size
thisbin_xbar = npmedian(thisbin_mags)
# get s1
thisbin_s1_top = (
thisbin_ndet *
(thisbin_xbar - all_xbar) *
(thisbin_xbar - all_xbar)
)
# get s2
thisbin_s2_top = npsum((thisbin_mags - all_xbar) *
(thisbin_mags - all_xbar))
bin_s1_tops.append(thisbin_s1_top)
bin_s2_tops.append(thisbin_s2_top)
binndets.append(thisbin_ndet)
goodbins = goodbins + 1
# turn the quantities into arrays
bin_s1_tops = nparray(bin_s1_tops)
bin_s2_tops = nparray(bin_s2_tops)
binndets = nparray(binndets)
# calculate s1 first
s1 = npsum(bin_s1_tops)/(goodbins - 1.0)
# then calculate s2
s2 = npsum(bin_s2_tops)/(ndets - goodbins)
theta_aov = s1/s2
return theta_aov | python | {
"resource": ""
} |
q258773 | bootstrap_falsealarmprob | validation | def bootstrap_falsealarmprob(lspinfo,
times,
mags,
errs,
nbootstrap=250,
magsarefluxes=False,
sigclip=10.0,
npeaks=None):
'''Calculates the false alarm probabilities of periodogram peaks using
bootstrap resampling of the magnitude time series.
The false alarm probability here is defined as::
(1.0 + sum(trialbestpeaks[i] > peak[j]))/(ntrialbestpeaks + 1)
for each best periodogram peak j. The index i is for each bootstrap
trial. This effectively gives us a significance for the peak. Smaller FAP
means a better chance that the peak is real.
The basic idea is to get the number of trial best peaks that are larger than
the current best peak and divide this by the total number of trials. The
distribution of these trial best peaks is obtained after scrambling the mag
values and rerunning the specified periodogram method for a bunch of trials.
`lspinfo` is the output dict from a periodbase periodogram function and MUST
contain a 'method' key that corresponds to one of the keys in the LSPMETHODS
dict above. This will let this function know which periodogram function to
run to generate the bootstrap samples. The lspinfo SHOULD also have a
'kwargs' key that corresponds to the input keyword arguments for the
periodogram function as it was run originally, to keep everything the same
during the bootstrap runs. If this is missing, default values will be used.
FIXME: this may not be strictly correct; must look more into bootstrap
significance testing. Also look into if we're doing resampling correctly for
time series because the samples are not iid. Look into moving block
bootstrap.
Parameters
----------
lspinfo : dict
A dict of period-finder results from one of the period-finders in
periodbase, or your own functions, provided it's of the form and
contains at least the keys listed below::
{'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
`astrobase.periodbase.METHODLABELS` dict,
'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,
'kwargs': dict of kwargs passed to your own period-finder function}
If you provide your own function's period-finder results, you should add
a corresponding key for it to the LSPMETHODS dict above so the bootstrap
function can use it correctly. Your period-finder function should take
`times`, `mags`, errs and any extra parameters as kwargs and return a
dict of the form described above. A small worked example::
from your_module import your_periodfinder_func
from astrobase import periodbase
periodbase.LSPMETHODS['your-finder'] = your_periodfinder_func
# run a period-finder session
your_pfresults = your_periodfinder_func(times, mags, errs,
**extra_kwargs)
# run bootstrap to find FAP
falsealarm_info = periodbase.bootstrap_falsealarmprob(
your_pfresults,
times, mags, errs,
nbootstrap=250,
magsarefluxes=False,
)
times,mags,errs : np.arrays
The magnitude/flux time-series to process along with their associated
measurement errors.
nbootstrap : int
The total number of bootstrap trials to run. This is set to 250 by
default, but should probably be around 1000 for realistic results.
magsarefluxes : bool
If True, indicates the input time-series is fluxes and not mags.
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.
npeaks : int or None
The number of peaks from the list of 'nbestlspvals' in the period-finder
result dict to run the bootstrap for. If None, all of the peaks in this
list will have their FAP calculated.
Returns
-------
dict
Returns a dict of the form::
{'peaks':allpeaks,
'periods':allperiods,
'probabilities':allfaps,
'alltrialbestpeaks':alltrialbestpeaks}
'''
# figure out how many periods to work on
if (npeaks and (0 < npeaks < len(lspinfo['nbestperiods']))):
nperiods = npeaks
else:
LOGWARNING('npeaks not specified or invalid, '
'getting FAP for all %s periodogram peaks' %
len(lspinfo['nbestperiods']))
nperiods = len(lspinfo['nbestperiods'])
nbestperiods = lspinfo['nbestperiods'][:nperiods]
nbestpeaks = lspinfo['nbestlspvals'][:nperiods]
# get rid of nans first and sigclip
stimes, smags, serrs = sigclip_magseries(times,
mags,
errs,
magsarefluxes=magsarefluxes,
sigclip=sigclip)
allpeaks = []
allperiods = []
allfaps = []
alltrialbestpeaks = []
# make sure there are enough points to calculate a spectrum
if len(stimes) > 9 and len(smags) > 9 and len(serrs) > 9:
for ind, period, peak in zip(range(len(nbestperiods)),
nbestperiods,
nbestpeaks):
LOGINFO('peak %s: running %s trials...' % (ind+1, nbootstrap))
trialbestpeaks = []
for _trial in range(nbootstrap):
# get a scrambled index
tindex = np.random.randint(0,
high=mags.size,
size=mags.size)
# get the kwargs dict out of the lspinfo
if 'kwargs' in lspinfo:
kwargs = lspinfo['kwargs']
# update the kwargs with some local stuff
kwargs.update({'magsarefluxes':magsarefluxes,
'sigclip':sigclip,
'verbose':False})
else:
kwargs = {'magsarefluxes':magsarefluxes,
'sigclip':sigclip,
'verbose':False}
# run the periodogram with scrambled mags and errs
# and the appropriate keyword arguments
lspres = LSPMETHODS[lspinfo['method']](
times, mags[tindex], errs[tindex],
**kwargs
)
trialbestpeaks.append(lspres['bestlspval'])
trialbestpeaks = np.array(trialbestpeaks)
alltrialbestpeaks.append(trialbestpeaks)
# calculate the FAP for a trial peak j = FAP[j] =
# (1.0 + sum(trialbestpeaks[i] > peak[j]))/(ntrialbestpeaks + 1)
if lspinfo['method'] != 'pdm':
falsealarmprob = (
(1.0 + trialbestpeaks[trialbestpeaks > peak].size) /
(trialbestpeaks.size + 1.0)
)
# for PDM, we're looking for a peak smaller than the best peak
# because values closer to 0.0 are more significant
else:
falsealarmprob = (
(1.0 + trialbestpeaks[trialbestpeaks < peak].size) /
(trialbestpeaks.size + 1.0)
)
LOGINFO('FAP for peak %s, period: %.6f = %.3g' % (ind+1,
period,
falsealarmprob))
allpeaks.append(peak)
allperiods.append(period)
allfaps.append(falsealarmprob)
return {'peaks':allpeaks,
'periods':allperiods,
'probabilities':allfaps,
'alltrialbestpeaks':alltrialbestpeaks}
else:
LOGERROR('not enough mag series points to calculate periodogram')
return None | python | {
"resource": ""
} |
q258774 | make_combined_periodogram | validation | def make_combined_periodogram(pflist, outfile, addmethods=False):
'''This just puts all of the period-finders on a single periodogram.
This will renormalize all of the periodograms so their values lie between 0
and 1, with values lying closer to 1 being more significant. Periodograms
that give the same best periods will have their peaks line up together.
Parameters
----------
pflist : list of dict
This is a list of result dicts from any of the period-finders in
periodbase. To use your own period-finders' results here, make sure the
result dict is of the form and has at least the keys below::
{'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
`astrobase.periodbase.METHODLABELS` dict,
'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,
'kwargs': dict of kwargs passed to your own period-finder function}
outfile : str
This is the output file to write the output to. NOTE: EPS/PS won't work
because we use alpha transparency to better distinguish between the
various periodograms.
addmethods : bool
If this is True, will add all of the normalized periodograms together,
then renormalize them to between 0 and 1. In this way, if all of the
period-finders agree on something, it'll stand out easily. FIXME:
implement this kwarg.
Returns
-------
str
The name of the generated plot file.
'''
import matplotlib.pyplot as plt
for pf in pflist:
if pf['method'] == 'pdm':
plt.plot(pf['periods'],
np.max(pf['lspvals'])/pf['lspvals'] - 1.0,
label='%s P=%.5f' % (pf['method'], pf['bestperiod']),
alpha=0.5)
else:
plt.plot(pf['periods'],
pf['lspvals']/np.max(pf['lspvals']),
label='%s P=%.5f' % (pf['method'], pf['bestperiod']),
alpha=0.5)
plt.xlabel('period [days]')
plt.ylabel('normalized periodogram power')
plt.xscale('log')
plt.legend()
plt.tight_layout()
plt.savefig(outfile)
plt.close('all')
return outfile | python | {
"resource": ""
} |
q258775 | _get_value | validation | def _get_value(quantitystr, fitparams, fixedparams):
"""This decides if a value is to be fit for or is fixed in a model fit.
When you want to get the value of some parameter, but you're not sure if
it's being fit or if it is fixed. then, e.g. for `period`::
period_value = _get_value('period', fitparams, fixedparams)
"""
# for Mandel-Agol fitting, sometimes we want to fix some parameters,
# and fit others. this function allows that flexibility.
fitparamskeys, fixedparamskeys = fitparams.keys(), fixedparams.keys()
if quantitystr in fitparamskeys:
quantity = fitparams[quantitystr]
elif quantitystr in fixedparamskeys:
quantity = fixedparams[quantitystr]
return quantity | python | {
"resource": ""
} |
q258776 | _transit_model | validation | def _transit_model(times, t0, per, rp, a, inc, ecc, w, u, limb_dark,
exp_time_minutes=2, supersample_factor=7):
'''This returns a BATMAN planetary transit model.
Parameters
----------
times : np.array
The times at which the model will be evaluated.
t0 : float
The time of periastron for the transit.
per : float
The orbital period of the planet.
rp : float
The stellar radius of the planet's star (in Rsun).
a : float
The semi-major axis of the planet's orbit (in Rsun).
inc : float
The orbital inclination (in degrees).
ecc : float
The eccentricity of the orbit.
w : float
The longitude of periastron (in degrees).
u : list of floats
The limb darkening coefficients specific to the limb darkening model
used.
limb_dark : {"uniform", "linear", "quadratic", "square-root", "logarithmic", "exponential", "power2", "custom"}
The type of limb darkening model to use. See the full list here:
https://www.cfa.harvard.edu/~lkreidberg/batman/tutorial.html#limb-darkening-options
exp_time_minutes : float
The amount of time to 'smear' the transit LC points over to simulate a
long exposure time.
supersample_factor: int
The number of supersampled time data points to average the lightcurve
model over.
Returns
-------
(params, batman_model) : tuple
The returned tuple contains the params list and the generated
`batman.TransitModel` object.
'''
params = batman.TransitParams() # object to store transit parameters
params.t0 = t0 # time of periastron
params.per = per # orbital period
params.rp = rp # planet radius (in stellar radii)
params.a = a # semi-major axis (in stellar radii)
params.inc = inc # orbital inclination (in degrees)
params.ecc = ecc # the eccentricity of the orbit
params.w = w # longitude of periastron (in degrees)
params.u = u # limb darkening coefficient list
params.limb_dark = limb_dark # limb darkening model to use
t = times
m = batman.TransitModel(params, t, exp_time=exp_time_minutes/60./24.,
supersample_factor=supersample_factor)
return params, m | python | {
"resource": ""
} |
q258777 | _log_prior_transit | validation | def _log_prior_transit(theta, priorbounds):
'''
Assume priors on all parameters have uniform probability.
'''
# priorbounds contains the input priors, and because of how we previously
# sorted theta, its sorted keys tell us which parts of theta correspond to
# which physical quantities.
allowed = True
for ix, key in enumerate(np.sort(list(priorbounds.keys()))):
if priorbounds[key][0] < theta[ix] < priorbounds[key][1]:
allowed = True and allowed
else:
allowed = False
if allowed:
return 0.
return -np.inf | python | {
"resource": ""
} |
q258778 | list_trilegal_filtersystems | validation | def list_trilegal_filtersystems():
'''
This just lists all the filter systems available for TRILEGAL.
'''
print('%-40s %s' % ('FILTER SYSTEM NAME','DESCRIPTION'))
print('%-40s %s' % ('------------------','-----------'))
for key in sorted(TRILEGAL_FILTER_SYSTEMS.keys()):
print('%-40s %s' % (key, TRILEGAL_FILTER_SYSTEMS[key]['desc'])) | python | {
"resource": ""
} |
q258779 | query_radecl | validation | def query_radecl(ra,
decl,
filtersystem='sloan_2mass',
field_deg2=1.0,
usebinaries=True,
extinction_sigma=0.1,
magnitude_limit=26.0,
maglim_filtercol=4,
trilegal_version=1.6,
extraparams=None,
forcefetch=False,
cachedir='~/.astrobase/trilegal-cache',
verbose=True,
timeout=60.0,
refresh=150.0,
maxtimeout=700.0):
'''This runs the TRILEGAL query for decimal equatorial coordinates.
Parameters
----------
ra,decl : float
These are the center equatorial coordinates in decimal degrees
filtersystem : str
This is a key in the TRILEGAL_FILTER_SYSTEMS dict. Use the function
:py:func:`astrobase.services.trilegal.list_trilegal_filtersystems` to
see a nicely formatted table with the key and description for each of
these.
field_deg2 : float
The area of the simulated field in square degrees. This is in the
Galactic coordinate system.
usebinaries : bool
If this is True, binaries will be present in the model results.
extinction_sigma : float
This is the applied std dev around the `Av_extinction` value for the
galactic coordinates requested.
magnitude_limit : float
This is the limiting magnitude of the simulation in the
`maglim_filtercol` band index of the filter system chosen.
maglim_filtercol : int
The index in the filter system list of the magnitude limiting band.
trilegal_version : float
This is the the version of the TRILEGAL form to use. This can usually be
left as-is.
extraparams : dict or None
This is a dict that can be used to override parameters of the model
other than the basic ones used for input to this function. All
parameters are listed in `TRILEGAL_DEFAULT_PARAMS` above. See:
http://stev.oapd.inaf.it/cgi-bin/trilegal
for explanations of these parameters.
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.
Returns
-------
dict
This returns a dict of the form::
{'params':the input param dict used,
'extraparams':any extra params used,
'provenance':'cached' or 'new download',
'tablefile':the path on disk to the downloaded model text file}
'''
# convert the ra/decl to gl, gb
radecl = SkyCoord(ra=ra*u.degree, dec=decl*u.degree)
gl = radecl.galactic.l.degree
gb = radecl.galactic.b.degree
return query_galcoords(gl,
gb,
filtersystem=filtersystem,
field_deg2=field_deg2,
usebinaries=usebinaries,
extinction_sigma=extinction_sigma,
magnitude_limit=magnitude_limit,
maglim_filtercol=maglim_filtercol,
trilegal_version=trilegal_version,
extraparams=extraparams,
forcefetch=forcefetch,
cachedir=cachedir,
verbose=verbose,
timeout=timeout,
refresh=refresh,
maxtimeout=maxtimeout) | python | {
"resource": ""
} |
q258780 | read_model_table | validation | def read_model_table(modelfile):
'''
This reads a downloaded TRILEGAL model file.
Parameters
----------
modelfile : str
Path to the downloaded model file to read.
Returns
-------
np.recarray
Returns the model table as a Numpy record array.
'''
infd = gzip.open(modelfile)
model = np.genfromtxt(infd,names=True)
infd.close()
return model | python | {
"resource": ""
} |
q258781 | _time_independent_equals | validation | def _time_independent_equals(a, b):
'''
This compares two values in constant time.
Taken from tornado:
https://github.com/tornadoweb/tornado/blob/
d4eb8eb4eb5cc9a6677e9116ef84ded8efba8859/tornado/web.py#L3060
'''
if len(a) != len(b):
return False
result = 0
if isinstance(a[0], int): # python3 byte strings
for x, y in zip(a, b):
result |= x ^ y
else: # python2
for x, y in zip(a, b):
result |= ord(x) ^ ord(y)
return result == 0 | python | {
"resource": ""
} |
q258782 | FrontendEncoder.default | validation | def default(self, obj):
'''Overrides the default serializer for `JSONEncoder`.
This can serialize the following objects in addition to what
`JSONEncoder` can already do.
- `np.array`
- `bytes`
- `complex`
- `np.float64` and other `np.dtype` objects
Parameters
----------
obj : object
A Python object to serialize to JSON.
Returns
-------
str
A JSON encoded representation of the input object.
'''
if isinstance(obj, np.ndarray):
return obj.tolist()
elif isinstance(obj, bytes):
return obj.decode()
elif isinstance(obj, complex):
return (obj.real, obj.imag)
elif (isinstance(obj, (float, np.float64, np.float_)) and
not np.isfinite(obj)):
return None
elif isinstance(obj, (np.int8, np.int16, np.int32, np.int64)):
return int(obj)
else:
return json.JSONEncoder.default(self, obj) | python | {
"resource": ""
} |
q258783 | IndexHandler.initialize | validation | def initialize(self, currentdir, assetpath, cplist,
cplistfile, executor, readonly, baseurl):
'''
handles initial setup.
'''
self.currentdir = currentdir
self.assetpath = assetpath
self.currentproject = cplist
self.cplistfile = cplistfile
self.executor = executor
self.readonly = readonly
self.baseurl = baseurl | python | {
"resource": ""
} |
q258784 | IndexHandler.get | validation | def get(self):
'''This handles GET requests to the index page.
TODO: provide the correct baseurl from the checkplotserver options dict,
so the frontend JS can just read that off immediately.
'''
# generate the project's list of checkplots
project_checkplots = self.currentproject['checkplots']
project_checkplotbasenames = [os.path.basename(x)
for x in project_checkplots]
project_checkplotindices = range(len(project_checkplots))
# get the sortkey and order
project_cpsortkey = self.currentproject['sortkey']
if self.currentproject['sortorder'] == 'asc':
project_cpsortorder = 'ascending'
elif self.currentproject['sortorder'] == 'desc':
project_cpsortorder = 'descending'
# get the filterkey and condition
project_cpfilterstatements = self.currentproject['filterstatements']
self.render('cpindex.html',
project_checkplots=project_checkplots,
project_cpsortorder=project_cpsortorder,
project_cpsortkey=project_cpsortkey,
project_cpfilterstatements=project_cpfilterstatements,
project_checkplotbasenames=project_checkplotbasenames,
project_checkplotindices=project_checkplotindices,
project_checkplotfile=self.cplistfile,
readonly=self.readonly,
baseurl=self.baseurl) | python | {
"resource": ""
} |
q258785 | CheckplotListHandler.get | validation | def get(self):
'''
This handles GET requests for the current checkplot-list.json file.
Used with AJAX from frontend.
'''
# add the reviewed key to the current dict if it doesn't exist
# this will hold all the reviewed objects for the frontend
if 'reviewed' not in self.currentproject:
self.currentproject['reviewed'] = {}
# just returns the current project as JSON
self.write(self.currentproject) | python | {
"resource": ""
} |
q258786 | StandaloneHandler.initialize | validation | def initialize(self, executor, secret):
'''
This handles initial setup of the `RequestHandler`.
'''
self.executor = executor
self.secret = secret | python | {
"resource": ""
} |
q258787 | smooth_magseries_gaussfilt | validation | def smooth_magseries_gaussfilt(mags, windowsize, windowfwhm=7):
'''This smooths the magseries with a Gaussian kernel.
Parameters
----------
mags : np.array
The input mags/flux time-series to smooth.
windowsize : int
This is a odd integer containing the smoothing window size.
windowfwhm : int
This is an odd integer containing the FWHM of the applied Gaussian
window function.
Returns
-------
np.array
The smoothed mag/flux time-series array.
'''
convkernel = Gaussian1DKernel(windowfwhm, x_size=windowsize)
smoothed = convolve(mags, convkernel, boundary='extend')
return smoothed | python | {
"resource": ""
} |
q258788 | smooth_magseries_savgol | validation | def smooth_magseries_savgol(mags, windowsize, polyorder=2):
'''This smooths the magseries with a Savitsky-Golay filter.
Parameters
----------
mags : np.array
The input mags/flux time-series to smooth.
windowsize : int
This is a odd integer containing the smoothing window size.
polyorder : int
This is an integer containing the polynomial degree order to use when
generating the Savitsky-Golay filter.
Returns
-------
np.array
The smoothed mag/flux time-series array.
'''
smoothed = savgol_filter(mags, windowsize, polyorder)
return smoothed | python | {
"resource": ""
} |
q258789 | _old_epd_diffmags | validation | def _old_epd_diffmags(coeff, fsv, fdv, fkv, xcc, ycc, bgv, bge, mag):
'''
This calculates the difference in mags after EPD coefficients are
calculated.
final EPD mags = median(magseries) + epd_diffmags()
'''
return -(coeff[0]*fsv**2. +
coeff[1]*fsv +
coeff[2]*fdv**2. +
coeff[3]*fdv +
coeff[4]*fkv**2. +
coeff[5]*fkv +
coeff[6] +
coeff[7]*fsv*fdv +
coeff[8]*fsv*fkv +
coeff[9]*fdv*fkv +
coeff[10]*np.sin(2*np.pi*xcc) +
coeff[11]*np.cos(2*np.pi*xcc) +
coeff[12]*np.sin(2*np.pi*ycc) +
coeff[13]*np.cos(2*np.pi*ycc) +
coeff[14]*np.sin(4*np.pi*xcc) +
coeff[15]*np.cos(4*np.pi*xcc) +
coeff[16]*np.sin(4*np.pi*ycc) +
coeff[17]*np.cos(4*np.pi*ycc) +
coeff[18]*bgv +
coeff[19]*bge -
mag) | python | {
"resource": ""
} |
q258790 | _old_epd_magseries | validation | def _old_epd_magseries(times, mags, errs,
fsv, fdv, fkv, xcc, ycc, bgv, bge,
epdsmooth_windowsize=21,
epdsmooth_sigclip=3.0,
epdsmooth_func=smooth_magseries_signal_medfilt,
epdsmooth_extraparams=None):
'''
Detrends a magnitude series given in mag using accompanying values of S in
fsv, D in fdv, K in fkv, x coords in xcc, y coords in ycc, background in
bgv, and background error in bge. smooth is used to set a smoothing
parameter for the fit function. Does EPD voodoo.
'''
# find all the finite values of the magsnitude
finiteind = np.isfinite(mags)
# calculate median and stdev
mags_median = np.median(mags[finiteind])
mags_stdev = np.nanstd(mags)
# if we're supposed to sigma clip, do so
if epdsmooth_sigclip:
excludeind = abs(mags - mags_median) < epdsmooth_sigclip*mags_stdev
finalind = finiteind & excludeind
else:
finalind = finiteind
final_mags = mags[finalind]
final_len = len(final_mags)
# smooth the signal
if isinstance(epdsmooth_extraparams, dict):
smoothedmags = epdsmooth_func(final_mags,
epdsmooth_windowsize,
**epdsmooth_extraparams)
else:
smoothedmags = epdsmooth_func(final_mags, epdsmooth_windowsize)
# make the linear equation matrix
epdmatrix = np.c_[fsv[finalind]**2.0,
fsv[finalind],
fdv[finalind]**2.0,
fdv[finalind],
fkv[finalind]**2.0,
fkv[finalind],
np.ones(final_len),
fsv[finalind]*fdv[finalind],
fsv[finalind]*fkv[finalind],
fdv[finalind]*fkv[finalind],
np.sin(2*np.pi*xcc[finalind]),
np.cos(2*np.pi*xcc[finalind]),
np.sin(2*np.pi*ycc[finalind]),
np.cos(2*np.pi*ycc[finalind]),
np.sin(4*np.pi*xcc[finalind]),
np.cos(4*np.pi*xcc[finalind]),
np.sin(4*np.pi*ycc[finalind]),
np.cos(4*np.pi*ycc[finalind]),
bgv[finalind],
bge[finalind]]
# solve the matrix equation [epdmatrix] . [x] = [smoothedmags]
# return the EPD differential magss if the solution succeeds
try:
coeffs, residuals, rank, singulars = lstsq(epdmatrix, smoothedmags,
rcond=None)
if DEBUG:
print('coeffs = %s, residuals = %s' % (coeffs, residuals))
retdict = {'times':times,
'mags':(mags_median +
_old_epd_diffmags(coeffs, fsv, fdv,
fkv, xcc, ycc, bgv, bge, mags)),
'errs':errs,
'fitcoeffs':coeffs,
'residuals':residuals}
return retdict
# if the solution fails, return nothing
except Exception as e:
LOGEXCEPTION('EPD solution did not converge')
retdict = {'times':times,
'mags':np.full_like(mags, np.nan),
'errs':errs,
'fitcoeffs':coeffs,
'residuals':residuals}
return retdict | python | {
"resource": ""
} |
q258791 | _epd_function | validation | def _epd_function(coeffs, fsv, fdv, fkv, xcc, ycc, bgv, bge, iha, izd):
'''
This is the EPD function to fit using a smoothed mag-series.
'''
return (coeffs[0]*fsv*fsv +
coeffs[1]*fsv +
coeffs[2]*fdv*fdv +
coeffs[3]*fdv +
coeffs[4]*fkv*fkv +
coeffs[5]*fkv +
coeffs[6] +
coeffs[7]*fsv*fdv +
coeffs[8]*fsv*fkv +
coeffs[9]*fdv*fkv +
coeffs[10]*np.sin(2*pi_value*xcc) +
coeffs[11]*np.cos(2*pi_value*xcc) +
coeffs[12]*np.sin(2*pi_value*ycc) +
coeffs[13]*np.cos(2*pi_value*ycc) +
coeffs[14]*np.sin(4*pi_value*xcc) +
coeffs[15]*np.cos(4*pi_value*xcc) +
coeffs[16]*np.sin(4*pi_value*ycc) +
coeffs[17]*np.cos(4*pi_value*ycc) +
coeffs[18]*bgv +
coeffs[19]*bge +
coeffs[20]*iha +
coeffs[21]*izd) | python | {
"resource": ""
} |
q258792 | _epd_residual2 | validation | def _epd_residual2(coeffs,
times, mags, errs,
fsv, fdv, fkv, xcc, ycc, bgv, bge, iha, izd):
'''This is the residual function to minimize using
scipy.optimize.least_squares.
This variant is for :py:func:`.epd_magseries_extparams`.
'''
f = _epd_function(coeffs, fsv, fdv, fkv, xcc, ycc, bgv, bge, iha, izd)
residual = mags - f
return residual | python | {
"resource": ""
} |
q258793 | epd_magseries | validation | def epd_magseries(times, mags, errs,
fsv, fdv, fkv, xcc, ycc, bgv, bge, iha, izd,
magsarefluxes=False,
epdsmooth_sigclip=3.0,
epdsmooth_windowsize=21,
epdsmooth_func=smooth_magseries_savgol,
epdsmooth_extraparams=None):
'''Detrends a magnitude series using External Parameter Decorrelation.
Requires a set of external parameters similar to those present in HAT light
curves. At the moment, the HAT light-curve-specific external parameters are:
- S: the 'fsv' column in light curves,
- D: the 'fdv' column in light curves,
- K: the 'fkv' column in light curves,
- x coords: the 'xcc' column in light curves,
- y coords: the 'ycc' column in light curves,
- background value: the 'bgv' column in light curves,
- background error: the 'bge' column in light curves,
- hour angle: the 'iha' column in light curves,
- zenith distance: the 'izd' column in light curves
S, D, and K are defined as follows:
- S -> measure of PSF sharpness (~1/sigma^2 sosmaller S = wider PSF)
- D -> measure of PSF ellipticity in xy direction
- K -> measure of PSF ellipticity in cross direction
S, D, K are related to the PSF's variance and covariance, see eqn 30-33 in
A. Pal's thesis: https://arxiv.org/abs/0906.3486
NOTE: The errs are completely ignored and returned unchanged (except for
sigclip and finite filtering).
Parameters
----------
times,mags,errs : np.array
The input mag/flux time-series to detrend.
fsv : np.array
Array containing the external parameter `S` of the same length as times.
fdv : np.array
Array containing the external parameter `D` of the same length as times.
fkv : np.array
Array containing the external parameter `K` of the same length as times.
xcc : np.array
Array containing the external parameter `x-coords` of the same length as
times.
ycc : np.array
Array containing the external parameter `y-coords` of the same length as
times.
bgv : np.array
Array containing the external parameter `background value` of the same
length as times.
bge : np.array
Array containing the external parameter `background error` of the same
length as times.
iha : np.array
Array containing the external parameter `hour angle` of the same length
as times.
izd : np.array
Array containing the external parameter `zenith distance` of the same
length as times.
magsarefluxes : bool
Set this to True if `mags` actually contains fluxes.
epdsmooth_sigclip : float or int or sequence of two floats/ints or None
This specifies how to sigma-clip the input LC before fitting the EPD
function to it.
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.
epdsmooth_windowsize : int
This is the number of LC points to smooth over to generate a smoothed
light curve that will be used to fit the EPD function.
epdsmooth_func : Python function
This sets the smoothing filter function to use. A Savitsky-Golay filter
is used to smooth the light curve by default. The functions that can be
used with this kwarg are listed in `varbase.trends`. If you want to use
your own function, it MUST have the following signature::
def smoothfunc(mags_array, window_size, **extraparams)
and return a numpy array of the same size as `mags_array` with the
smoothed time-series. Any extra params can be provided using the
`extraparams` dict.
epdsmooth_extraparams : dict
This is a dict of any extra filter params to supply to the smoothing
function.
Returns
-------
dict
Returns a dict of the following form::
{'times':the input times after non-finite elems removed,
'mags':the EPD detrended mag values (the EPD mags),
'errs':the errs after non-finite elems removed,
'fitcoeffs':EPD fit coefficient values,
'fitinfo':the full tuple returned by scipy.leastsq,
'fitmags':the EPD fit function evaluated at times,
'mags_median': this is median of the EPD mags,
'mags_mad': this is the MAD of EPD mags}
'''
finind = np.isfinite(times) & np.isfinite(mags) & np.isfinite(errs)
ftimes, fmags, ferrs = times[::][finind], mags[::][finind], errs[::][finind]
ffsv, ffdv, ffkv, fxcc, fycc, fbgv, fbge, fiha, fizd = (
fsv[::][finind],
fdv[::][finind],
fkv[::][finind],
xcc[::][finind],
ycc[::][finind],
bgv[::][finind],
bge[::][finind],
iha[::][finind],
izd[::][finind],
)
stimes, smags, serrs, separams = sigclip_magseries_with_extparams(
times, mags, errs,
[fsv, fdv, fkv, xcc, ycc, bgv, bge, iha, izd],
sigclip=epdsmooth_sigclip,
magsarefluxes=magsarefluxes
)
sfsv, sfdv, sfkv, sxcc, sycc, sbgv, sbge, siha, sizd = separams
# smooth the signal
if isinstance(epdsmooth_extraparams, dict):
smoothedmags = epdsmooth_func(smags,
epdsmooth_windowsize,
**epdsmooth_extraparams)
else:
smoothedmags = epdsmooth_func(smags, epdsmooth_windowsize)
# initial fit coeffs
initcoeffs = np.zeros(22)
# fit the smoothed mags and find the EPD function coefficients
leastsqfit = leastsq(_epd_residual,
initcoeffs,
args=(smoothedmags,
sfsv, sfdv, sfkv, sxcc,
sycc, sbgv, sbge, siha, sizd),
full_output=True)
# if the fit succeeds, then get the EPD mags
if leastsqfit[-1] in (1,2,3,4):
fitcoeffs = leastsqfit[0]
epdfit = _epd_function(fitcoeffs,
ffsv, ffdv, ffkv, fxcc, fycc,
fbgv, fbge, fiha, fizd)
epdmags = npmedian(fmags) + fmags - epdfit
retdict = {'times':ftimes,
'mags':epdmags,
'errs':ferrs,
'fitcoeffs':fitcoeffs,
'fitinfo':leastsqfit,
'fitmags':epdfit,
'mags_median':npmedian(epdmags),
'mags_mad':npmedian(npabs(epdmags - npmedian(epdmags)))}
return retdict
# if the solution fails, return nothing
else:
LOGERROR('EPD fit did not converge')
return None | python | {
"resource": ""
} |
q258794 | rfepd_magseries | validation | def rfepd_magseries(times, mags, errs,
externalparam_arrs,
magsarefluxes=False,
epdsmooth=True,
epdsmooth_sigclip=3.0,
epdsmooth_windowsize=21,
epdsmooth_func=smooth_magseries_savgol,
epdsmooth_extraparams=None,
rf_subsample=1.0,
rf_ntrees=300,
rf_extraparams={'criterion':'mse',
'oob_score':False,
'n_jobs':-1}):
'''This uses a `RandomForestRegressor` to de-correlate the given magseries.
Parameters
----------
times,mags,errs : np.array
The input mag/flux time-series to run EPD on.
externalparam_arrs : list of np.arrays
This is a list of ndarrays of external parameters to decorrelate
against. These should all be the same size as `times`, `mags`, `errs`.
epdsmooth : bool
If True, sets the training LC for the RandomForestRegress to be a
smoothed version of the sigma-clipped light curve provided in `times`,
`mags`, `errs`.
epdsmooth_sigclip : float or int or sequence of two floats/ints or None
This specifies how to sigma-clip the input LC before smoothing it and
fitting the EPD function to it. The actual LC will not be sigma-clipped.
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.
epdsmooth_windowsize : int
This is the number of LC points to smooth over to generate a smoothed
light curve that will be used to fit the EPD function.
epdsmooth_func : Python function
This sets the smoothing filter function to use. A Savitsky-Golay filter
is used to smooth the light curve by default. The functions that can be
used with this kwarg are listed in `varbase.trends`. If you want to use
your own function, it MUST have the following signature::
def smoothfunc(mags_array, window_size, **extraparams)
and return a numpy array of the same size as `mags_array` with the
smoothed time-series. Any extra params can be provided using the
`extraparams` dict.
epdsmooth_extraparams : dict
This is a dict of any extra filter params to supply to the smoothing
function.
rf_subsample : float
Defines the fraction of the size of the `mags` array to use for
training the random forest regressor.
rf_ntrees : int
This is the number of trees to use for the `RandomForestRegressor`.
rf_extraprams : dict
This is a dict of any extra kwargs to provide to the
`RandomForestRegressor` instance used.
Returns
-------
dict
Returns a dict with decorrelated mags and the usual info from the
`RandomForestRegressor`: variable importances, etc.
'''
# get finite times, mags, errs
finind = np.isfinite(times) & np.isfinite(mags) & np.isfinite(errs)
ftimes, fmags, ferrs = times[::][finind], mags[::][finind], errs[::][finind]
finalparam_arrs = []
for ep in externalparam_arrs:
finalparam_arrs.append(ep[::][finind])
stimes, smags, serrs, eparams = sigclip_magseries_with_extparams(
times, mags, errs,
externalparam_arrs,
sigclip=epdsmooth_sigclip,
magsarefluxes=magsarefluxes
)
# smoothing is optional for RFR because we train on a fraction of the mag
# series and so should not require a smoothed input to fit a function to
if epdsmooth:
# smooth the signal
if isinstance(epdsmooth_extraparams, dict):
smoothedmags = epdsmooth_func(smags,
epdsmooth_windowsize,
**epdsmooth_extraparams)
else:
smoothedmags = epdsmooth_func(smags,
epdsmooth_windowsize)
else:
smoothedmags = smags
# set up the regressor
if isinstance(rf_extraparams, dict):
RFR = RandomForestRegressor(n_estimators=rf_ntrees,
**rf_extraparams)
else:
RFR = RandomForestRegressor(n_estimators=rf_ntrees)
# collect the features
features = np.column_stack(eparams)
# fit, then generate the predicted values, then get corrected values
# we fit on a randomly selected subsample of all the mags
if rf_subsample < 1.0:
featureindices = np.arange(smoothedmags.size)
# these are sorted because time-order should be important
training_indices = np.sort(
npr.choice(featureindices,
size=int(rf_subsample*smoothedmags.size),
replace=False)
)
else:
training_indices = np.arange(smoothedmags.size)
RFR.fit(features[training_indices,:], smoothedmags[training_indices])
# predict on the full feature set
flux_corrections = RFR.predict(np.column_stack(finalparam_arrs))
corrected_fmags = npmedian(fmags) + fmags - flux_corrections
retdict = {'times':ftimes,
'mags':corrected_fmags,
'errs':ferrs,
'feature_importances':RFR.feature_importances_,
'regressor':RFR,
'mags_median':npmedian(corrected_fmags),
'mags_mad':npmedian(npabs(corrected_fmags -
npmedian(corrected_fmags)))}
return retdict | python | {
"resource": ""
} |
q258795 | stellingwerf_pdm_theta | validation | def stellingwerf_pdm_theta(times, mags, errs, frequency,
binsize=0.05, minbin=9):
'''
This calculates the Stellingwerf PDM theta value at a test frequency.
Parameters
----------
times,mags,errs : np.array
The input time-series and associated errors.
frequency : float
The test frequency to calculate the theta statistic at.
binsize : float
The phase bin size to use.
minbin : int
The minimum number of items in a phase bin to consider in the
calculation of the statistic.
Returns
-------
theta_pdm : float
The value of the theta statistic at the specified `frequency`.
'''
period = 1.0/frequency
fold_time = times[0]
phased = phase_magseries(times,
mags,
period,
fold_time,
wrap=False,
sort=True)
phases = phased['phase']
pmags = phased['mags']
bins = nparange(0.0, 1.0, binsize)
binnedphaseinds = npdigitize(phases, bins)
binvariances = []
binndets = []
goodbins = 0
for x in npunique(binnedphaseinds):
thisbin_inds = binnedphaseinds == x
thisbin_mags = pmags[thisbin_inds]
if thisbin_mags.size > minbin:
thisbin_variance = npvar(thisbin_mags,ddof=1)
binvariances.append(thisbin_variance)
binndets.append(thisbin_mags.size)
goodbins = goodbins + 1
# now calculate theta
binvariances = nparray(binvariances)
binndets = nparray(binndets)
theta_top = npsum(binvariances*(binndets - 1)) / (npsum(binndets) -
goodbins)
theta_bot = npvar(pmags,ddof=1)
theta = theta_top/theta_bot
return theta | python | {
"resource": ""
} |
q258796 | keplermag_to_sdssr | validation | def keplermag_to_sdssr(keplermag, kic_sdssg, kic_sdssr):
'''Converts magnitude measurements in Kepler band to SDSS r band.
Parameters
----------
keplermag : float or array-like
The Kepler magnitude value(s) to convert to fluxes.
kic_sdssg,kic_sdssr : float or array-like
The SDSS g and r magnitudes of the object(s) from the Kepler Input
Catalog. The .llc.fits MAST light curve file for a Kepler object
contains these values in the FITS extension 0 header.
Returns
-------
float or array-like
SDSS r band magnitude(s) converted from the Kepler band magnitude.
'''
kic_sdssgr = kic_sdssg - kic_sdssr
if kic_sdssgr < 0.8:
kepsdssr = (keplermag - 0.2*kic_sdssg)/0.8
else:
kepsdssr = (keplermag - 0.1*kic_sdssg)/0.9
return kepsdssr | python | {
"resource": ""
} |
q258797 | kepler_lcdict_to_pkl | validation | def kepler_lcdict_to_pkl(lcdict, outfile=None):
'''This writes the `lcdict` to a Python pickle.
Parameters
----------
lcdict : lcdict
This is the input `lcdict` to write to a pickle.
outfile : str or None
If this is None, the object's Kepler ID/EPIC ID will determined from the
`lcdict` and used to form the filename of the output pickle file. If
this is a `str`, the provided filename will be used.
Returns
-------
str
The absolute path to the written pickle file.
'''
if not outfile:
outfile = '%s-keplc.pkl' % lcdict['objectid'].replace(' ','-')
# we're using pickle.HIGHEST_PROTOCOL here, this will make Py3 pickles
# unreadable for Python 2.7
with open(outfile,'wb') as outfd:
pickle.dump(lcdict, outfd, protocol=pickle.HIGHEST_PROTOCOL)
return os.path.abspath(outfile) | python | {
"resource": ""
} |
q258798 | read_kepler_pklc | validation | def read_kepler_pklc(picklefile):
'''This turns the pickled lightcurve file back into an `lcdict`.
Parameters
----------
picklefile : str
The path to a previously written Kepler LC picklefile generated by
`kepler_lcdict_to_pkl` above.
Returns
-------
lcdict
Returns an `lcdict` (this is useable by most astrobase functions for LC
processing).
'''
if picklefile.endswith('.gz'):
infd = gzip.open(picklefile, 'rb')
else:
infd = open(picklefile, 'rb')
try:
with infd:
lcdict = pickle.load(infd)
except UnicodeDecodeError:
with open(picklefile,'rb') as infd:
lcdict = pickle.load(infd, encoding='latin1')
LOGWARNING('pickle %s was probably from Python 2 '
'and failed to load without using "latin1" encoding. '
'This is probably a numpy issue: '
'http://stackoverflow.com/q/11305790' % picklefile)
return lcdict | python | {
"resource": ""
} |
q258799 | filter_kepler_lcdict | validation | def filter_kepler_lcdict(lcdict,
filterflags=True,
nanfilter='sap,pdc',
timestoignore=None):
'''This filters the Kepler `lcdict`, removing nans and bad
observations.
By default, this function removes points in the Kepler LC that have ANY
quality flags set.
Parameters
----------
lcdict : lcdict
An `lcdict` produced by `consolidate_kepler_fitslc` or
`read_kepler_fitslc`.
filterflags : bool
If True, will remove any measurements that have non-zero quality flags
present. This usually indicates an issue with the instrument or
spacecraft.
nanfilter : {'sap','pdc','sap,pdc'}
Indicates the flux measurement type(s) to apply the filtering to.
timestoignore : list of tuples or None
This is of the form::
[(time1_start, time1_end), (time2_start, time2_end), ...]
and indicates the start and end times to mask out of the final
lcdict. Use this to remove anything that wasn't caught by the quality
flags.
Returns
-------
lcdict
Returns an `lcdict` (this is useable by most astrobase functions for LC
processing). The `lcdict` is filtered IN PLACE!
'''
cols = lcdict['columns']
# filter all bad LC points as noted by quality flags
if filterflags:
nbefore = lcdict['time'].size
filterind = lcdict['sap_quality'] == 0
for col in cols:
if '.' in col:
key, subkey = col.split('.')
lcdict[key][subkey] = lcdict[key][subkey][filterind]
else:
lcdict[col] = lcdict[col][filterind]
nafter = lcdict['time'].size
LOGINFO('applied quality flag filter, ndet before = %s, ndet after = %s'
% (nbefore, nafter))
if nanfilter and nanfilter == 'sap,pdc':
notnanind = (
npisfinite(lcdict['sap']['sap_flux']) &
npisfinite(lcdict['pdc']['pdcsap_flux']) &
npisfinite(lcdict['time'])
)
elif nanfilter and nanfilter == 'sap':
notnanind = (
npisfinite(lcdict['sap']['sap_flux']) &
npisfinite(lcdict['time'])
)
elif nanfilter and nanfilter == 'pdc':
notnanind = (
npisfinite(lcdict['pdc']['pdcsap_flux']) &
npisfinite(lcdict['time'])
)
# remove nans from all columns
if nanfilter:
nbefore = lcdict['time'].size
for col in cols:
if '.' in col:
key, subkey = col.split('.')
lcdict[key][subkey] = lcdict[key][subkey][notnanind]
else:
lcdict[col] = lcdict[col][notnanind]
nafter = lcdict['time'].size
LOGINFO('removed nans, ndet before = %s, ndet after = %s'
% (nbefore, nafter))
# exclude all times in timestoignore
if (timestoignore and
isinstance(timestoignore, list) and
len(timestoignore) > 0):
exclind = npfull_like(lcdict['time'], True, dtype=np.bool_)
nbefore = exclind.size
# get all the masks
for ignoretime in timestoignore:
time0, time1 = ignoretime[0], ignoretime[1]
thismask = ~((lcdict['time'] >= time0) & (lcdict['time'] <= time1))
exclind = exclind & thismask
# apply the masks
for col in cols:
if '.' in col:
key, subkey = col.split('.')
lcdict[key][subkey] = lcdict[key][subkey][exclind]
else:
lcdict[col] = lcdict[col][exclind]
nafter = lcdict['time'].size
LOGINFO('removed timestoignore, ndet before = %s, ndet after = %s'
% (nbefore, nafter))
return lcdict | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.