INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Return the first preferences object for the current site. If preferences do not exist create it. | def get_queryset(self):
"""
Return the first preferences object for the current site.
If preferences do not exist create it.
"""
queryset = super(SingletonManager, self).get_queryset()
# Get current site
current_site = None
if getattr(settings, 'SITE_ID'... |
Load an iterable. | def load_iterable(self, iterable, session=None):
'''Load an ``iterable``.
By default it returns a generator of data loaded via the
:meth:`loads` method.
:param iterable: an iterable over data to load.
:param session: Optional :class:`stdnet.odm.Session`.
:return: an ite... |
Implements: meth: stdnet. odm. SearchEngine. search_model. It return a new: class: stdnet. odm. QueryElem instance from the input: class: Query and the * text * to search. | def search_model(self, q, text, lookup=None):
'''Implements :meth:`stdnet.odm.SearchEngine.search_model`.
It return a new :class:`stdnet.odm.QueryElem` instance from
the input :class:`Query` and the *text* to search.'''
words = self.words_from_text(text, for_search=True)
if not words:
... |
Full text search. Return a list of queries to intersect. | def _search(self, words, include=None, exclude=None, lookup=None):
'''Full text search. Return a list of queries to intersect.'''
lookup = lookup or 'contains'
query = self.router.worditem.query()
if include:
query = query.filter(model_type__in=include)
if exclu... |
Get a new redis client. | def redis_client(address=None, connection_pool=None, timeout=None,
parser=None, **kwargs):
'''Get a new redis client.
:param address: a ``host``, ``port`` tuple.
:param connection_pool: optional connection pool.
:param timeout: socket timeout.
:param timeout: socket timeout.
''... |
Returns a bytestring version of s encoded as specified in encoding. | def to_bytes(s, encoding=None, errors='strict'):
"""Returns a bytestring version of 's',
encoded as specified in 'encoding'."""
encoding = encoding or 'utf-8'
if isinstance(s, bytes):
if encoding != 'utf-8':
return s.decode('utf-8', errors).encode(encoding, errors)
else:
... |
Inverse of to_bytes | def to_string(s, encoding=None, errors='strict'):
"""Inverse of to_bytes"""
encoding = encoding or 'utf-8'
if isinstance(s, bytes):
return s.decode(encoding, errors)
if not is_string(s):
s = string_type(s)
return s |
The default JSON decoder hook. It is the inverse of: class: stdnet. utils. jsontools. JSONDateDecimalEncoder. | def date_decimal_hook(dct):
'''The default JSON decoder hook. It is the inverse of
:class:`stdnet.utils.jsontools.JSONDateDecimalEncoder`.'''
if '__datetime__' in dct:
return todatetime(dct['__datetime__'])
elif '__date__' in dct:
return todatetime(dct['__date__']).date()
elif '__decimal... |
Convert a flat representation of a dictionary to a nested representation. Fields in the flat representation are separated by the * splitter * parameters. | def flat_to_nested(data, instance=None, attname=None,
separator=None, loads=None):
'''Convert a flat representation of a dictionary to
a nested representation. Fields in the flat representation are separated
by the *splitter* parameters.
:parameter data: a flat dictionary of key value pairs.
:pa... |
Convert a nested dictionary into a flat dictionary representation | def dict_flat_generator(value, attname=None, splitter=JSPLITTER,
dumps=None, prefix=None, error=ValueError,
recursive=True):
'''Convert a nested dictionary into a flat dictionary representation'''
if not isinstance(value, dict) or not recursive:
if not pre... |
Multiply dictionaries by a numeric values and add them together. | def addmul_number_dicts(series):
'''Multiply dictionaries by a numeric values and add them together.
:parameter series: a tuple of two elements tuples. Each serie is of the form::
(weight,dictionary)
where ``weight`` is a number and ``dictionary`` is a dictionary with
numeric values.
:parameter s... |
Submits a cluster job to the build queue to download all TPFs for a given campaign. | def Download(campaign=0, queue='build', email=None, walltime=8, **kwargs):
'''
Submits a cluster job to the build queue to download all TPFs for a given
campaign.
:param int campaign: The `K2` campaign to run
:param str queue: The name of the queue to submit to. Default `build`
:param str email... |
Download all stars from a given campaign. This is called from missions/ k2/ download. pbs | def _Download(campaign, subcampaign):
'''
Download all stars from a given campaign. This is
called from ``missions/k2/download.pbs``
'''
# Are we doing a subcampaign?
if subcampaign != -1:
campaign = campaign + 0.1 * subcampaign
# Get all star IDs for this campaign
stars = [s[0... |
Submits a cluster job to compute and plot data for all targets in a given campaign. | def Run(campaign=0, EPIC=None, nodes=5, ppn=12, walltime=100,
mpn=None, email=None, queue=None, **kwargs):
'''
Submits a cluster job to compute and plot data for all targets
in a given campaign.
:param campaign: The K2 campaign number. If this is an :py:class:`int`, \
returns all tar... |
The actual function that publishes a given campaign ; this must be called from missions/ k2/ publish. pbs. | def _Publish(campaign, subcampaign, strkwargs):
'''
The actual function that publishes a given campaign; this must
be called from ``missions/k2/publish.pbs``.
'''
# Get kwargs from string
kwargs = pickle.loads(strkwargs.replace('%%%', '\n').encode('utf-8'))
# Check the cadence
cadence... |
Shows the progress of the de - trending runs for the specified campaign ( s ). | def Status(season=range(18), model='nPLD', purge=False, injection=False,
cadence='lc', **kwargs):
'''
Shows the progress of the de-trending runs for the specified campaign(s).
'''
# Mission compatibility
campaign = season
# Injection?
if injection:
return InjectionStatu... |
Shows the progress of the injection de - trending runs for the specified campaign ( s ). | def InjectionStatus(campaign=range(18), model='nPLD', purge=False,
depths=[0.01, 0.001, 0.0001], **kwargs):
'''
Shows the progress of the injection de-trending runs for
the specified campaign(s).
'''
if not hasattr(campaign, '__len__'):
if type(campaign) is int:
... |
A wrapper around an: py: obj: everest model for PBS runs. | def EverestModel(ID, model='nPLD', publish=False, csv=False, **kwargs):
'''
A wrapper around an :py:obj:`everest` model for PBS runs.
'''
if model != 'Inject':
from ... import detrender
# HACK: We need to explicitly mask short cadence planets
if kwargs.get('cadence', 'lc') == ... |
Construct the primary HDU file containing basic header info. | def PrimaryHDU(model):
'''
Construct the primary HDU file containing basic header info.
'''
# Get mission cards
cards = model._mission.HDUCards(model.meta, hdu=0)
if 'KEPMAG' not in [c[0] for c in cards]:
cards.append(('KEPMAG', model.mag, 'Kepler magnitude'))
# Add EVEREST info
... |
Construct the data HDU file containing the arrays and the observing info. | def LightcurveHDU(model):
'''
Construct the data HDU file containing the arrays and the observing info.
'''
# Get mission cards
cards = model._mission.HDUCards(model.meta, hdu=1)
# Add EVEREST info
cards.append(('COMMENT', '************************'))
cards.append(('COMMENT', '* E... |
Construct the HDU containing the pixel - level light curve. | def PixelsHDU(model):
'''
Construct the HDU containing the pixel-level light curve.
'''
# Get mission cards
cards = model._mission.HDUCards(model.meta, hdu=2)
# Add EVEREST info
cards = []
cards.append(('COMMENT', '************************'))
cards.append(('COMMENT', '* EVERES... |
Construct the HDU containing the aperture used to de - trend. | def ApertureHDU(model):
'''
Construct the HDU containing the aperture used to de-trend.
'''
# Get mission cards
cards = model._mission.HDUCards(model.meta, hdu=3)
# Add EVEREST info
cards.append(('COMMENT', '************************'))
cards.append(('COMMENT', '* EVEREST INFO ... |
Construct the HDU containing sample postage stamp images of the target. | def ImagesHDU(model):
'''
Construct the HDU containing sample postage stamp images of the target.
'''
# Get mission cards
cards = model._mission.HDUCards(model.meta, hdu=4)
# Add EVEREST info
cards.append(('COMMENT', '************************'))
cards.append(('COMMENT', '* EVEREST... |
Construct the HDU containing the hi res image of the target. | def HiResHDU(model):
'''
Construct the HDU containing the hi res image of the target.
'''
# Get mission cards
cards = model._mission.HDUCards(model.meta, hdu=5)
# Add EVEREST info
cards.append(('COMMENT', '************************'))
cards.append(('COMMENT', '* EVEREST INFO *'... |
Generate a FITS file for a given: py: mod: everest run. | def MakeFITS(model, fitsfile=None):
'''
Generate a FITS file for a given :py:mod:`everest` run.
:param model: An :py:mod:`everest` model instance
'''
# Get the fits file name
if fitsfile is None:
outfile = os.path.join(model.dir, model._mission.FITSFile(
model.ID, model.se... |
Retrieve a serializer register as * name *. If the serializer is not available a ValueError exception will raise. A common usage pattern:: qs = MyModel. objects. query (). sort_by ( id ) s = odm. get_serializer ( json ) s. dump ( qs ) | def get_serializer(name, **options):
'''Retrieve a serializer register as *name*. If the serializer is not
available a ``ValueError`` exception will raise.
A common usage pattern::
qs = MyModel.objects.query().sort_by('id')
s = odm.get_serializer('json')
s.dump(qs)
'''
if name in _serializ... |
\ Register a new serializer to the library.: parameter name: serializer name ( it can override existing serializers ).: parameter serializer: an instance or a derived class of a: class: stdnet. odm. Serializer class or a callable. | def register_serializer(name, serializer):
'''\
Register a new serializer to the library.
:parameter name: serializer name (it can override existing serializers).
:parameter serializer: an instance or a derived class of a
:class:`stdnet.odm.Serializer` class or a callable.
'''
if not isclass(serial... |
Finds the solution x to the linear problem A x = b for all contiguous w - sized masks applied to the rows and columns of A and to the entries of b. Returns an array X of shape ( N - w + 1 N - w ) where the nth row is the solution to the equation A [ ! [ n n + w ) ] x = b [ ! [ n n + w ) ] where ! [ n n + w ) indicates ... | def MaskSolve(A, b, w=5, progress=True, niter=None):
'''
Finds the solution `x` to the linear problem
A x = b
for all contiguous `w`-sized masks applied to
the rows and columns of `A` and to the entries
of `b`.
Returns an array `X` of shape `(N - w + 1, N - w)`,
where t... |
Identical to MaskSolve but computes the solution the brute - force way. | def MaskSolveSlow(A, b, w=5, progress=True, niter=None):
'''
Identical to `MaskSolve`, but computes the solution
the brute-force way.
'''
# Number of data points
N = b.shape[0]
# How many iterations? Default is to go through
# the entire dataset
if niter is None:
... |
Return the unmasked overfitting metric for a given transit depth. | def unmasked(self, depth=0.01):
"""Return the unmasked overfitting metric for a given transit depth."""
return 1 - (np.hstack(self._O2) +
np.hstack(self._O3) / depth) / np.hstack(self._O1) |
Show the overfitting PDF summary. | def show(self):
"""Show the overfitting PDF summary."""
try:
if platform.system().lower().startswith('darwin'):
subprocess.call(['open', self.pdf])
elif os.name == 'nt':
os.startfile(self.pdf)
elif os.name == 'posix':
su... |
Return the current observing season. | def season(self):
"""
Return the current observing season.
For *K2*, this is the observing campaign, while for *Kepler*,
it is the current quarter.
"""
try:
self._season
except AttributeError:
self._season = self._mission.Season(self.ID)
... |
The CBV - corrected de - trended flux. | def fcor(self):
'''
The CBV-corrected de-trended flux.
'''
if self.XCBV is None:
return None
else:
return self.flux - self._mission.FitCBVs(self) |
The array of indices to be masked. This is the union of the sets of outliers bad ( flagged ) cadences transit cadences and: py: obj: NaN cadences. | def mask(self):
'''
The array of indices to be masked. This is the union of the sets of
outliers, bad (flagged) cadences, transit cadences, and :py:obj:`NaN`
cadences.
'''
return np.array(list(set(np.concatenate([self.outmask, self.badmask,
self.... |
Computes the design matrix at the given * PLD * order and the given indices. The columns are the * PLD * vectors for the target at the corresponding order computed as the product of the fractional pixel flux of all sets of: py: obj: n pixels where: py: obj: n is the * PLD * order. | def X(self, i, j=slice(None, None, None)):
'''
Computes the design matrix at the given *PLD* order and the given
indices. The columns are the *PLD* vectors for the target at the
corresponding order, computed as the product of the fractional pixel
flux of all sets of :py:obj:`n` p... |
Plots miscellaneous de - trending information on the data validation summary figure. | def plot_info(self, dvs):
'''
Plots miscellaneous de-trending information on the data
validation summary figure.
:param dvs: A :py:class:`dvs.DVS` figure instance
'''
axl, axc, axr = dvs.title()
axc.annotate("%s %d" % (self._mission.IDSTRING, self.ID),
... |
Compute the model for the current value of lambda. | def compute(self):
'''
Compute the model for the current value of lambda.
'''
# Is there a transit model?
if self.transit_model is not None:
return self.compute_joint()
log.info('Computing the model...')
# Loop over all chunks
model = [None... |
Compute the model in a single step allowing for a light curve - wide transit model. This is a bit more expensive to compute. | def compute_joint(self):
'''
Compute the model in a single step, allowing for a light curve-wide
transit model. This is a bit more expensive to compute.
'''
# Init
log.info('Computing the joint model...')
A = [None for b in self.breakpoints]
B = [None fo... |
Returns the outlier mask an array of indices corresponding to the non - outliers. | def apply_mask(self, x=None):
'''
Returns the outlier mask, an array of indices corresponding to the
non-outliers.
:param numpy.ndarray x: If specified, returns the masked version of \
:py:obj:`x` instead. Default :py:obj:`None`
'''
if x is None:
... |
Returns the indices corresponding to a given light curve chunk. | def get_chunk(self, b, x=None, pad=True):
'''
Returns the indices corresponding to a given light curve chunk.
:param int b: The index of the chunk to return
:param numpy.ndarray x: If specified, applies the mask to array \
:py:obj:`x`. Default :py:obj:`None`
'''
... |
Computes the PLD weights vector: py: obj: w. | def get_weights(self):
'''
Computes the PLD weights vector :py:obj:`w`.
..warning :: Deprecated and not thoroughly tested.
'''
log.info("Computing PLD weights...")
# Loop over all chunks
weights = [None for i in range(len(self.breakpoints))]
for b, brk... |
Returns the CDPP value in * ppm * for each of the chunks in the light curve. | def get_cdpp_arr(self, flux=None):
'''
Returns the CDPP value in *ppm* for each of the
chunks in the light curve.
'''
if flux is None:
flux = self.flux
return np.array([self._mission.CDPP(flux[self.get_masked_chunk(b)],
cadence=self.c... |
Returns the scalar CDPP for the light curve. | def get_cdpp(self, flux=None):
'''
Returns the scalar CDPP for the light curve.
'''
if flux is None:
flux = self.flux
return self._mission.CDPP(self.apply_mask(flux), cadence=self.cadence) |
Plots the aperture and the pixel images at the beginning middle and end of the time series. Also plots a high resolution image of the target if available. | def plot_aperture(self, axes, labelsize=8):
'''
Plots the aperture and the pixel images at the beginning, middle,
and end of the time series. Also plots a high resolution image of
the target, if available.
'''
log.info('Plotting the aperture...')
# Get colormap... |
r Compute the masked & unmasked overfitting metrics for the light curve. | def overfit(self, tau=None, plot=True, clobber=False, w=9, **kwargs):
r"""
Compute the masked & unmasked overfitting metrics for the light curve.
This routine injects a transit model given by `tau` at every cadence
in the light curve and recovers the transit depth when (1) leaving
... |
r Return the likelihood of the astrophysical model model. | def lnlike(self, model, refactor=False, pos_tol=2.5, neg_tol=50.,
full_output=False):
r"""
Return the likelihood of the astrophysical model `model`.
Returns the likelihood of `model` marginalized over the PLD model.
:param ndarray model: A vector of the same shape as `se... |
Run one of the: py: obj: everest models with injected transits and attempt to recover the transit depth at the end with a simple linear regression with a polynomial baseline. The depth is stored in the: py: obj: inject attribute of the model ( a dictionary ) as: py: obj: rec_depth. A control injection is also performed... | def Inject(ID, inj_model='nPLD', t0=None, per=None, dur=0.1, depth=0.001,
mask=False, trn_win=5, poly_order=3, make_fits=False, **kwargs):
'''
Run one of the :py:obj:`everest` models with injected transits and attempt
to recover the transit depth at the end with a simple linear regression
wit... |
Instance of: attr: model_type with id: attr: object_id. | def object(self, session):
'''Instance of :attr:`model_type` with id :attr:`object_id`.'''
if not hasattr(self, '_object'):
pkname = self.model_type._meta.pkname()
query = session.query(self.model_type).filter(**{pkname:
... |
Returns a: py: obj: DataContainer instance with the raw data for the target.: param int ID: The target ID number: param int season: The observing season. Default: py: obj: None: param str cadence: The light curve cadence. Default lc: param bool clobber: Overwrite existing files? Default: py: obj: False: param bool dele... | def GetData(ID, season = None, cadence = 'lc', clobber = False, delete_raw = False,
aperture_name = None, saturated_aperture_name = None,
max_pixels = None, download_only = False, saturation_tolerance = None,
bad_bits = None, **kwargs):
'''
Returns a :py:obj:`DataContainer` ins... |
Return neighbors random bright stars on the same module as EPIC.: param int ID: The target ID number: param str model: The: py: obj: everest model name. Only used when imposing CDPP bounds. Default: py: obj: None: param int neighbors: Number of neighbors to return. Default None: param str aperture_name: The name of the... | def GetNeighbors(ID, model = None, neighbors = None, mag_range = None,
cdpp_range = None, aperture_name = None,
cadence = 'lc', **kwargs):
'''
Return `neighbors` random bright stars on the same module as `EPIC`.
:param int ID: The target ID number
:param str model: The :py... |
Returns the time and flux for a given EPIC ID and a given pipeline name. | def get(ID, pipeline='everest2', campaign=None):
'''
Returns the `time` and `flux` for a given EPIC `ID` and
a given `pipeline` name.
'''
log.info('Downloading %s light curve for %d...' % (pipeline, ID))
# Dev version hack
if EVEREST_DEV:
if pipeline.lower() == 'everest2' or pipel... |
Plots the de - trended flux for the given EPIC ID and for the specified pipeline. | def plot(ID, pipeline='everest2', show=True, campaign=None):
'''
Plots the de-trended flux for the given EPIC `ID` and for
the specified `pipeline`.
'''
# Get the data
time, flux = get(ID, pipeline=pipeline, campaign=campaign)
# Remove nans
mask = np.where(np.isnan(flux))[0]
time ... |
Computes the CDPP for a given campaign and a given pipeline. Stores the results in a file under/ missions/ k2/ tables/. | def get_cdpp(campaign, pipeline='everest2'):
'''
Computes the CDPP for a given `campaign` and a given `pipeline`.
Stores the results in a file under "/missions/k2/tables/".
'''
# Imports
from .k2 import CDPP
from .utils import GetK2Campaign
# Check pipeline
assert pipeline.lower()... |
Computes the number of outliers for a given campaign and a given pipeline. Stores the results in a file under/ missions/ k2/ tables/. | def get_outliers(campaign, pipeline='everest2', sigma=5):
'''
Computes the number of outliers for a given `campaign`
and a given `pipeline`.
Stores the results in a file under "/missions/k2/tables/".
:param int sigma: The sigma level at which to clip outliers. Default 5
'''
# Imports
... |
Returns the name of the current: py: class: Detrender subclass. | def name(self):
'''
Returns the name of the current :py:class:`Detrender` subclass.
'''
if self.cadence == 'lc':
return self.__class__.__name__
else:
return '%s.sc' % self.__class__.__name__ |
Pre - compute the matrices: py: obj: A and: py: obj: B ( cross - validation step only ) for chunk: py: obj: b. | def cv_precompute(self, mask, b):
'''
Pre-compute the matrices :py:obj:`A` and :py:obj:`B`
(cross-validation step only)
for chunk :py:obj:`b`.
'''
# Get current chunk and mask outliers
m1 = self.get_masked_chunk(b)
flux = self.fraw[m1]
K = GetCov... |
Compute the model ( cross - validation step only ) for chunk: py: obj: b. | def cv_compute(self, b, A, B, C, mK, f, m1, m2):
'''
Compute the model (cross-validation step only) for chunk :py:obj:`b`.
'''
A = np.sum([l * a for l, a in zip(self.lam[b], A)
if l is not None], axis=0)
B = np.sum([l * b for l, b in zip(self.lam[b], B)
... |
Performs iterative sigma clipping to get outliers. | def get_outliers(self):
'''
Performs iterative sigma clipping to get outliers.
'''
log.info("Clipping outliers...")
log.info('Iter %d/%d: %d outliers' %
(0, self.oiter, len(self.outmask)))
def M(x): return np.delete(x, np.concatenate(
[self... |
Returns the index of: py: attr: self. lambda_arr that minimizes the validation scatter in the segment with minimum at the lowest value of: py: obj: lambda with fractional tolerance: py: attr: self. leps. | def optimize_lambda(self, validation):
'''
Returns the index of :py:attr:`self.lambda_arr` that minimizes the
validation scatter in the segment with minimum at the lowest value
of :py:obj:`lambda`, with
fractional tolerance :py:attr:`self.leps`.
:param numpy.ndarray vali... |
Cross - validate to find the optimal value of: py: obj: lambda. | def cross_validate(self, ax, info=''):
'''
Cross-validate to find the optimal value of :py:obj:`lambda`.
:param ax: The current :py:obj:`matplotlib.pyplot` axis instance to \
plot the cross-validation results.
:param str info: The label to show in the bottom right-hand co... |
Computes the ideal y - axis limits for the light curve plot. Attempts to set the limits equal to those of the raw light curve but if more than 1% of the flux lies either above or below these limits auto - expands to include those points. At the end adds 5% padding to both the top and the bottom. | def get_ylim(self):
'''
Computes the ideal y-axis limits for the light curve plot. Attempts to
set the limits equal to those of the raw light curve, but if more than
1% of the flux lies either above or below these limits, auto-expands
to include those points. At the end, adds 5% ... |
Plots the current light curve. This is called at several stages to plot the de - trending progress as a function of the different * PLD * orders. | def plot_lc(self, ax, info_left='', info_right='', color='b'):
'''
Plots the current light curve. This is called at several stages to
plot the de-trending progress as a function of the different
*PLD* orders.
:param ax: The current :py:obj:`matplotlib.pyplot` axis instance
... |
Plots the final de - trended light curve. | def plot_final(self, ax):
'''
Plots the final de-trended light curve.
'''
# Plot the light curve
bnmask = np.array(
list(set(np.concatenate([self.badmask, self.nanmask]))), dtype=int)
def M(x): return np.delete(x, bnmask)
if (self.cadence == 'lc') o... |
Plots the final CBV - corrected light curve. | def plot_cbv(self, ax, flux, info, show_cbv=False):
'''
Plots the final CBV-corrected light curve.
'''
# Plot the light curve
bnmask = np.array(
list(set(np.concatenate([self.badmask, self.nanmask]))), dtype=int)
def M(x): return np.delete(x, bnmask)
... |
Loads the target pixel file. | def load_tpf(self):
'''
Loads the target pixel file.
'''
if not self.loaded:
if self._data is not None:
data = self._data
else:
data = self._mission.GetData(
self.ID, season=self.season,
... |
Loads a saved version of the model. | def load_model(self, name=None):
'''
Loads a saved version of the model.
'''
if self.clobber:
return False
if name is None:
name = self.name
file = os.path.join(self.dir, '%s.npz' % name)
if os.path.exists(file):
if not self.... |
Saves all of the de - trending information to disk in an npz file and saves the DVS as a pdf. | def save_model(self):
'''
Saves all of the de-trending information to disk in an `npz` file
and saves the DVS as a `pdf`.
'''
# Save the data
log.info("Saving data to '%s.npz'..." % self.name)
d = dict(self.__dict__)
d.pop('_weights', None)
d.pop... |
A custom exception handler. | def exception_handler(self, pdb):
'''
A custom exception handler.
:param pdb: If :py:obj:`True`, enters PDB post-mortem \
mode for debugging.
'''
# Grab the exception
exctype, value, tb = sys.exc_info()
# Log the error and create a .err file
... |
Calls: py: func: gp. GetKernelParams to optimize the GP and obtain the covariance matrix for the regression. | def update_gp(self):
'''
Calls :py:func:`gp.GetKernelParams` to optimize the GP and obtain the
covariance matrix for the regression.
'''
self.kernel_params = GetKernelParams(self.time, self.flux,
self.fraw_err,
... |
Initializes the covariance matrix with a guess at the GP kernel parameters. | def init_kernel(self):
'''
Initializes the covariance matrix with a guess at
the GP kernel parameters.
'''
if self.kernel_params is None:
X = self.apply_mask(self.fpix / self.flux.reshape(-1, 1))
y = self.apply_mask(self.flux) - np.dot(X, np.linalg.solve... |
Runs the de - trending step. | def run(self):
'''
Runs the de-trending step.
'''
try:
# Load raw data
log.info("Loading target data...")
self.load_tpf()
self.mask_planets()
self.plot_aperture([self.dvs.top_right() for i in range(4)])
self.init_... |
Correct the light curve with the CBVs generate a cover page for the DVS figure and produce a FITS file for publication. | def publish(self, **kwargs):
'''
Correct the light curve with the CBVs, generate a
cover page for the DVS figure,
and produce a FITS file for publication.
'''
try:
# HACK: Force these params for publication
self.cbv_win = 999
self.cb... |
This is called during production de - trending prior to calling the: py: obj: Detrender. run () method. | def setup(self, **kwargs):
'''
This is called during production de-trending, prior to
calling the :py:obj:`Detrender.run()` method.
:param tuple cdpp_range: If :py:obj:`parent_model` is set, \
neighbors are selected only if \
their de-trended CDPPs fall wit... |
This is called during production de - trending prior to calling the: py: obj: Detrender. run () method. | def setup(self, **kwargs):
'''
This is called during production de-trending, prior to
calling the :py:obj:`Detrender.run()` method.
:param str parent_model: The name of the model to operate on. \
Default `nPLD`
'''
# Load the parent model
self.pa... |
This is called during production de - trending prior to calling the: py: obj: Detrender. run () method. | def setup(self, **kwargs):
'''
This is called during production de-trending, prior to
calling the :py:obj:`Detrender.run()` method.
:param inter piter: The number of iterations in the minimizer. \
Default 3
:param int pmaxf: The maximum number of function evaluati... |
Runs the de - trending. | def run(self):
'''
Runs the de-trending.
'''
try:
# Plot original
self.plot_aperture([self.dvs.top_right() for i in range(4)])
self.plot_lc(self.dvs.left(), info_right='nPLD', color='k')
# Cross-validate
self.cross_validate(... |
Performs the cross - validation step. | def cross_validate(self, ax):
'''
Performs the cross-validation step.
'''
# The CDPP to beat
cdpp_opt = self.get_cdpp_arr()
# Loop over all chunks
for b, brkpt in enumerate(self.breakpoints):
log.info("Cross-validating chunk %d/%d..." %
... |
Computes the scatter in the validation set. | def validation_scatter(self, log_lam, b, masks, pre_v, gp, flux,
time, med):
'''
Computes the scatter in the validation set.
'''
# Update the lambda matrix
self.lam[b] = 10 ** log_lam
# Validation set scatter
scatter = [None for i in ... |
Utility function for populating lists with random data. Useful for populating database with data for fuzzy testing. Supported data - types * * string * For example:: populate ( string 100 min_len = 3 max_len = 10 ) create a 100 elements list with random strings with random length between 3 and 10 * * date * For example... | def populate(datatype='string', size=10, start=None, end=None,
converter=None, choice_from=None, **kwargs):
'''Utility function for populating lists with random data.
Useful for populating database with data for fuzzy testing.
Supported data-types
* *string*
For example::
populat... |
NOTE: pos_tol is the positive ( i. e. above the median ) outlier tolerance in standard deviations. NOTE: neg_tol is the negative ( i. e. below the median ) outlier tolerance in standard deviations. | def Search(star, pos_tol=2.5, neg_tol=50., **ps_kwargs):
'''
NOTE: `pos_tol` is the positive (i.e., above the median)
outlier tolerance in standard deviations.
NOTE: `neg_tol` is the negative (i.e., below the median)
outlier tolerance in standard deviations.
'''
# Smooth the light curve
... |
Ordered iterator over dirty elements. | def iterdirty(self):
'''Ordered iterator over dirty elements.'''
return iter(chain(itervalues(self._new), itervalues(self._modified))) |
Add a new instance to this: class: SessionModel.: param modified: Optional flag indicating if the instance has been modified. By default its value is True.: param force_update: if instance is persistent it forces an update of the data rather than a full replacement. This is used by the: meth: insert_update_replace meth... | def add(self, instance, modified=True, persistent=None,
force_update=False):
'''Add a new instance to this :class:`SessionModel`.
:param modified: Optional flag indicating if the ``instance`` has been
modified. By default its value is ``True``.
:param force_update: if ``instance`` is pers... |
delete an * instance * | def delete(self, instance, session):
'''delete an *instance*'''
if instance._meta.type == 'structure':
return self._delete_structure(instance)
inst = self.pop(instance)
instance = inst if inst is not None else instance
if instance is not None:
state... |
Remove instance from the: class: SessionModel. Instance could be a: class: Model or an id.: parameter instance: a: class: Model or an id.: rtype: the: class: Model removed from session or None if it was not in the session. | def pop(self, instance):
'''Remove ``instance`` from the :class:`SessionModel`. Instance
could be a :class:`Model` or an id.
:parameter instance: a :class:`Model` or an ``id``.
:rtype: the :class:`Model` removed from session or ``None`` if
it was not in the session.
'''
if isinstance(instan... |
Remove * instance * from the: class: Session. Instance could be a: class: Model or an id.: parameter instance: a: class: Model or an * id *: rtype: the: class: Model removed from session or None if it was not in the session. | def expunge(self, instance):
'''Remove *instance* from the :class:`Session`. Instance could be a
:class:`Model` or an id.
:parameter instance: a :class:`Model` or an *id*
:rtype: the :class:`Model` removed from session or ``None`` if
it was not in the session.
'''
instance = self.pop(instan... |
\ Process results after a commit.: parameter results: iterator over: class: stdnet. instance_session_result items.: rtype: a two elements tuple containing a list of instances saved and a list of ids of instances deleted. | def post_commit(self, results):
'''\
Process results after a commit.
:parameter results: iterator over :class:`stdnet.instance_session_result`
items.
:rtype: a two elements tuple containing a list of instances saved and
a list of ids of instances deleted.'''
tpy = self._meta.pk_to_pytho... |
Close the transaction and commit session to the backend. | def commit(self, callback=None):
'''Close the transaction and commit session to the backend.'''
if self.executed:
raise InvalidTransaction('Invalid operation. '
'Transaction already executed.')
session = self.session
self.session = N... |
The set of instances in this: class: Session which have been modified. | def dirty(self):
'''The set of instances in this :class:`Session` which have
been modified.'''
return frozenset(chain(*tuple((sm.dirty for sm
in itervalues(self._models))))) |
Begin a new: class: Transaction. If this: class: Session is already in a: ref: transactional state <transactional - state > an error will occur. It returns the: attr: transaction attribute. This method is mostly used within a with statement block:: with session. begin () as t: t. add (... )... which is equivalent to:: ... | def begin(self, **options):
'''Begin a new :class:`Transaction`. If this :class:`Session`
is already in a :ref:`transactional state <transactional-state>`,
an error will occur. It returns the :attr:`transaction` attribute.
This method is mostly used within a ``with`` statement block::
with session.... |
Create a new: class: Query for * model *. | def query(self, model, **kwargs):
'''Create a new :class:`Query` for *model*.'''
sm = self.model(model)
query_class = sm.manager.query_class or Query
return query_class(sm._meta, self, **kwargs) |
Update or create a new instance of model. This method can raise an exception if the kwargs dictionary contains field data that does not validate.: param model: a: class: StdModel: param kwargs: dictionary of parameters.: returns: A two elements tuple containing the instance and a boolean indicating if the instance was ... | def update_or_create(self, model, **kwargs):
'''Update or create a new instance of ``model``.
This method can raise an exception if the ``kwargs`` dictionary
contains field data that does not validate.
:param model: a :class:`StdModel`
:param kwargs: dictionary of parame... |
Add an instance to the session. If the session is not in a: ref: transactional state <transactional - state > this operation commits changes to the back - end server immediately.: parameter instance: a: class: Model instance. It must be registered with the: attr: router which created this: class: Session.: parameter mo... | def add(self, instance, modified=True, **params):
'''Add an ``instance`` to the session.
If the session is not in a
:ref:`transactional state <transactional-state>`, this operation
commits changes to the back-end server immediately.
:parameter instance: a :class:`Model` ... |
Delete an instance or a query. Adds instance_or_query to this: class: Session list of data to be deleted. If the session is not in a: ref: transactional state <transactional - state > this operation commits changes to the backend server immediately.: parameter instance_or_query: a: class: Model instance or a: class: Qu... | def delete(self, instance_or_query):
'''Delete an ``instance`` or a ``query``.
Adds ``instance_or_query`` to this :class:`Session` list
of data to be deleted. If the session is not in a
:ref:`transactional state <transactional-state>`, this operation
commits changes to the... |
Returns the: class: SessionModel for model which can be: class: Model or a: class: MetaClass or an instance of: class: Model. | def model(self, model, create=True):
'''Returns the :class:`SessionModel` for ``model`` which
can be :class:`Model`, or a :class:`MetaClass`, or an instance
of :class:`Model`.'''
manager = self.manager(model)
sm = self._models.get(manager)
if sm is None and create:
sm ... |
Remove instance from this: class: Session. If instance is not given it removes all instances from this: class: Session. | def expunge(self, instance=None):
'''Remove ``instance`` from this :class:`Session`. If ``instance``
is not given, it removes all instances from this :class:`Session`.'''
if instance is not None:
sm = self._models.get(instance._meta)
if sm:
return sm.expunge... |
Retrieve the: class: Manager for model which can be any of the values valid for the: meth: model method. | def manager(self, model):
'''Retrieve the :class:`Manager` for ``model`` which can be any of the
values valid for the :meth:`model` method.'''
try:
return self.router[model]
except KeyError:
meta = getattr(model, '_meta', model)
if meta.type == 'structu... |
Create a new instance of: attr: model and commit it to the backend server. This a shortcut method for the more verbose:: instance = manager. session (). add ( MyModel ( ** kwargs )) | def new(self, *args, **kwargs):
'''Create a new instance of :attr:`model` and commit it to the backend
server. This a shortcut method for the more verbose::
instance = manager.session().add(MyModel(**kwargs))
'''
return self.session().add(self.model(*args, **kwargs)) |
Returns a new: class: Query for: attr: Manager. model. | def query(self, session=None):
'''Returns a new :class:`Query` for :attr:`Manager.model`.'''
if session is None or session.router is not self.router:
session = self.session()
return session.query(self.model) |
Returns a new: class: Query for: attr: Manager. model with a full text search value. | def search(self, text, lookup=None):
'''Returns a new :class:`Query` for :attr:`Manager.model` with
a full text search value.'''
return self.query().search(text, lookup=lookup) |
Create a dict given a list of key/ value pairs | def pairs_to_dict(response, encoding):
"Create a dict given a list of key/value pairs"
it = iter(response)
return dict(((k.decode(encoding), v) for k, v in zip(it, it))) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.