_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | 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'):
| 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')
| 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']
| 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 | 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
| 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):
| 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)):
| 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 | 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.
| 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 = | 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) | 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,
| 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
| 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.
| 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 | 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]
| 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
| 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,
| 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 | 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
| 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
| 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 "
| 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']],
| 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:
| 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 | 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.
'''
| 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 | 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 | 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 | 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 = | 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 | 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'}
'''
| 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
| 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
| 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 | 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'],
| 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
| 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 | 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,
| 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.
| 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
| 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
| 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::
| 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
| 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 '
| 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
| 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
'''
| 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).
| 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:
| 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)
| 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)
| 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 | 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:
| 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 | 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
| 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
| 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
-------
| 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 | 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 | 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
| 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
| 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
| 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
| 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.
| 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.
| 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.
| 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.
| 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.
| 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.
| 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.
| 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.
| 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.
| 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 | 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 | 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
| 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 | 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 | 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()))):
| 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 | 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 | 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 | 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 | 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
| 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
| 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']
| 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 | python | {
"resource": ""
} |
q258786 | StandaloneHandler.initialize | validation | def initialize(self, executor, secret):
'''
This handles initial setup of the `RequestHandler`.
'''
| 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
| 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 | 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. +
| 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]),
| 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) +
| 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`. | 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,
| 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 | 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,
| 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 | 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:
| 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)
| 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']) &
| python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.