INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Collects the configurations for all registered services and writes the appropriate supervisord. conf file. | def deploy_services(self, site=None):
"""
Collects the configurations for all registered services and writes
the appropriate supervisord.conf file.
"""
verbose = self.verbose
r = self.local_renderer
if not r.env.manage_configs:
return
#
# tar... |
Clone a remote Git repository into a new directory. | def clone(self, remote_url, path=None, use_sudo=False, user=None):
"""
Clone a remote Git repository into a new directory.
:param remote_url: URL of the remote repository to clone.
:type remote_url: str
:param path: Path of the working copy directory. Must not exist yet.
... |
Add a remote Git repository into a directory. | def add_remote(self, path, name, remote_url, use_sudo=False, user=None, fetch=True):
"""
Add a remote Git repository into a directory.
:param path: Path of the working copy directory. This directory must exist
and be a Git working copy with a default remote to fetch from.
... |
Fetch changes from the default remote repository. | def fetch(self, path, use_sudo=False, user=None, remote=None):
"""
Fetch changes from the default remote repository.
This will fetch new changesets, but will not update the contents of
the working tree unless yo do a merge or rebase.
:param path: Path of the working copy direct... |
Fetch changes from the default remote repository and merge them. | def pull(self, path, use_sudo=False, user=None, force=False):
"""
Fetch changes from the default remote repository and merge them.
:param path: Path of the working copy directory. This directory must exist
and be a Git working copy with a default remote to pull from.
... |
Retrieves all commit messages for all commits between the given commit numbers on the current branch. | def get_logs_between_commits(self, a, b):
"""
Retrieves all commit messages for all commits between the given commit numbers
on the current branch.
"""
print('REAL')
ret = self.local('git --no-pager log --pretty=oneline %s...%s' % (a, b), capture=True)
if self.ver... |
Retrieves the git commit number of the current head branch. | def get_current_commit(self):
"""
Retrieves the git commit number of the current head branch.
"""
with hide('running', 'stdout', 'stderr', 'warnings'):
s = str(self.local('git rev-parse HEAD', capture=True))
self.vprint('current commit:', s)
return s |
Called after a deployment to record any data necessary to detect changes for a future deployment. | def record_manifest(self):
"""
Called after a deployment to record any data necessary to detect changes
for a future deployment.
"""
manifest = super(GitTrackerSatchel, self).record_manifest()
manifest[CURRENT_COMMIT] = self.get_current_commit()
return manifest |
Get the SSH parameters for connecting to a vagrant VM. | def ssh_config(self, name=''):
"""
Get the SSH parameters for connecting to a vagrant VM.
"""
r = self.local_renderer
with self.settings(hide('running')):
output = r.local('vagrant ssh-config %s' % name, capture=True)
config = {}
for line in output.sp... |
Get the Vagrant version. | def version(self):
"""
Get the Vagrant version.
"""
r = self.local_renderer
with self.settings(hide('running', 'warnings'), warn_only=True):
res = r.local('vagrant --version', capture=True)
if res.failed:
return None
line = res.splitlines()... |
Run the following tasks on a vagrant box. | def vagrant(self, name=''):
"""
Run the following tasks on a vagrant box.
First, you need to import this task in your ``fabfile.py``::
from fabric.api import *
from burlap.vagrant import vagrant
@task
def some_task():
run('echo h... |
Context manager that sets a vagrant VM as the remote host. | def vagrant_settings(self, name='', *args, **kwargs):
"""
Context manager that sets a vagrant VM
as the remote host.
Use this context manager inside a task to run commands
on your current Vagrant box::
from burlap.vagrant import vagrant_settings
with va... |
Get the list of vagrant base boxes | def base_boxes(self):
"""
Get the list of vagrant base boxes
"""
return sorted(list(set([name for name, provider in self._box_list()]))) |
Installs Vagrant from the most recent package available from their homepage. | def install_from_upstream(self):
"""
Installs Vagrant from the most recent package available from their homepage.
"""
from burlap.system import get_arch, distrib_family
r = self.local_renderer
content = urlopen(r.env.download_url).read()
print(len(content))
... |
Get the OS distribution ID. | def distrib_id():
"""
Get the OS distribution ID.
Example::
from burlap.system import distrib_id
if distrib_id() != 'Debian':
abort(u"Distribution is not supported")
"""
with settings(hide('running', 'stdout')):
kernel = (run('uname -s') or '').strip().lower(... |
Get the release number of the distribution. | def distrib_release():
"""
Get the release number of the distribution.
Example::
from burlap.system import distrib_id, distrib_release
if distrib_id() == 'CentOS' and distrib_release() == '6.1':
print(u"CentOS 6.2 has been released. Please upgrade.")
"""
with settings... |
Get the distribution family. | def distrib_family():
"""
Get the distribution family.
Returns one of ``debian``, ``redhat``, ``arch``, ``gentoo``,
``sun``, ``other``.
"""
distrib = (distrib_id() or '').lower()
if distrib in ['debian', 'ubuntu', 'linuxmint', 'elementary os']:
return DEBIAN
elif distrib in ['re... |
Gets the list of supported locales. | def supported_locales():
"""
Gets the list of supported locales.
Each locale is returned as a ``(locale, charset)`` tuple.
"""
family = distrib_family()
if family == 'debian':
return _parse_locales('/usr/share/i18n/SUPPORTED')
elif family == 'arch':
return _parse_locales('/e... |
Forcibly terminates all Celery processes. | def force_stop(self):
"""
Forcibly terminates all Celery processes.
"""
r = self.local_renderer
with self.settings(warn_only=True):
r.sudo('pkill -9 -f celery')
r.sudo('rm -f /tmp/celery*.pid') |
Sets ownership and permissions for Celery - related files. | def set_permissions(self):
"""
Sets ownership and permissions for Celery-related files.
"""
r = self.local_renderer
for path in r.env.paths_owned:
r.env.path_owned = path
r.sudo('chown {celery_daemon_user}:{celery_daemon_user} {celery_path_owned}') |
This is called for each site to render a Celery config file. | def create_supervisor_services(self, site):
"""
This is called for each site to render a Celery config file.
"""
self.vprint('create_supervisor_services:', site)
self.set_site_specifics(site=site)
r = self.local_renderer
if self.verbose:
print('r.en... |
Ensures all tests have passed for this branch. | def check_ok(self):
"""
Ensures all tests have passed for this branch.
This should be called before deployment, to prevent accidental deployment of code
that hasn't passed automated testing.
"""
import requests
if not self.env.check_ok:
return
... |
Returns true if the given host exists on the network. Returns false otherwise. | def is_present(self, host=None):
"""
Returns true if the given host exists on the network.
Returns false otherwise.
"""
r = self.local_renderer
r.env.host = host or self.genv.host_string
ret = r._local("getent hosts {host} | awk '{{ print $1 }}'", capture=True) or... |
Deletes all SSH keys on the localhost associated with the current remote host. | def purge_keys(self):
"""
Deletes all SSH keys on the localhost associated with the current remote host.
"""
r = self.local_renderer
r.env.default_ip = self.hostname_to_ip(self.env.default_hostname)
r.env.home_dir = '/home/%s' % getpass.getuser()
r.local('ssh-keyg... |
Returns the first working combination of username and password for the current host. | def find_working_password(self, usernames=None, host_strings=None):
"""
Returns the first working combination of username and password for the current host.
"""
r = self.local_renderer
if host_strings is None:
host_strings = []
if not host_strings:
... |
Returns true if the host does not exist at the expected location and may need to have its initial configuration set. Returns false if the host exists at the expected location. | def needs_initrole(self, stop_on_error=False):
"""
Returns true if the host does not exist at the expected location and may need
to have its initial configuration set.
Returns false if the host exists at the expected location.
"""
ret = False
target_host_present... |
Called to set default password login for systems that do not yet have passwordless login setup. | def initrole(self, check=True):
"""
Called to set default password login for systems that do not yet have passwordless
login setup.
"""
if self.env.original_user is None:
self.env.original_user = self.genv.user
if self.env.original_key_filename is None:
... |
Yields a list of tuples of the form ( ip hostname ). | def iter_hostnames(self):
"""
Yields a list of tuples of the form (ip, hostname).
"""
from burlap.common import get_hosts_retriever
if self.env.use_retriever:
self.vprint('using retriever')
self.vprint('hosts:', self.genv.hosts)
retriever = get... |
Gets the public IP for a host. | def get_public_ip(self):
"""
Gets the public IP for a host.
"""
r = self.local_renderer
ret = r.run(r.env.get_public_ip_command) or ''
ret = ret.strip()
print('ip:', ret)
return ret |
Assigns a name to the server accessible from user space. | def configure(self, reboot=1):
"""
Assigns a name to the server accessible from user space.
Note, we add the name to /etc/hosts since not all programs use
/etc/hostname to reliably identify the server hostname.
"""
r = self.local_renderer
for ip, hostname in self... |
Run during a deployment. Looks at all commits between now and the last deployment. Finds all ticket numbers and updates their status in Jira. | def update_tickets_from_git(self, from_commit=None, to_commit=None):
"""
Run during a deployment.
Looks at all commits between now and the last deployment.
Finds all ticket numbers and updates their status in Jira.
"""
from jira import JIRA, JIRAError
#from burlap... |
Get a partition list for all disk or for selected device only | def partitions(device=""):
"""
Get a partition list for all disk or for selected device only
Example::
from burlap.disk import partitions
spart = {'Linux': 0x83, 'Swap': 0x82}
parts = partitions()
# parts = {'/dev/sda1': 131, '/dev/sda2': 130, '/dev/sda3': 131}
r ... |
Get a HDD device by uuid | def getdevice_by_uuid(uuid):
"""
Get a HDD device by uuid
Example::
from burlap.disk import getdevice_by_uuid
device = getdevice_by_uuid("356fafdc-21d5-408e-a3e9-2b3f32cb2a8c")
if device:
mount(device,'/mountpoint')
"""
with settings(hide('running', 'warnings',... |
Check if partition is mounted | def ismounted(device):
"""
Check if partition is mounted
Example::
from burlap.disk import ismounted
if ismounted('/dev/sda1'):
print ("disk sda1 is mounted")
"""
# Check filesystem
with settings(hide('running', 'stdout')):
res = run_as_root('mount')
for... |
Run a MySQL query. | def query(query, use_sudo=True, **kwargs):
"""
Run a MySQL query.
"""
func = use_sudo and run_as_root or run
user = kwargs.get('mysql_user') or env.get('mysql_user')
password = kwargs.get('mysql_password') or env.get('mysql_password')
options = [
'--batch',
'--raw',
... |
Check if a MySQL user exists. | def user_exists(name, host='localhost', **kwargs):
"""
Check if a MySQL user exists.
"""
with settings(hide('running', 'stdout', 'stderr', 'warnings'), warn_only=True):
res = query("""
use mysql;
SELECT COUNT(*) FROM user
WHERE User = '%(name)s' AND Host =... |
Create a MySQL user. | def create_user(name, password, host='localhost', **kwargs):
"""
Create a MySQL user.
Example::
import burlap
# Create DB user if it does not exist
if not burlap.mysql.user_exists('dbuser'):
burlap.mysql.create_user('dbuser', password='somerandomstring')
"""
w... |
Check if a MySQL database exists. | def database_exists(name, **kwargs):
"""
Check if a MySQL database exists.
"""
with settings(hide('running', 'stdout', 'stderr', 'warnings'), warn_only=True):
res = query("SHOW DATABASES LIKE '%(name)s';" % {
'name': name
}, **kwargs)
return res.succeeded and (res == nam... |
Create a MySQL database. | def create_database(name, owner=None, owner_host='localhost', charset='utf8',
collate='utf8_general_ci', **kwargs):
"""
Create a MySQL database.
Example::
import burlap
# Create DB if it does not exist
if not burlap.mysql.database_exists('myapp'):
b... |
Retrieves the path to the MySQL configuration file. | def conf_path(self):
"""
Retrieves the path to the MySQL configuration file.
"""
from burlap.system import distrib_id, distrib_release
hostname = self.current_hostname
if hostname not in self._conf_cache:
self.env.conf_specifics[hostname] = self.env.conf_defau... |
Enters the root password prompt entries into the debconf cache so we can set them without user interaction. | def prep_root_password(self, password=None, **kwargs):
"""
Enters the root password prompt entries into the debconf cache
so we can set them without user interaction.
We keep this process separate from set_root_password() because we also need to do
this before installing the bas... |
Drops all views. | def drop_views(self, name=None, site=None):
"""
Drops all views.
"""
r = self.database_renderer
result = r.sudo("mysql --batch -v -h {db_host} "
#"-u {db_root_username} -p'{db_root_password}' "
"-u {db_user} -p'{db_password}' "
"--execute=\"SEL... |
Returns true if a database with the given name exists. False otherwise. | def exists(self, **kwargs):
"""
Returns true if a database with the given name exists. False otherwise.
"""
name = kwargs.pop('name', 'default')
site = kwargs.pop('site', None)
r = self.database_renderer(name=name, site=site)
ret = r.run('mysql -h {db_host} -u {db... |
Restores a database snapshot onto the target database server. | def load(self, dump_fn='', prep_only=0, force_upload=0, from_local=0, name=None, site=None, dest_dir=None, force_host=None):
"""
Restores a database snapshot onto the target database server.
If prep_only=1, commands for preparing the load will be generated,
but not the command to finall... |
Opens a SQL shell to the given database assuming the configured database and user supports this feature. | def shell(self, name='default', site=None, use_root=0, **kwargs):
"""
Opens a SQL shell to the given database, assuming the configured database
and user supports this feature.
"""
r = self.database_renderer(name=name, site=site)
if int(use_root):
kwargs = dic... |
This does a cross - match against the TIC catalog on MAST. | def tic_single_object_crossmatch(ra, dec, radius):
'''This does a cross-match against the TIC catalog on MAST.
Speed tests: about 10 crossmatches per second. (-> 3 hours for 10^5 objects
to crossmatch).
Parameters
----------
ra,dec : np.array
The coordinates to cross match against, al... |
This converts the normalized fluxes in the TESS lcdicts to TESS mags. | def normalized_flux_to_mag(lcdict,
columns=('sap.sap_flux',
'sap.sap_flux_err',
'sap.sap_bkg',
'sap.sap_bkg_err',
'pdc.pdcsap_flux',
... |
Reads TESS Ames - format FITS light curve files. | def get_time_flux_errs_from_Ames_lightcurve(infile,
lctype,
cadence_min=2):
'''Reads TESS Ames-format FITS light curve files.
MIT TOI alerts include Ames lightcurve files. This function gets the finite,
nonzero times, f... |
This extracts the light curve from a single TESS. lc. fits file. | def read_tess_fitslc(lcfits,
headerkeys=LCHEADERKEYS,
datakeys=LCDATAKEYS,
sapkeys=LCSAPKEYS,
pdckeys=LCPDCKEYS,
topkeys=LCTOPKEYS,
apkeys=LCAPERTUREKEYS,
normalize=False,
... |
This consolidates a list of LCs for a single TIC object. | def consolidate_tess_fitslc(lclist,
normalize=True,
filterqualityflags=False,
nanfilter=None,
timestoignore=None,
headerkeys=LCHEADERKEYS,
datakeys=LCDA... |
This filters the provided TESS lcdict removing nans and bad observations. | def filter_tess_lcdict(lcdict,
filterqualityflags=True,
nanfilter='sap,pdc,time',
timestoignore=None,
quiet=False):
'''This filters the provided TESS `lcdict`, removing nans and bad
observations.
By default, this fu... |
This returns the finder chart and object information as a dict. | def _pkl_finder_objectinfo(
objectinfo,
varinfo,
findercmap,
finderconvolve,
sigclip,
normto,
normmingap,
deredden_object=True,
custom_bandpasses=None,
lclistpkl=None,
nbrradiusarcsec=30.0,
maxnumneighbors=5,
plotdpi... |
This returns the periodogram plot PNG as base64 plus info as a dict. | def _pkl_periodogram(lspinfo,
plotdpi=100,
override_pfmethod=None):
'''This returns the periodogram plot PNG as base64, plus info as a dict.
Parameters
----------
lspinfo : dict
This is an lspinfo dict containing results from a period-finding
f... |
This returns the magseries plot PNG as base64 plus arrays as dict. | def _pkl_magseries_plot(stimes, smags, serrs,
plotdpi=100,
magsarefluxes=False):
'''This returns the magseries plot PNG as base64, plus arrays as dict.
Parameters
----------
stimes,smags,serrs : np.array
The mag/flux time-series arrays along with... |
This returns the phased magseries plot PNG as base64 plus info as a dict. | def _pkl_phased_magseries_plot(
checkplotdict,
lspmethod,
periodind,
stimes, smags, serrs,
varperiod, varepoch,
lspmethodind=0,
phasewrap=True,
phasesort=True,
phasebin=0.002,
minbinelems=7,
plotxlim=(-0.8,0.8),
plotdpi=100,... |
Removes a periodic sinusoidal signal generated using whitenparams from the input magnitude time series. | def prewhiten_magseries(times, mags, errs,
whitenperiod,
whitenparams,
sigclip=3.0,
magsarefluxes=False,
plotfit=None,
plotfitphasedlconly=True,
rescale... |
Iterative pre - whitening of a magnitude series using the L - S periodogram. | def gls_prewhiten(times, mags, errs,
fourierorder=3, # 3rd order series to start with
initfparams=None,
startp_gls=None,
endp_gls=None,
stepsize=1.0e-4,
autofreq=True,
sigclip=30.0,
... |
This removes repeating signals in the magnitude time series. | def mask_signal(times, mags, errs,
signalperiod,
signalepoch,
magsarefluxes=False,
maskphases=(0,0,0.5,1.0),
maskphaselength=0.1,
plotfit=None,
plotfitphasedlconly=True,
sigclip=30.0):
'''... |
This launches the server. The current script args are shown below:: | def main():
'''
This launches the server. The current script args are shown below::
Usage: checkplotserver [OPTIONS]
Options:
--help show this help information
checkplotserver.py options:
--assetpath Sets the asset (server ima... |
Finds gaps in the provided time - series and indexes them into groups. | def find_lc_timegroups(lctimes, mingap=4.0):
'''Finds gaps in the provided time-series and indexes them into groups.
This finds the gaps in the provided `lctimes` array, so we can figure out
which times are for consecutive observations and which represent gaps
between seasons or observing eras.
Pa... |
This normalizes the magnitude time - series to a specified value. | def normalize_magseries(times,
mags,
mingap=4.0,
normto='globalmedian',
magsarefluxes=False,
debugmode=False):
'''This normalizes the magnitude time-series to a specified value.
This is used ... |
Sigma - clips a magnitude or flux time - series. | def sigclip_magseries(times, mags, errs,
sigclip=None,
iterative=False,
niterations=None,
meanormedian='median',
magsarefluxes=False):
'''Sigma-clips a magnitude or flux time-series.
Selects the finite... |
Sigma - clips a magnitude or flux time - series and associated measurement arrays. | def sigclip_magseries_with_extparams(times, mags, errs, extparams,
sigclip=None,
iterative=False,
magsarefluxes=False):
'''Sigma-clips a magnitude or flux time-series and associated measurement
arrays.... |
Phases a magnitude/ flux time - series using a given period and epoch. | def phase_magseries(times, mags, period, epoch, wrap=True, sort=True):
'''Phases a magnitude/flux time-series using a given period and epoch.
The equation used is::
phase = (times - epoch)/period - floor((times - epoch)/period)
This phases the given magnitude timeseries using the given period and... |
Bins the given mag/ flux time - series in time using the bin size given. | def time_bin_magseries(times, mags,
binsize=540.0,
minbinelems=7):
'''Bins the given mag/flux time-series in time using the bin size given.
Parameters
----------
times,mags : np.array
The magnitude/flux time-series to bin in time. Non-finite elemen... |
Bins a phased magnitude/ flux time - series using the bin size provided. | def phase_bin_magseries(phases, mags,
binsize=0.005,
minbinelems=7):
'''Bins a phased magnitude/flux time-series using the bin size provided.
Parameters
----------
phases,mags : np.array
The phased magnitude/flux time-series to bin in phase. Non-... |
This fills in gaps in a light curve. | def fill_magseries_gaps(times, mags, errs,
fillgaps=0.0,
sigclip=3.0,
magsarefluxes=False,
filterwindow=11,
forcetimebin=None,
verbose=True):
'''This fills in gaps in a lig... |
Calculate the total SNR of a transit assuming gaussian uncertainties. | def get_snr_of_dip(times,
mags,
modeltimes,
modelmags,
atol_normalization=1e-8,
indsforrms=None,
magsarefluxes=False,
verbose=True,
transitdepth=None,
... |
Using Carter et al. 2009 s estimate calculate the theoretical optimal precision on mid - transit time measurement possible given a transit of a particular SNR. | def estimate_achievable_tmid_precision(snr, t_ingress_min=10,
t_duration_hr=2.14):
'''Using Carter et al. 2009's estimate, calculate the theoretical optimal
precision on mid-transit time measurement possible given a transit of a
particular SNR.
The relation used i... |
Given a BLS period epoch and transit ingress/ egress points ( usually from: py: func: astrobase. periodbase. kbls. bls_stats_singleperiod ) return the times within transit durations + extra_maskfrac of each transit. | def get_transit_times(
blsd,
time,
extra_maskfrac,
trapd=None,
nperiodint=1000
):
'''Given a BLS period, epoch, and transit ingress/egress points (usually
from :py:func:`astrobase.periodbase.kbls.bls_stats_singleperiod`), return
the times within transit durations + `e... |
Gets the transit start middle and end times for transits in a given time - series of observations. | def given_lc_get_transit_tmids_tstarts_tends(
time,
flux,
err_flux,
blsfit_savpath=None,
trapfit_savpath=None,
magsarefluxes=True,
nworkers=1,
sigclip=None,
extra_maskfrac=0.03
):
'''Gets the transit start, middle, and end times for transits in... |
This gets the out - of - transit light curve points. | def given_lc_get_out_of_transit_points(
time, flux, err_flux,
blsfit_savpath=None,
trapfit_savpath=None,
in_out_transit_savpath=None,
sigclip=None,
magsarefluxes=True,
nworkers=1,
extra_maskfrac=0.03
):
'''This gets the out-of-transit light curve point... |
This just compresses the sqlitecurve. Should be independent of OS. | def _pycompress_sqlitecurve(sqlitecurve, force=False):
'''This just compresses the sqlitecurve. Should be independent of OS.
'''
outfile = '%s.gz' % sqlitecurve
try:
if os.path.exists(outfile) and not force:
os.remove(sqlitecurve)
return outfile
else:
... |
This just uncompresses the sqlitecurve. Should be independent of OS. | def _pyuncompress_sqlitecurve(sqlitecurve, force=False):
'''This just uncompresses the sqlitecurve. Should be independent of OS.
'''
outfile = sqlitecurve.replace('.gz','')
try:
if os.path.exists(outfile) and not force:
return outfile
else:
with gzip.open(sq... |
This just compresses the sqlitecurve in gzip format. | def _gzip_sqlitecurve(sqlitecurve, force=False):
'''This just compresses the sqlitecurve in gzip format.
FIXME: this doesn't work with gzip < 1.6 or non-GNU gzip (probably).
'''
# -k to keep the input file just in case something explodes
if force:
cmd = 'gzip -k -f %s' % sqlitecurve
e... |
This just uncompresses the sqlitecurve in gzip format. | def _gunzip_sqlitecurve(sqlitecurve):
'''This just uncompresses the sqlitecurve in gzip format.
FIXME: this doesn't work with gzip < 1.6 or non-GNU gzip (probably).
'''
# -k to keep the input .gz just in case something explodes
cmd = 'gunzip -k %s' % sqlitecurve
try:
subprocess.check... |
This validates the sqlitecurve filter string. | def _validate_sqlitecurve_filters(filterstring, lccolumns):
'''This validates the sqlitecurve filter string.
This MUST be valid SQL but not contain any commands.
'''
# first, lowercase, then _squeeze to single spaces
stringelems = _squeeze(filterstring).lower()
# replace shady characters
... |
This reads a HAT sqlitecurve and optionally filters it. | def read_and_filter_sqlitecurve(lcfile,
columns=None,
sqlfilters=None,
raiseonfail=False,
returnarrays=True,
forcerecompress=False,
... |
This describes the light curve object and columns present. | def describe(lcdict, returndesc=False, offsetwith=None):
'''This describes the light curve object and columns present.
Parameters
----------
lcdict : dict
The input lcdict to parse for column and metadata info.
returndesc : bool
If True, returns the description string as an str in... |
This just tries to apply the caster function to castee. | def _smartcast(castee, caster, subval=None):
'''
This just tries to apply the caster function to castee.
Returns None on failure.
'''
try:
return caster(castee)
except Exception as e:
if caster is float or caster is int:
return nan
elif caster is str:
... |
This parses the CSV header from the CSV HAT sqlitecurve. | 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... |
This parses the header of the LCC CSV V1 LC format. | 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 i... |
This reads a CSV LC produced by an LCC - Server <https:// github. com/ waqasbhatti/ lcc - server > _ instance. | def read_lcc_csvlc(lcfile):
'''This reads a CSV LC produced by an `LCC-Server
<https://github.com/waqasbhatti/lcc-server>`_ instance.
Parameters
----------
lcfile : str
The LC file to read.
Returns
-------
dict
Returns an lcdict that's readable by most astrobase funct... |
This describes the LCC CSV format light curve file. | 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 ju... |
This reads a HAT data server or LCC - Server produced CSV light curve into an lcdict. | 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... |
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. | 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... |
This normalizes magcols in lcdict using timecol to find timegroups. | def normalize_lcdict(lcdict,
timecol='rjd',
magcols='all',
mingap=4.0,
normto='sdssr',
debugmode=False,
quiet=False):
'''This normalizes magcols in `lcdict` using `timecol` to find timegroup... |
This is a function to normalize light curves across all instrument combinations present. | def normalize_lcdict_byinst(
lcdict,
magcols='all',
normto='sdssr',
normkeylist=('stf','ccd','flt','fld','prj','exp'),
debugmode=False,
quiet=False
):
'''This is a function to normalize light curves across all instrument
combinations present.
Use this to norm... |
This is called when we re executed from the commandline. | 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 ... |
Calculates object coordinates features including: | def coord_features(objectinfo):
'''Calculates object coordinates features, including:
- galactic coordinates
- total proper motion from pmra, pmdecl
- reduced J proper motion from propermotion and Jmag
Parameters
----------
objectinfo : dict
This is an objectinfo dict from a ligh... |
Stellar colors and dereddened stellar colors using 2MASS DUST API: | def color_features(in_objectinfo,
deredden=True,
custom_bandpasses=None,
dust_timeout=10.0):
'''Stellar colors and dereddened stellar colors using 2MASS DUST API:
http://irsa.ipac.caltech.edu/applications/DUST/docs/dustProgramInterface.html
Paramete... |
This calculates the M - dwarf subtype given SDSS r - i and i - z colors. | 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
-------... |
This calculates rough star type classifications based on star colors in the ugrizJHK bands. | def color_classification(colorfeatures, pmfeatures):
'''This calculates rough star type classifications based on star colors
in the ugrizJHK bands.
Uses the output from `color_features` and `coord_features`. By default,
`color_features` will use dereddened colors, as are expected by most
relations ... |
Gets several neighbor GAIA and SIMBAD features: | def neighbor_gaia_features(objectinfo,
lclist_kdtree,
neighbor_radius_arcsec,
gaia_matchdist_arcsec=3.0,
verbose=True,
gaia_submit_timeout=10.0,
gaia_submit_t... |
This applies external parameter decorrelation ( EPD ) to a light curve. | def apply_epd_magseries(lcfile,
timecol,
magcol,
errcol,
externalparams,
lcformat='hat-sql',
lcformatdir=None,
epdsmooth_sigclip=3.0,
... |
This is a parallel worker for the function below. | def parallel_epd_worker(task):
'''This is a parallel worker for the function below.
Parameters
----------
task : tuple
- task[0] = lcfile
- task[1] = timecol
- task[2] = magcol
- task[3] = errcol
- task[4] = externalparams
- task[5] = lcformat
- ... |
This applies EPD in parallel to all LCs in the input list. | def parallel_epd_lclist(lclist,
externalparams,
timecols=None,
magcols=None,
errcols=None,
lcformat='hat-sql',
lcformatdir=None,
epdsmooth_sigclip=3.0,
... |
This applies EPD in parallel to all LCs in a directory. | 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,... |
Runs the Box Least Squares Fitting Search for transit - shaped signals. | def bls_serial_pfind(times, mags, errs,
magsarefluxes=False,
startp=0.1, # search from 0.1 d to...
endp=100.0, # ... 100.0 d -- don't search full timebase
stepsize=5.0e-4,
mintransitduration=0.01, # minimum trans... |
This wraps Astropy s BoxLeastSquares for use with bls_parallel_pfind below. | 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] = ste... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.